Reputation: 4417
I have a simple animation:
$(function () {
$(".galleryButtonLeft").mousedown(function(){
$("#theGallery").animate({
marginLeft: "-=300px",
}, 1000 );
});
});
theGallery is just a div
with position:relative
.
Nothing fancy:
<div style="position:relative">
<img/>
</div>
When I click my galleryButtonLeft to move it 300px
to the left, the page immediately goes to the top if I have my browser unmaximized and scroll to the middle of the page where my gallery sits. I want the page to stay where it is and not jump to the top everytime the button is clicked. How do I do that?
Upvotes: 0
Views: 166
Reputation: 75993
I'll assume that the .galleryButtonLeft
element(s) is/are links with their href
attribute set to a hash (#
). Either return false
or event.preventDefault()
to cancel the default behavior of the link(s):
$(function () {
$(".galleryButtonLeft").mousedown(function(){
$("#theGallery").animate({
marginLeft: "-=300px"//notice I removed the trailing comma here, it'll come back to haunt you if you don't (some browsers throw errors for these)
}, 1000 );
}).click(false);//this returns false for any click event for the/these element(s), stopping the default behavior of the element(s)
});
Returning false
inside of a jQuery event handler is the same thing as calling event.preventDefault()
and event.stopPropagation()
.
If you want to use event.preventDefault()
instead of returning false
then you have to pass-in the event
object in your anonymous function (event handler):
$(function () {
$(".galleryButtonLeft").mousedown(function(){
event.preventDefault();
$("#theGallery").animate({
marginLeft: "-=300px"//notice I removed the trailing comma here, it'll come back to haunt you if you don't (some browsers throw errors for these)
}, 1000 );
}).click(function (event) {
event.preventDefault();
});
});
Notice that you can call event.preventDefault()
anywhere in the event handler, however returning false
has to be the last thing called because it will stop the execution of the event handler.
Upvotes: 2
Reputation: 41533
how about adding
/*...*/mousedown(function(e){e.preventDefault(); /*...*/
or
$(".galleryButtonLeft").click(function(e){e.preventDefault();});
I think that the problem might be that your trigger (.galleryButtonLeft
) is an a element which has the href
property set to something starting with #
.This way, when you click the link, the hash in the browser bar changes, making the browser to jump up.
Upvotes: 2