views:

61

answers:

1

I though returning false would be enough to cancel the link action, but apparently it isn't. When I click the link in the code below I do get the 'click' message, which is expected. But I also end up at google.com, which is unexpected.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head>
    <title>Link test</title>
    <script>
        window.addEventListener('load', function () {
            document.getElementsByTagName('a')[0].addEventListener('click', function () {
                alert('click');
                return false;
            }, false);
        }, false);
    </script>
</head>
<body>
    <a href="http://www.google.com"&gt;google&lt;/a&gt;
</body>
</html>

How can I make the url NOT change when clicking the link? Pure JavaScript solutions only please, no additional libraries (like jQuery). It only has to work in FireFox 3+ and Chrome.

A: 

If you don't want the url on on the anchor to change the location you can try the following

document.getElementsByTagName('a')[0].addEventListener('click', function (e) {
            alert('click');
            e=e¦¦event; 
            e.preventDefault? e.preventDefault() : e.returnValue = false; 
        }, false);
andreas
Thanks for the very quick answer! I'm guessing you've got some cross-browser things happening there. You care to point them out? (i.e. what browser doesn't pass 'e' to the function etc.)
Tobbe