dwilbank
dwilbank

Reputation: 2520

Confusion with on() method

doing my lessons on codeschool, the following does not work

$(document).ready(function() { 
  $("#tour").on("click", "button", function() { 
    $(".photos").slideToggle();
  });
    $(".photos").on("mouseenter", "li", function() {
    $(this).find("span").slideToggle();

    $(".photos").on("mouseleave", "li", function() {
    $(this).find("span").slideToggle();
    });
  });
});

while the following is apparently correct.

$(document).ready(function() { 
  $("#tour").on("click", "button", function() { 
    $(".photos").slideToggle();
  });
  $(".photos").on("mouseenter", "li", function() {
    $(this).find("span").slideToggle();

  })          .on("mouseleave", "li", function() {
    $(this).find("span").slideToggle();
  });
});

It looks to me as though they're simply taking a shortcut by leaving out the second $(".photos"). I can see how it might be inefficient to call something twice like that, but it's actually an error as well?

Upvotes: 2

Views: 40

Answers (1)

Ram
Ram

Reputation: 144659

No, this is not an error, the problem is you are attaching a new mouseleave event handler on each mouseenter event.

$(".photos").on("mouseenter", "li", function() {
    $(this).find("span").slideToggle();

    // Here
    $(".photos").on("mouseleave", "li", function() {
        $(this).find("span").slideToggle();
    });
});

For minifying the code you can pass an object to the on method:

$(".photos").on({
   mouseenter: function() {
      $(this).find("span").slideToggle();
   },
   mouseleave: function() {
      $(this).find("span").slideToggle();
   }
}, 'li');

Upvotes: 3

Related Questions