João Costa
João Costa

Reputation: 519

Jquery mouseenter and mouseout animation

Im trying to do an event on mouseenter and mouseout. If i put mouseover more than one time it will repeat the number of times i did it, even if still on first animation. Im also trying to stop the animation on mouseleave and animate it back. Thanks in advance

Here's the javascript

$('.velejador').mouseenter(function(){
    $('.velejador').animate({
        left: '-=50',
        width: '40px'
      }, 2000);
}).mouseleave(function(){
    $('.velejador').animate({
        left: '+=50',
        width: '40px'
      }, 2000);
});

Here the html

<div id="hidden-cartoons">
    <img src="<?php echo base_url().'assets/img/cartoons/velejador.png' ?>" class="cartoon velejador">
    <img src="<?php echo base_url().'assets/img/cartoons/bodoleite.png' ?>" class="cartoon bodoleite">
</div>

Upvotes: 1

Views: 167

Answers (3)

Hasib Tarafder
Hasib Tarafder

Reputation: 5813

You can try this..

var velejador = $('.velejador');
var position = velejador.position();
velejador.mouseenter(function(){
    var $this = $(this);
    console.log(position);
    $this.css('left',position.left);
    $this.stop(1,0).animate({
        left: '-=50',
        width: '40px'
      }, 2000,function(){
        $this.stop(1,0).animate({
            left: '+=50',
            width: '40px'
        }, 2000);
      });       
});

Upvotes: 3

Matt Burland
Matt Burland

Reputation: 45135

What you are looking for is .stop()

Try this fiddle

Two things, I've used stop to cancel any currently running animation. Second, I've replaced the '+=50' and '-=50' with absolute values because without those, if you keep mousing in and out, the div will end up moving further and further across the screen, which I assume isn't your objective.

Another thing to remember is, when do an animation on mouseenter that moves or resizes the element, you may potentially end up firing the mouseout event unless the user "chases" the element as you move it.

Upvotes: 2

pmandell
pmandell

Reputation: 4328

$('.velejador').mouseover(function() {
    $('.velejador').animate({
        left: '-=50',
        width: '40px'
    }, 2000);
}).mouseout(function() {
    $('.velejador').animate({
        left: '+=50',
        width: '40px'
    }, 2000).stop();
});

Depending on where the image is on "mouseout", you might want to use .css() to return the image to the original position.

Upvotes: 2

Related Questions