TubbyStubby TubbyStubby - 7 months ago 11
Javascript Question

How to call a js function when an element with a particular class is hovered?

I am trying to call a function when an element of a particular class is hovered. Suppose there are 100 div and 50 of them have class test, so what I wanted was that a function should be called when I hover on the divs with class test.

<div class="test" mouseover="myfunc()">
</div>
<div class="test" mouseover="myfunc()">
</div>
<div class="test" mouseover="myfunc()">
</div>
.
.
.
<script type="text/javascript">
function myfucn(){......}
</script>


but this becomes too tedious, so what I want is a generalized method which targets all test class elements without needing to write mouseover event again and again. I prefer only javascript(because I was learning it) but have no problems with jquery.

Answer

If you don't mine to using only Javascript. Try using Jquery like this.

function doSomeThing(){
     //do something
}

$("div.test").hover(function(){
     doSomeThing();
});

if you want only Javascript try this:

function doSomeThing(){
    //do something
}

var el = document.getElementsByClassName("test");
for (i in el){
    el[i].addEventListener("mouseover", function(){
        //do something here

        //or call a function
        doSomeThing();
    });
}

More information

When you do document.getElementsByClassName("test");

You will get it as Array. Then you have to add them an addEventListener("mouseover") to make them know when they was hovered. After that, you write something you want to do inside of its function.

Comments