Horai Nuri
Horai Nuri

Reputation: 5578

How to use $(this) with jquery to change an element that is on the parent of a div?

I'm trying to do a simple thing with JQuery but I struggle to understand what I should do.

What I'd like to do is when .overlay-detail is hovered $(this).closest('p img:first-child').css('display', 'none') else ('display', 'block')

(see html to understand)

<div id="block-views-quipe-block">

<div class="field-content">
   <p>
     <img alt="" src="/sites/default/files/_CA17330lr.jpg">
     <img alt="" src="/sites/default/files/_CA17322lr.jpg">
   </p>

   <div class="overlay-detail">
     <p>John Doe 1</p>
     <p>job 1</p>
   </div>
</div>  

<div class="field-content">
   <p>
     <img alt="" src="/sites/default/files/_CA17330lr.jpg">
     <img alt="" src="/sites/default/files/_CA17322lr.jpg">
   </p>

   <div class="overlay-detail">
     <p>John Doe 2</p>
     <p>job 2</p>
   </div>
</div>  

...

</div>

Here is what I thought doing :

$("#block-views-quipe-block .overlay-detail").hover(function(){
  $(this).closest('p img:first-child').css("display", "none");
}, function(){
   $(this).closest('p img:nth-child(2)').css("display", "block");
});

What am I doing wrong ?

Upvotes: 1

Views: 39

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337580

The issue is because closest() looks for parent elements, whereas the p is a sibling. Use prev() instead to get the p, then find() to get the child img:

$("#block-views-quipe-block .overlay-detail").hover(function(){
  $(this).prev('p').find('img:first-child').hide();
}, function(){
  $(this).prev('p').find('img:nth-child(2)').show();
});

Upvotes: 5

Related Questions