Use normal href if Javascript is disabled
Posted June 12th, 2008 in Javascript
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.
Related posts:
- Loop through key value pairs from an associative array with Javascript (Friday, April 3rd 2009)
- Assigning values to associative arrays in Javascript (Sunday, December 30th 2007)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.
