0

I have multiple divs as such:

<div class="hover-effect">
   <div class="hover-effect">
      <div class="hover-effect">
         <div class="hover-effect"></div>
      </div>
   </div>
</div>
<div class="hover-effect">
    <div class="hover-effect"></div>
</div>
<div class="hover-effect"></div>
<div class="hover-effect"></div>

And I'm trying to accomplish a hover effect on only the deepest element if it is the one being hovered. Currently it also applies the effect to the parent elements. How would I go by avoiding this?

3 Answers3

0

I think it will be possible using Javascript

see this : https://jsfiddle.net/eszujrwm/

$(".hover-effect").each(function(){
    if( $(this).find(".hover-effect").length == 0 ){
        $(this).mouseenter(function() {
        $(this).addClass("hovered");
    }).mouseleave(function() {
         $(this).removeClass("hovered");
    });
    }
})

This code selects all .hover-effect elements, and for every one of them see if it have a child with class "hover-effect" if no It's the deepest element so we add a mouseenter/leave event

In CSS, we define a class "hovered" which contains style for onhover:

.hovered{
    background-color:green;
}
Elheni Mokhles
  • 3,801
  • 2
  • 12
  • 17
0

There was topic about deepest element here

Following this answer, Gerald Fullman wrote jQuery plugin called .deepest which, i think, can help you.

I can't test it right now, but i think it will be like:

$(dokument).ready(function() {
  $('.hover-effect').mouseover(function() {
    $(this).deepest('.hover-effect'); // ...
  });
});

Try to avoid use stopPropagation, because of potential problems. Read more here

Community
  • 1
  • 1
jacqbus
  • 457
  • 3
  • 13
0

You can use :not(), :has() to select element which do not have a specific selector as a child node

$(".hover-effect:not(:has(.hover-effect))")
.hover(function() {
  $(this).toggleClass("deepest")
});
.deepest {
  background:purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hover-effect">
  not deepest
   <div class="hover-effect">
     not deepest
      <div class="hover-effect">
        not deepest
         <div class="hover-effect">deepest</div>
      </div>
   </div>
</div>
<div class="hover-effect">
  not deepest
    <div class="hover-effect">deepest</div>
</div>
<div class="hover-effect">deepest</div>
<div class="hover-effect">deepest</div>
guest271314
  • 1
  • 15
  • 104
  • 177