user2955394
user2955394

Reputation: 1183

How to hover mutiple "div" in the same time?

I have

<div id="d1" class="hov"></div>

and

<div id="d2" class="hov"></div>

and the CSS is

.hov:hover{
    background-color:#cde0c4;
    cursor:pointer;
}

When I hover on d1 I want d2 is hover same. How to hover multiple DIVs at the same time?

Upvotes: 2

Views: 2642

Answers (4)

Andreas Andersson
Andreas Andersson

Reputation: 566

Building on Kierans solution you can also do this with different classes if you would like.

For example:

<div class="container">
  <div class="a">a</div>
  <div class="b">b</div>
  <div class="c">c</div>
</div>

Then with CSS:

.container:hover .a,
.container:hover .b,
.container:hover .c {  
background-color:#cde0c4;
cursor:pointer; }

By doing this you avoid javascript for a simple task. Example: [http://jsbin.com/nohawufoqa/1/edit?html,css,output]

Upvotes: 1

Kieran Hunter
Kieran Hunter

Reputation: 121

Could you wrap them both in a div?

.container:hover .hov {
  background-color: #cde0c4;
  cursor: pointer;
}
<div class="container">
  <div id="d1" class="hov">NUMBER 1</div>
    <br>
  <div id="d2" class="hov">NUMBER 2</div>
</div>

Upvotes: 4

jAndy
jAndy

Reputation: 235972

You need some Javascript for that. For instance:

document.body.addEventListener( 'mouseover', function( event ) {
    if( event.target.classList.contains( 'hov' ) ) {
        [].forEach.call(document.getElementsByClassName( 'hov' ), function( elem ) {
            elem.classList.add( 'hover' );
        });
    }
});

document.body.addEventListener( 'mouseout', function( event ) {
    if( event.target.classList.contains( 'hov' ) ) {
        [].forEach.call(document.getElementsByClassName( 'hov' ), function( elem ) {
            elem.classList.remove( 'hover' );
        });
    }
});

And you need to create a css class called hover which applies the same properties in this scenario.

Demo: http://jsfiddle.net/1LkfbcLx/

Upvotes: 7

sabkaraja
sabkaraja

Reputation: 342

a quick dirty way would be to use script and some additional css. I havent tested it, but is should work

css:

.hov:hover, .active {
    background-color:#cde0c4;
    cursor:pointer;
}

script:

$('#d1').hover( function() {
  $('.hov').addClass('active');
}, function() {
  $('.hov').removeClass('active');
});

Upvotes: 0

Related Questions