href="#" is forcing the page to reposition itself to the top - how can I stop this? [duplicate]
Possible Duplicate:
How do I stop a web page from scrolling to the top when a link is clicked that triggers javascript?
When I click on a date of a jQuery datepicker on my web page, my page repositions itself to the top because the date on the datepicker has an href="#"
attribute.
It seems that whenever I click an <a>
element that has href="#"
then my page reorientates iteself to display from the top of the page. This is pretty annoying because the user is开发者_JS百科 having to cope with the page moving about and may even have to scroll just to see the part of the page they were using before they clicked. Can anyone tell me how I can stop this from happening?
I can take the href
attribute from some of my links, but jQuery widgets often have them in.
Many thanks
Usually when a link has href="#"
, it's because it's supposed to do something other than navigating (the exception being "To the top" links seen on some long pages...). The "other thing" they're doing is usually handled via JavaScript, and to make sure that they don't continue to their default handler (i.e. navigate) the JS handler should return false.
If you make sure that all your click handlers return false, you won't have this problem anymore.
If you're using jQuery to hook up your events, you could also call .preventDefault()
and .stopPropagation()
on the first argument to the click handler function. This will do it on it's own in most browsers, but you should still return false for compatibility.
$('.someLink').click(function(ev) {
// do your thing
// Prevent the click from being handled.
ev.preventDefault();
// Prevent the event from propagating through the DOM tree (bubbling)
ev.stopPropagation();
// Return false, for compatibility reasons
return false;
});
Note: If there are click handlers in some library you're using that doesn't return false, you can always wrap it in a handler function of your own that does. But I'd consider abandoning that library...
You can do it by doing this:
<a href="#" onclick="return false;">Click me</a>
This should work and avoid dealing with the url hash:
<a href="javascript:void(0);">Click me</a>
When using jQuery you can take advantage of the event.preventDefault()
function such as:
$("a").click(function(event) {
event.preventDefault();
alert('Will not jump to top of page after alert');
});
http://api.jquery.com/event.preventDefault/
Use preventDefault
method of the event object to avoid this or just return false from the click handler.
$("a").click(function(e){
e.preventDefault();
});
You can also just not use href="#"
and set cursor: pointer;
in css
write some jQuery like this
jQuery('a[href=#]').attr('href','javascript:void(null);');
精彩评论