Joe Morano
Joe Morano

Reputation: 1895

Jquery: Why isn't timer being cancelled on mouseleave?

I wrote some code for a jquery event to be triggered after a delay when a div is mouseentered, but cancelled if the mouse leaves the div during the delay. That code worked perfectly, but I tried to apply the same code format to another jquery event, and that event doesn't cancel if my mouse leaves the div during the delay. Here's my new code that doesn't work:

<div class="expander"><%=image_tag("BigCircle2.jpg")%></div>
<script type="text/javascript">
  $(".expander").on('mouseenter', function () {
    $.data(".expander", 'timer', setTimeout(function() {
      $(".expander").stop(true, true).animate({width: "150%"}, 270, function() {
      });
    }, 400));
  }).on('mouseleave', function() {
    clearTimeout($.data(".expander", 'timer'));
    $(".expander").stop(true, true).animate({width: "100%"}, 270, function() {
    });
  });
  $(".expander").mouseleave(function () {
    $(".expander").animate({width: "100%"}, 270, function() {
    });
  });
</script>

The issue is that the mouseenter event isn't cancelled if the mouse leaves .expander during the 400 delay. Does anyone see what is wrong with my code?


This is the initial code I had that executed flawlessly:

<script type="text/javascript">
  $("#top").hide();
  $("#con").on('mouseenter', function () {
    $.data(this, 'timer', setTimeout(function() {
      $('#top').stop(true, true).fadeIn("fast");
    }, 400));
  }).on('mouseleave', function() {
    clearTimeout($.data(this, 'timer'));
    $('#top').stop(true, true).fadeOut('fast');
  });
  $("#con").mouseleave(function () {
    $('#top').fadeOut("fast");
  });
</script>

Upvotes: 0

Views: 80

Answers (1)

Mottie
Mottie

Reputation: 86483

jQuery's $.data() requires a DOM object... the new code is using a string selector.

$.data(".expander")

change that to this or just don't use $.data()

Update: by "don't use $.data()" I meant this:

var timer;
$(".expander").on('mouseenter', function () {
    timer = setTimeout(function() {
        $(".expander").stop(true, true).animate({width: "150%"}, 270, function() {
        });
    }, 400);
}).on('mouseleave', function() {
    clearTimeout(timer);
    $(".expander").stop(true, true).animate({width: "100%"}, 270, function() {});
});
$(".expander").mouseleave(function () {
    $(".expander").animate({width: "100%"}, 270, function() {});
});

Upvotes: 1

Related Questions