Kai Aragaki
Kai Aragaki

Reputation: 437

Pure JavaScript replacement for :hover

My goal, essentially, is to have the CSS :hover replaced by JavaScript. The reason is that I need a loop to be executed on a variable number of divs that will be nested inside the parent div that should react upon :hover.

The problem, however, is that I have no idea how to target just the div being hovered over without hard-coding in specific IDs - something that I will not be able to do once applied to my project, a tumblr theme.

HTML

<div id="motherbox">
    <div class="middlebox">
        <div class="childbox">One</div>
        <div class="childbox">Two</div>
        <div class="childbox">Three</div>
    </div>
</div>
<div id="motherbox">
    <div class="middlebox">
        <div class="childbox">One</div>
        <div class="childbox">Two</div>
        <div class="childbox">Three</div>
        <div class="childbox">Four</div>
        <div class="childbox">Five</div>
    </div>
</div>

CSS

#motherbox {
    width:30%;
    height:100px;
    margin:100px auto;
    background-color:gray;
}

JavaScript

document.getElementById("motherbox").onmouseenter = function(){
    this.style.backgroundColor = 'blue';
};

document.getElementById("motherbox").onmouseleave = function(){
    this.style.backgroundColor = "gray";
};

JSFiddle

My question is - how do I cause divs with the same class or id to react individually (or, rather, not all at once) on hover using javascript, rather than CSS?

Thank you for your time.

Upvotes: 1

Views: 5923

Answers (2)

Basically you can select elements having a particular class using getElementsByClassName.

Here is a working demo.

var elements = document.getElementsByClassName('childbox');
for(var i=0; i<elements.length; i++) { 
  elements[i].onmouseleave = function(){
    this.style.backgroundColor = "blue";
};
}

Upvotes: 2

Paweł Smołka
Paweł Smołka

Reputation: 638

So use instead of getElementById this: http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

And provide classess for your divs, where you want have that event.

Upvotes: 0

Related Questions