How do I stop a link from changing the position on the page (maintain scroll back position)
I have an href tag with an image nested inside it and I want to be able stop the page jumping back to the top after it is clicked.
NOTE:
the href does not post back it fires a jQuery event on the page.
<a href="#" onclick="javascript:SendPlaylist()" style="border:开发者_JAVA技巧none;" class="addButton" ><img style="border:none;" src="/Images/icons/icon_add.gif"/></a>
Okay any help much appreciated.
Cheers, Pete
This should work:
$(".addButton").click(function(event) {
// Do your stuff here
event.preventDefault();
});
Hope this helps !
Why not just remove the anchor and add the onclick event to the image
like this:
<img style="border:none;cursor:pointer;" src="/Images/icons/icon_add.gif" onclick="javascript:SendPlaylist()"/>
the logical solution here would be:
<a href="#" onclick="SendPlaylist(); return false;" style="border:none;" class="addButton" ><img style="border:none;" src="/Images/icons/icon_add" onclick="javascript:SendPlaylist()"/></a>
you don't use the "javascript" keyword when using onclick... you can use it in the HREF itself, which would produce:
<a href="javascript:SendPlaylist(); return false;">
... and then you can remove the onclick part completely.
I also don't see a reason for another onclick for that img tag though - it can be removed altogether, since it would probably duplicate the call from that link
also, since you're saying that the link does not post back but uses a jQuery event, perhaps adding a "return false" to that event would work just as well as returning false in the onclick
The href="#" causes it to jump to the top, so logically speaking, in order to prevent that type of behavior, you should replace the 'a' tag with a span or something similar. The onclick should still work and unless SendPlaylist jumps to the top, it shouldn't change your scroll position.
Jumping between links on a page using anchors and more or less staying with the link in question see anyword2
<html>
<body>
<a href="#top">top</a>
<a href="#anylink">Jump to anylink</a>
<a name="anylink">TEXT</a>
<p> Top
<a href="#anylink2">Jump to anylink2</a>
<br><br><br><br><br>
<br><br><br><br><br>
<p> bottom
<a href="#bottom">Jump to Bottom</a>
<br><br><br><br><br><br><br><br>
<a href="#anylink2">Stay at link2</a>
<a name="anylink2">anylink 2 </a>
<a href="#bottom">Jump to Bottom</a>
<br><br><br><br><br<br><br<br><br
<br><br><br><br><br<br><br<br><br<br<br><br
<a name="bottom">You're at the bottom!</A>
<a href="#top">Jump to top</a>
</body>
</html>
The reason why the browser moves to the top, is that it attempts to find the anchor named "#".
You can remove the link tag altogether. Any element's onclick handler should be sufficient for your needs.
精彩评论