Reputation: 21934
I have a link
<a href="#">has a jQuery click handler</a>
My jQuery works the way it's supposed to...however the hash # tag is making my browser jump to the top of the page on every click.
Is there any way to get around this? I tried removing the # but it changes my css styling.
Upvotes: 1
Views: 130
Reputation: 10077
You should add a return false;
to the end of your click handler if you want to resolve the issue quick and dirty.
However, return false forces you to exit and virtually stops event propagation. Since you are using the jquery javascript library, you also have the option of using the preventDefault()
method instead, which removes the default action and allows the function to keep runnning.
Upvotes: 6
Reputation: 2726
To reiterate the comments above, which are correct, add a return false to the click handler. This would look like:
$('.link').click(function(){
... things to run on click ...
return false;
});
Upvotes: 1
Reputation: 29658
You can also use javascript: void false;
instead of #
. So:
<a href="javascript: void false;">has a jQuery click handler</a>
Upvotes: 1
Reputation: 20404
return false
or call eventHandler.preventDefault()
on onclick
event:
$('#yourLink').click(function() {
return false;
});
or
$('#yourLink').click(function(e) {
e.preventDefault();
});
or change the href
to:
<a href="javascript:void(0);">has a jQuery click handler</a>
Upvotes: 0
Reputation: 37516
Your click handler should either return false;
or call preventDefault() on the event object.
Example:
$('your selector').click(function(e) /* note the parameter e */
{
e.preventDefault();
//your code
});
Upvotes: 5