Monday, 23 November 2009

Hou do you get a hyperlink to run some code instead of linking to another location?

I was just working on a web page today and the design was such that there were multiple hyperlinks, two were to other pages but the third was a function to validate a portion of the current page. My problem was, how do I run some javascript instead of setting the anchor to another page?

I first tried to use an onclick handler without a url - now this did work but as a side effect of not having a url link the hyper link was not drawn showing the underline and coloring. So I added a url but of course the onclick functioned correctly but the page then navigated away.

Finally, and successfully, if you specify javascript:functionname() in the anchor href- where functionname() is defined in the script somewhere in your html document it works a charm. Additionally, after the javascript: you actually add multiple commands as long as they are semi-colon delimited. Obviously this can get a bit messy so better to have all the code in the function but the option is there!

No comments:

Post a Comment