Alvarado87 Alvarado87 - 2 months ago 7
CSS Question

Hover two different elements

I have two elements that hover when you mouse over them independently, but I also want that when hovering the second element ("btn"), the first one ("i") also gets selected and hovers. There is more than one div, so it should work the same way in every div.

I have tried first with CSS using adjacent sibling selectors and then with the following jQuery statement (with some variations, but no result).

<div>
<p class="i">Ilumínate</p>
<h3>Web Development</h3>
<p>Professional custom e-commerce and web design...</p>
<a href="#" class="btn">Read more</a></div>


CSS

i{
font-size: 60px;
margin-left: 0;
-webkit-transition: color 0.8s;
transition: color 0.8s;
}

i:hover{
color: #1AC4F8
}

#services [class*="flaticon"]:hover{
color: #1AC4F8
}

.btn{
display: inline-block;
padding: 5px 10px;
border: 2px solid #1AC4F8;
color: #1AC4F8;
-webkit-transition: color 0.8s, background-color 0.8s;
transition: color 0.8s, background-color 0.8s
}

.btn:hover{
background-color: #1AC4F8;
color: #F2F2F2;
}


JQUERY

$('#btn').hover(function(){
$(this).prev('.i').css( "color", "#1AC4F8" ) });


Here's a working fiddle

Answer

Make use of prevAll with a required class because prev() just gives the prev sibling

$('.btn').on('mouseenter', function(){
   
	$(this).prevAll('.i:first').addClass('hovering');
})
$('.btn').on('mouseleave', function(){

	$(this).prevAll('.i:first').removeClass('hovering');
})
.i{
  font-size: 20px;
	margin-left: 0;
	-webkit-transition: color 0.8s;
	transition: color 0.8s;  
}	

.i:hover, .hovering{
  color: #1AC4F8
}


#services [class*="flaticon"]:hover{
	color: #1AC4F8
}

.btn{
	display: inline-block;
	padding: 5px 10px;
	border: 2px solid #1AC4F8;
	color: #1AC4F8;
	-webkit-transition: color 0.8s, background-color 0.8s;
	transition: color 0.8s, background-color 0.8s
}

.btn:hover{
	background-color: #1AC4F8;
	color: #F2F2F2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
     <p class="i">Ilumínate 1</p>
     <h3>Web Development</h3>
     <p>Professional custom e-commerce and web design to let your business grow at a rapid pace. See how we do that.</p>
     <a href="#" class="btn">Read more</a>
</div>

<div>
     <p class="i">Ilumínate 2</p>
     <h3>Web Development</h3>
     <p>Professional custom e-commerce and web design to let your business grow at a rapid pace. See how we do that.</p>
     <a href="#" class="btn">Read more</a>
</div>