javascript - JS: Set Background on hovered items -
i have 6 <p>
tags on site , want x
have different color when it's hovered:
html:
<p>a<span class="del">x</span></p> <p>b<span class="del">x</span></p> <p>c<span class="del">x</span></p> <p>d<span class="del">x</span></p> <p>e<span class="del">x</span></p> <p>f<span class="del">x</span></p>
js:
function func(elem) { 'use strict'; elem.style.backgroundcolor = "red"; } var spans = document.getelementsbyclassname("del"); var i; (i = 0; < spans.length; = + 1) { spans[i].onmouseover = func(spans[i]); }
but code every x
has red background, if don't hover on anything. have change?
use .addeventlistener()
have placed loop function called events()
. called when page ready.
function func() { this.style.backgroundcolor = "red"; } function events(){ var spans = document.getelementsbyclassname("del"); var i; (i = 0; < spans.length; = + 1) { spans[i].addeventlistener('mouseover',func,false); } } window.onload=events;
<p>a<span class="del">x</span></p> <p>b<span class="del">x</span></p> <p>c<span class="del">x</span></p> <p>d<span class="del">x</span></p> <p>e<span class="del">x</span></p> <p>f<span class="del">x</span></p>
if have questions, please leave comment below , possible.
i hope helps. happy coding!
Comments
Post a Comment