Question

I have the following code which is supposed to stop anything from happening when you click a link except for firing and alert. The link destination is cancelled, but clicking the link scrolls you up to the top of the page. How can I stop this behaviour? Thanks

$('a#target').click(function(event){
    event.preventDefault();
    alert('End of demo');
});

UPDATE my link looks like this:

<a href="#">Submit</a>
Was it helpful?

Solution

No, preventDefault is not supposed to stop anything, it's supposed to do exactly what it says - prevent the default action. i.e. If you click on a link with an href, it will prevent the default action of the browser which is to go to that link.

If you want to stop all other events attached to that link, you must return false at the end of the event handler AND make sure that that event handler is executed before any others.

UPDATE:

Thanks for posting the link and the href value. I'll bet that what is happening is that JavaScript encounters an error before that click handler can ever get fired. As the first comment on this answer correctly indicates - preventDefault should prevent the link from jumping to anchors within the page as well. If it's not, doing it's job, then it's probably because there's a JavaScript error elsewhere on the page.

All this being said, are you sure you posted the correct HTML?

$('a#target').click(...

Attached a click handler to a link that looks like this:

<a href="#" id="target">Submit</a>

And one final thought - if an anchor element only has action(s) attached to it via JavaScript, then why specify the option href attribute at all?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top