0

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?

3
  • 2
    May I ask what is the point of this? (By the way to disable the effect of href just do e.preventDefault() or even return false) Commented Apr 20, 2014 at 20:53
  • Sorry, the effect is not as it should be. When I use the link javascript is not detected. So even with javascript enabled it doesn't work because the href has a url in it. Commented Apr 20, 2014 at 20:54
  • I don't quite understand what do you mean but here is a demo: jsfiddle.net/DerekL/5bAfg Commented Apr 20, 2014 at 20:57

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.