Rachel Nicolas
Rachel Nicolas

Reputation: 1155

jQuery: style hover on parents() and children()

I am wondering if it is possible to change the style of child when its element was hovered, while its css was also styled when its parent was hovered?

To make my question clear, I wrote down a basic code below:

   //styling child while mouse is inside child element
$('child').on('hover', function(e){
   if (e.type == 'mouseenter'){
      $(this).css('background','yellow');
   }
})

   // styling child while mouse is inside parent
$('child').parents().on('hover', function (e){
   if (e.type == 'mouseenter'){
      $(this).css('background', 'blue');
   }
})

So, basically once user enters space of parent to make child's bg blue, and once it enters space of child to change from blue to yellow bg.


I saw a comment on why I do not use css, so this is a little explanation: I am unable to select parent element. I can only do it from child using parents(). And as long as css does not support parents() method yet I went with jquery. :)

Upvotes: 3

Views: 3666

Answers (2)

scraaappy
scraaappy

Reputation: 2886

is that the behaviour you expect ?

$('#child').parent().on('mouseover', function(e){
  if(this===e.target){
    $(this).children().css('background','blue');
  }else{
    $(this).children().css('background','yellow');
  }
}).on('mouseout', function(e){      
    $(this).children().css('background', 'green');
});
#parent{
  width:200px;
  height:100px;
  background-color:#f00;
}

#child{
  width:30px;
  height:30px;
  background-color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <div id="child"></div>
</div>

Upvotes: 2

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

CSS Alone:

div {
  padding: 20px;
  border: 1px solid black;
}

/* something hovered that have .child as direct child => change .child color to blue */
*:hover > .child {
  background-color: blue;
}

/* .child element hovered => override the above color and set it to yellow (note that the above rule is still taking effect when this is taking effect) */
.child:hover {
  background-color: yellow;
}
<div>
  PARENT
  <div class="child">CHILD</div>
</div>
<div>
  PARENT
  <div class="child">CHILD</div>
</div>
<div>
  PARENT
  <div class="child">CHILD</div>
</div>

Upvotes: 2

Related Questions