views:

237

answers:

4

Suppose we have the ff. in a.html:

<script>
  function onClick() {
    // Do some important stuff and then...
    location = "b.html";
  }
</script>
<a href="#" onclick="onClick();">Link</a>

Double-clicking on Link will trigger the event-handler onClick. However, the second click in the double-click seems to be interpreted as another click and causes the page to jump to the named anchor. In effect, the location isn't changed.

My questions are:

  1. Is this a browser bug or feature?

  2. Is there a way to work-around this behavior?

+1  A: 

You could try

href="javascript:void(0);"

instead

Ganesh Shankar
Side-effect: Link is never marked as visited but, since they're skinned to look like buttons, this is OK.
Chry Cheng
+1  A: 

Use window.location = "b.html". location by itself has no special meaning.

The anchor jumping is unrelated. You can disable it by stopping the event.

function onClick(event) {
  event.preventDefault();
  event.stopPropagation();
}

<a href="#" onclick="onClick(event)">Link</a>
August Lilleaas
Did not work :(
Chry Cheng
`window` is the global object. Which means `location` is available in the global scope when written by itself. It's the same thing as `window.location`. That's why you can also do `window.window.window.location` if you like. You're actually doing the same thing for `event` in your code. It lives in the global scope and can therefore be accessed using `window.event`.Also, your answer is missing the `return false;` variant for older browsers, and `onclick="return onClick(event);"`.
Blixt
A: 

gshankar is right

Another variant:

<script>
  function onClick() {
    location = "b.html";
    return false;
  }
</script>
<a href="#" onclick="return onClick();">Link</a>
x2
Doesn't work as well :(
Chry Cheng
A: 

Or you can point the link at the function and skip the onclick event:

<script>
  function onClick() {
    location = "b.html";
    return false;
  }
</script>
<a href="javascript:onClick();">Link</a>
Johan Öbrink
Didn't mention that I'm fixing a custom tag. User's may want to use "this" in their click handlers. I think "this" means something else when in the "href" attrib.
Chry Cheng