Search code examples
javascripthtmldom-eventshrefonmousedown

Html onmousedown vs href Precedence


I use the following code in one of my html pages. When user clicks "Search Engines" links it opens yahoo.com on a new page and Google on current page.

I've tested this and it works (opens both urls), but is there any chance that the page will complete the window.location (redirect to a different page) without completing the href command?

Is there a rule for Precedence between the two command?

**Note: I know I can solve the problem in different ways, but I'm curious about this specific situation.

<html>
<head>
    <title></title>

<script type="text/javascript">
    function clickRedirect() {
        window.location = 'http://www.google.com';
    }
</script>
<body>

<a onmousedown="clickRedirect()" href="http://www.yahoo.com" target="_blank">Search Engines</a>
</body>
</html>

Solution

  • The mousedown event will happen first, but as you can see from the fact your code is currently working, that's not the whole story.

    The question is: Once the mousedown has happened and you've set window.location, does the page get whisked away immediately (and therefore processing of the default action of the click on the a element doesn't happen), or does that default action get completed before the page is destroyed and replaced with the new page?

    The answer is: I don't think that's guaranteed behavior at all (either way), and I wouldn't rely on it cross-browser. For one thing, what if the user holds down the mouse button? Since the default action of an a element isn't triggered until a click, which requires a mouseup.

    Instead, I'd probably hedge my bets, in two ways:

    First, I'd use click, not mousedown, for this. Users don't expect pages to swap out when they just hold the mouse down.

    Second, I'd change your function:

    function clickRedirect() {
        setTimeout(function() {
            window.location = "http://www.google.com";
        }, 0);
    }
    

    Now you're specifically giving the browser a chance to complete the default action of the click before you go off to another page.

    You might find more information on this buried deep in the DOM events specifications:

    ...in that they might say something about what should happen when an event is in progress and the page is being destroyed. I didn't immediately see anything.