Reputation: 928
myDiv = document.getElementById('results');
div = myDiv.getElementsByTagName('div');
for (var i = 0; i < div.length; i++) {
var division;
division = div[i];
// console.log(div[i]);
division.addEventListener('mouseover', function () {
division.style.fontWeight = "bold";
division.style.background = "rgba(0, 7, 255, 0.29)";
}, false);
division.addEventListener('mouseout', function () {
division.style.fontWeight = "";
division.style.background = "";
}, false);
Here is the html code :
<div id="results">
<div>Resulat 1</div>
<div>Resulat 2</div>
</div>
My script which bold and put a background on some text is when the mouse pointer is over it working only for the second element.. ( <div>Resulat 2</div>
)
Can someone tell me why because everything I did is right for me, even though I'm a JS beginner.
Upvotes: 2
Views: 74
Reputation: 3936
You are referencing the last element that "division" is set to w/ the event listeners. To do as you wish, use "this" in it's place:
myDiv = document.getElementById('results');
div = myDiv.getElementsByTagName('div');
for (var i = 0; i < div.length; i++) {
var division = div[i];
division.addEventListener('mouseover', function (e) {
this.style.fontWeight = "bold";
this.style.background = "rgba(0, 7, 255, 0.29)";
}, false);
division.addEventListener('mouseout', function (e) {
this.style.fontWeight = "normal";
this.style.background = "inherit";
}, false);
}
Upvotes: 0
Reputation: 150253
use this
:
division.addEventListener('mouseover', function() {
this.style.fontWeight = "bold";
this.style.background = "rgba(0, 7, 255, 0.29)";
}, false);
division.addEventListener('mouseout', function() {
this.style.fontWeight = "";
this.style.background = "";
}, false);
division
will hold the last div because of the loop.
Live DEMO
Another way if necessary is to create a private scope- closure for each iteration.
for (var i = 0; i < div.length; i++) {
(function() {
var division = div[i];;
division.addEventListener('mouseover', function() {
division.style.fontWeight = "bold";
division.style.background = "rgba(0, 7, 255, 0.29)";
}, false);
division.addEventListener('mouseout', function() {
division.style.fontWeight = "";
division.style.background = "";
}, false);
})();
}
Upvotes: 1
Reputation: 105886
What is division
in your function()
? It is the same as the division
you change in every iteration at division = div[i];
. After your for-loop has finished division
is div[1]
. This is why you only change the second div.
You could use a closure to tackle this problem, or use access the associated object with this
:
division.addEventListener('mouseover', function () {
this.style.fontWeight = "bold";
this.style.background = "rgba(0, 7, 255, 0.29)";
}, false);
division.addEventListener('mouseout', function () {
this.style.fontWeight = "";
this.style.background = "";
}, false);
However, your desired effect can be easily achieved with CSS:
#results > div:hover{
font-weight:bold;
background-color:rgba(0,7,255,0.29);
}
Upvotes: 1