Luken00
Luken00

Reputation: 21

Change multiples div class from another div

I'm trying to change (better would be to add) a class name to multiple divs using an onmouseover function in another element. The two elements are not nested to each other so I can't (or at least don't) think I can use plain CSS to do so.

I'm simplifying the following code to make it easier to read. The actual html for the "items" is a little bit more nested. Hope this won't be an issue.

<ul id="buttons">
   <li class="a">button a</li>
   <li class="b">button b</li>
</ul>

<div id="items">
    <div class="item-a"></div>
    <div class="item-b"></div>
    <div class="item-b"></div>
    <div class="item-a"></div>
    <div class="item-b"></div>
</div>

So basically what I want to do is when I hover the "li" elements with the mouse the corresponding class in div "items" gets a class added to itself (so class "a" in buttons would add a class 'hover' to all the "item-a" classes, and so on).

I'm fairly new to JavaScript/jQuery. So far I managed to get it done using Id instead of class, but since ID must be unique it's not what I need. The code was:

onmouseover="document.getElementById('item-a').className = 'hover';"

This worked. Only one div (the first with that ID) but it worked, so I tried to change it from Id to ClassName but it didn't work.

onmouseover="document.getElementsByClassName('item-a').className = 'hover';"

and also, if the above code would work, it would change the class, while I'd prefer to add it (and then remove it with a onmouseout function)

for reference, among the lot of searching i did i also tried this link Trigger the css:hover event with js trying to adapt it to my situation:

$(window).load(function() {
 $('.a').hover(function(){
    $('.item-a').addClass('hover');
});
}

with no results.

Upvotes: 1

Views: 819

Answers (2)

bookcasey
bookcasey

Reputation: 40493

Finagle your markup a little bit and you can do it with plain CSS:

<ul id="buttons">
   <li class="a">button a</li>
   <li class="b">button b</li>
   <li class="items">
       <div class="item-a"></div>
       <div class="item-b"></div>
       <div class="item-b"></div>
       <div class="item-a"></div>
       <div class="item-b"></div>
   </li>
</ul>​​​​​

.a:hover ~ li .item-a {
    background: red;
}

.b:hover ~ li .item-b {
    background: blue;
}

Demo

Upvotes: 1

David Thomas
David Thomas

Reputation: 253396

I'd suggest:

$('#buttons li').hover(function(){
    $('.item-' + this.className).addClass('hover');
},
function(){
    $('.item-' + this.className).removeClass('hover');
});

JS Fiddle demo.

References:

Upvotes: 4

Related Questions