Question

I have some hyperlinks with onclicks. These hyperlinks load content from another page into a div.

The hyperlink looks like this:

<a href="http://www.page2.html" onclick="gotopage2();">page 2</a>

and the code I have in my head section is:

<script type="text/javascript">
function gotopage2(){
  window.location("page2.html");
}

But this doesn't work as I'd like it to. What I would like to do is:

If JavaScript is enabled, use the onclick.
If Javasccript is disabled, use the href.

the problem is, putting a # in the href will allow the javascript to be executed - but then if javascript is disabled, i won't have any way to put the url in the href!

I don't want to have to go fetch all hyperlinks on a page on document load and take away the href's and I don't like using many . Isn't there a better way to do this?

Was it helpful?

Solution

Cancel the default action of the link.

If you are using intrinsic event attributes, return false from them.

onclick="gotopage2(); return false;"

If you are writing modern code, call preventDefault on the event object.

<a href="http://www.page2.html">page 2</a>

<script>
function goToPage(evt) {
    evt.preventDefault();
    window.location = this.href;
}
document.querySelector('a').addEventListener('click', goToPage);
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top