I'm using animate() to animate the DIV tag to the left when the pointer is over the DIV. And when the pointer leaves the DIV tag it animates back to it's original position. The problem here is that the animation moves the DIV tag 50 pixels to the left on mouse over and 50 pixels to the right on mouse leave.
This makes the DIV to move 50 pixels to the right even if the animation is not completed.
$('body').on('mouseenter', '.image-photo-previous', function() {
$(this).animate({marginLeft: '-=50px'}, 300, 'swing');
});
$('body').on('mouseleave', '.image-photo-previous', function() {
$(this).animate({marginLeft: '+=50px'}, {queue: false}, 300, 'swing');
});
http://jsfiddle.net/edgren/CubZy/
How can I make the DIV tag to animate back to its original position even if the animation is not complete on mouse leave?
(Without JS!) You can do it using CSS3 transition:
DEMO (CSS only)
.image-photo-previous {
background-color: #222222;
height: 100px;
width: 200px;
transition: 0.3s; /* Transition! */
}
.image-photo-previous:hover{
margin-left: -50px;
}
Using jQuery:
LIVE DEMO
$(".image-photo-previous").on('mouseenter mouseleave', function( e ) {
$(this).stop().animate({marginLeft: e.type=="mouseenter"?-50:0}, 300);
});
The .stop() method will prevent some ugly animations buildups, and with a bit of Ternary Operator (?:) you're on the right way.
Your example does not suit your needs cause at any new event you were messing with some new added margin calculations (to un-ended animations) due to += and -= that were added to the current DIV style, resulting in incorrect element positions specially on fast mousemovements. stop() clears that behavior and all you need is to strictly define the positions: -50 and 0 and bound them to the current event.
Try this:
$(document).ready(function() {
$('body').on('mouseenter', '.image-photo-previous', function() {
$(this).stop(true,true).animate({marginLeft: '-=50px'}, 300, 'swing');
});
$('body').on('mouseleave', '.image-photo-previous', function() {
$(this).stop(true,true).animate({marginLeft: '+=50px'}, {queue: false}, 300, 'swing');
});
});
Read more about .stop(): http://api.jquery.com/stop/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With