Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS hover - can it effect multiple divs with same class name

Tags:

html

css

I have 5 div's all with the same class name like this:

CSS:

.test:hover{
   color:red;
}

HTML:

<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>

Imagine for a moment these Div's are in different parent div's on the page...

I'm trying to find a way so they all change to color:red if i hover my mouse over any of the 5 rather than just the one in question changing...

I can't wrap them in a parent and give that parent a hover how ever... they are not sharing the same parents in the first place.

Does CSS provide a way to do this or am I going to have to rest to JavaScript?

like image 923
Sir Avatar asked Jul 22 '26 18:07

Sir


1 Answers

One (plain/vanilla) JavaScript approach that works (in compliant browsers, which support [].forEach(), and document.querySelectorAll()), given that CSS cannot (yet) perform this task, is:

function classToggle (evt, find, toggle) {
    [].forEach.call(document.querySelectorAll('.' + find), function(a){
        a.classList[evt.type === 'mouseover' ? 'add' : 'remove'](toggle);
    });
}

var els = document.querySelectorAll('.test');

for (var i = 0, len = els.length; i<len; i++){
    els[i].addEventListener('mouseover', function(e){
        classToggle(e, 'test', 'highlight');
    });
    els[i].addEventListener('mouseout', function(e){
        classToggle(e, 'test', 'highlight');
    });
}

JS Fiddle demo.

References:

  • Array.prototype.forEach().
  • document.querySelectorAll().
  • Element.classList.
  • Function.prototype.call().
like image 187
David Thomas Avatar answered Jul 25 '26 10:07

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!