Home > Software design >  How to add a hover event handler in JQuery, that will just target sibling elements with the same par
How to add a hover event handler in JQuery, that will just target sibling elements with the same par

Time:11-03

how to make hover over one div to trigger changes in another div, but not to affect to another div with Jquery. Here is example

I know for this option but It's not working for me

    $(function() {
  $(".single-holder-image").hover(function() {
    $(".read-more-a-black", this).css('color', '#a2d0ba');
  }, function() {
    // on mouseout, reset the background colour
    $(".read-more-a-black", this).css('color', '');
  });
});

maybe I need to change html structure

<div class="big-holder">

  <div class="single-post-holder">
  <a class="" href="#">
    <div class="single-holder-image">
       <img src="https://i.picsum.photos/id/717/200/300.jpg?hmac=OJYQhMLNcYlN5qz8IR345SJ7t6A0vyHzT_RdMxO4dSc" alt="">
    </div>
  </a>
  <div class="description-holder">
    <p class="category name "></p>
    <a class="read-more-a-black" href="#"><h5>Title 2</h5></a>
    <a class="read-more-a-black-p" href="#">lorem test test test test</a>
    <div class="pdf-holder">
      <p>Tools:</p>
    </div>
  </div>
</div>

  <div class="single-post-holder">
  <a class="" href="#">
    <div class="single-holder-image">
       <img src="https://i.picsum.photos/id/717/200/300.jpg?hmac=OJYQhMLNcYlN5qz8IR345SJ7t6A0vyHzT_RdMxO4dSc" alt="">
    </div>
  </a>
  <div class="description-holder">
    <p class="category name "></p>
    <a class="read-more-a-black" href="#"><h5>Title 2</h5></a>
    <a class="read-more-a-black-p" href="#">lorem test test test test</a>
    <div class="pdf-holder">
      <p>Tools:</p>
    </div>
  </div>
</div>


</div>

Also, will I be able to do the same when the mouse is hover over the title to trigger image and gets a transform: scale?

CodePudding user response:

Use $(this) in the .hover() event handler callback.

This way just the very element where the event occured will be selected.

After that some JQuery DOM traversing with .parents() and .find() and problem solved:

$(document).ready(function() {
  $(".single-holder-image").hover(function() {
    $(this).parents(".single-post-holder").find(".read-more-a-black").css('color', '#a2d0ba');
  }, function() {
    // on mouseout, reset the background colour
    $(this).parents(".single-post-holder").find(".read-more-a-black").css('color', '');
  });
});

  • Related