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?
I’ll assume that the
.galleryButtonLeftelement(s) is/are links with theirhrefattribute set to a hash (#). Eitherreturn falseorevent.preventDefault()to cancel the default behavior of the link(s):Returning
falseinside of a jQuery event handler is the same thing as callingevent.preventDefault()andevent.stopPropagation().If you want to use
event.preventDefault()instead of returningfalsethen you have to pass-in theeventobject in your anonymous function (event handler):Notice that you can call
event.preventDefault()anywhere in the event handler, however returningfalsehas to be the last thing called because it will stop the execution of the event handler.