I saw a post on a bulletin board somewhere recently where the poster asked how to make the href work normally on a link like this <a href=”javascript:;” onclick=”dosomething()”> if Javascript is not enabled. It’s actually quite simple and I will look at how to do this in this post.
To make the browser go to e.g. otherpage.html if Javascript is not enabled, and instead execute the Javascript and don’t go to that page if Javascript is enabled, set the href to otherpage.html and return false from the Javascript function as shown in the code snippet below.
<a href="otherpage.html" onclick="return dosomething()">link</a> <script language="javascript"> function dosomething() { ... code here ... return false; } </script>
The important thing to remember is the onclick needs to have “return” before the function call and the function must return false. If you still wanted the browser to go to otherpage.html after the function call you can simply leave out the return portions, or return true.
This also means you can conditionally allow the browser to go to otherpage.html by returning true or false depending on the condition. For example, you (wouldn’t really want to do this example but you) could prompt the user to see if they really do want to go to that link. If Javascript is disabled clicking it will simply take them there anyway.
<a href="otherpage.html" onclick="return dosomething(this)">link</a> <script language="javascript"> function dosomething(a) { return window.confirm('Go to ' + a.href + '?'); } </script
Another time I’ll look at how to manipulate the <a> tags in a page with conventional Javascript and also with jQuery. I do this on this site with conventional Javascript to track outbound links; without Javascript they are regular links but after the page has loaded they convert to trackable links.