Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in ".on" function in jquery

I have the following html file :

<div id="tour">
 <h2>Paris, France Tour</h2>
 <p>$2,499 for 7 Nights</p>
 <button>See photos from our last tour</button>
 <ul class="photos">
   <li>
   <img src="/assets/photos/paris1.jpg">
   <span>Arc de Triomphe</span>
   </li>
   <li>
  <img src="/assets/photos/paris2.jpg">
  <span>The Eiffel Tower</span>
  </li>
  <li>
  <img src="/assets/photos/paris3.jpg">
  <span>Notre Dame de Paris</span>
  </li>
 </ul>
</div>

This is my jQuery code :

function showPhotos()
{
    $(this).find("span").slideToggle();
}

$(document).ready(function() { 
    $("#tour").on("click", "button", function() { 
        $(".photos").slideToggle();
    });

    $(".photos").on("mouseenter", "li", showPhotos);
    $('.photos').on("mouseleave", "li", showPhotos);
});

This code works, it shows the span when mouse enters the img element . But when I try to do the same thing like so :

function showPhotos()
{
    $(this).find("span").slideToggle();
}

$(document).ready(function() { 
    $("#tour").on("click", "button", function() { 
        $(".photos").slideToggle();
    });
    $(".photos").on("mouseenter", "li", function() {
        showPhotos();
    });
    $('.photos').on("mouseleave", "li", function() {
        showPhotos();
    });
});

It doesn't work . With my limited knowledge, both codes seem to be doing the same thing. Please help me, How is the second code different from the first ?

like image 320
simha Avatar asked Apr 19 '26 15:04

simha


2 Answers

The second example doesn't have the this context in the showPhotos() function, you can pass the element as an argument:

function showPhotos(that)
{
    $(that).find("span").slideToggle();
}

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

Unlrelated to the question but a minor improvement would be to chain the mouseleave event, instead of re-selecting .photos again.

  $(".photos").on("mouseenter", "li", function() {
      showPhotos(this);
  }).on("mouseleave", "li", function() {
      showPhotos(this);
  });
like image 136
MrCode Avatar answered Apr 21 '26 05:04

MrCode


When you call the function showPhotos from within the anonymous function, 'this' does not refer to the element handling the event. So you'll either have to use the solution that MrCode has given or you can also use something like this:

$('.photos').on("mouseleave", "li", function() {
    showPhotos.apply(this,arguments);
});
like image 28
Dhruv Chandna Avatar answered Apr 21 '26 04:04

Dhruv Chandna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!