Javascript href Voids and More
Posted on : 07-07-2009 | By : chelfers | In : HTML, Javascript, Web
2
- If you are a web developer raise your hand. *raises hand*
- If you have ever referenced Javascript for a link address raise your hand. *raises hand*
I'm sure there are many guilty developers out in the wild who use the age old classic
A basic explanation is this little call tells the browser to call the function provided after "javascript:" when the link is clicked. Great, so we have an easy way to call a function using a link! What if I wanted the user to click the link and have the page do nothing? Easy!
Awesome! Now when the user clicks the link the browser interprets void(0) as stop right there, don't do a thing. The problem is "javascript:" wasn't exactly meant for this sort of use and some quirky stuff can happen ( obviously the keyword is there for a reason, but that does not make it a good one).
So what is the solution? Our trusty old pound sign, an onclick trigger, and of course a tiny bit of Javascript.
This will give the same end result as using void(0) and it is the correct way supported by all major browsers; hell some browsers specifically state to avoid "javascript:" in any link addresses, but this is the web, who sticks to standards?
If you really want to be anal about the whole thing and want to argue about Javascript being enabled on the browser ( which you should be sniffing for anyways if you really care that much ) you could do the following.
This will take the user to the page set by the href if and only if Javascript is disabled, but then I ask myself why not just push them to that page as the default?
Anyway, here is an example showing the bad and better ways of doing this for those that might need a side by side.
<script type="text/javascript"> function Testing(){ alert('hio'); } </script> //BAD <a href="javascript:Testing();">Click Here</a> //Better <a href="#" onclick="Testing(); return false;">Click Here</a> //BAD <a href="javascript:void(0);">Click Here</a> //Better <a href="#" onclick="return false;">Click Here</a>
Hope everyone had a good 4th of July weekend!



