SHRX
SHRX

Reputation: 579

How to change CSS of directly adjacent sibling elements on hover via JS?

i would like to change the css style of directly adjacent siblings of a hovered element, so if i hover element 4, elements 3 and 5 should get a new css class added.

Here is a JSfiddle with the expected result and what i got so far:

http://jsfiddle.net/uxa49myL/5/

$(document).ready(function() {
  $("h1").hover(function() {
    $(this).nextSibling.addClass("siblings");
    $(this).previousSibling.addClass("siblings");
  });
});

sadly, the nextSibling and previousSibling jquery functions do not work as i expected.

Upvotes: 1

Views: 500

Answers (3)

Bhuwan
Bhuwan

Reputation: 16855

Use next and prev jQuery to target the next and previous sibling. And use siblings to target all the sibling elements.

Also you will need to remove the siblings class from h1 on mouse out.

Remove the margins form the h1 and use padding instead to avoid the flickering issue.

Also you are using container-inner id twice which is not a best practice. Use class instead

$("h1").hover(function() {
  $(this).siblings().removeClass("siblings")
  $(this).next().addClass("siblings")
  $(this).prev().addClass("siblings");
}, function() {
  $("h1").removeClass("siblings")
});
#container {
  width: 100vw;
  height: 100vh;
  display: flex;
}

.container-inner {
  width: 50vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

h1 {
  transition: ease all .3s;
  font-size: 1rem;
  margin: 0;
  padding: 6px 0;
}

h1:hover {
  font-size: 2rem;
}

.siblings {
  font-size: 1.5rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'>
  <div class="container-inner">
    expected result:
    <img src="https://i.imgur.com/RJS2kHM.png" />
  </div>
  <div class="container-inner">
    result:<br><br>
    <h1>Heading</h1>
    <h1>Heading</h1>
    <h1>Heading</h1>
    <h1>Heading</h1>
    <h1>Heading</h1>
    <h1>Heading</h1>
    <h1>Heading</h1>
    <h1>Heading</h1>
    <h1>Heading</h1>
    <h1>Heading</h1>
  </div>
</div>

Upvotes: 0

ellipsis
ellipsis

Reputation: 12152

You can use .next and .prev methods of jquery

$(document).ready(function() {
  $("h1").hover(function() {
    $(this).siblings().removeClass("siblings")
    $(this).next().addClass("siblings");
    $(this).prev().addClass("siblings");
  });
});
.siblings {
  color:green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>C</h1>
<h1>A</h1>
<h1>B</h1>

Upvotes: 2

Shreyas Gaonkar
Shreyas Gaonkar

Reputation: 283

You'll have to use the .next() and .prev() JQuery call to get the adjacent siblings.

$(document).ready(function() {
  $("h1").hover(function(){
    $(this).siblings().removeClass("siblings");
    $(this).next().addClass("siblings");
    $(this).prev().addClass("siblings");
  });
});

Upvotes: 1

Related Questions