super jquery beginner here.
I somehow came to this. When hovering the heading I'd like to change the background of the excerpt too ... and viceversa (when hovering the excerpt the background of the heading will change too).
$(document).ready(function(){
$(".heading, .excerpt").hover(
function() { $(this).addClass('is-hover'); },
function() { $(this).removeClass('is-hover'); });
});
.heading.is-hover{background-color: red;}
.excerpt.is-hover{background-color:green;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<header class="heading"><h2>CIAO</h2></header>
<div>don't change me</div>
<div class="excerpt">text text text</div>
</div>
<div>
<header class="heading"><h2>hi!</h2></header>
<div>don't change me</div>
<div class="excerpt">text two text two</div>
</div>
How can I go on from here? I'm kind of stuck.
I can't change the html part, so no pure css (the question is somehow related my other one here).
thank you for your help & suggestions!
David
You can use a combination of events: mouseover
and mouseleave
and jQuery's .prevAll
and .nextAll
and the :first
css selector to color the corresponding header/excerpt or remove it
$(document).ready(function(){
$(".heading").on('mouseover', function() {
$(this).addClass('is-hover');
$(this).nextAll('.excerpt:first').addClass('is-hover');
});
$(".excerpt").on('mouseover', function() {
$(this).addClass('is-hover');
$(this).prevAll('.heading:first').addClass('is-hover');
});
$(".heading").on('mouseleave', function() {
$(this).removeClass('is-hover');
$(this).nextAll('.excerpt:first').removeClass('is-hover');
});
$(".excerpt").on('mouseleave', function() {
$(this).removeClass('is-hover');
$(this).prevAll('.heading:first').removeClass('is-hover');
});
});
.heading.is-hover{background-color: red;}
.excerpt.is-hover{background-color:green;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<header class="heading"><h2>CIAO</h2></header>
<div>don't change me</div>
<div class="excerpt">text text text</div>
</div>
<div>
<header class="heading"><h2>hi!</h2></header>
<div>don't change me</div>
<div class="excerpt">text two text two</div>
</div>