Reputation: 21
I am creating dynamically multiple div
elements using JavaScript. Below is the code I have used:
for(i=0;i<3;i++)
{
var d1 = document.createElement('div');
d1.id = "div" + i;
var l1 = document.createElement('label');
l1.innerHtml = "Hello";
d1.appendChild(l1);
var line1 = document.createElement('hr');
d1.appendChild(line1);
document.body.appendChild(d1);
}
Output:
Hello
Hello
Hello
Now I want to dynamically append event say onmouseover
and onmouseout
so that whenever I move cursor over a particular div
element say div1
, div2
or div3
, that respective div
section should change color (say blue) and when cursor moves out it should return to its original color.
I have tried working out but I am unable to retrieve the div
id's which I have created dynamically.
Upvotes: 2
Views: 113
Reputation: 340
If your elements are created dynamically it may be better to use event delegation and attach the event listener to the parent element instead of every element that you're dynamically creating. This way your listener will work even for elements created after it's attached. DOM events bubble, and an actual target of an event is available as event.target
. Here is an example:
<div id="parent">
<p id="event1">A</p>
<p id="event2">B</p>
<p id="event3">C</p>
</div>
// call on DOMContentLoaded
document.getElementById("parent").addEventListener("click", function(e) {
if(e.target && e.target.nodeName.toLowerCase() == "p") {
alert("Clicked element " + e.target.id);
}
});
See jsfiddle.
Upvotes: 0
Reputation: 25091
Just build your handlers and then assign them in the loop:
var mouseover = function() {
this.style.backgroundColor = '#AAF';
},
mouseout = function() {
this.style.backgroundColor = '';
};
for (i = 0; i < 3; i++) {
var d1 = document.createElement('div'),
l1 = document.createElement('label'),
line1 = document.createElement('hr');
d1.id = "div" + i;
l1.innerHtml = "Hello";
d1.appendChild(l1);
d1.appendChild(line1);
d1.onmouseover = mouseover;
d1.onmouseout = mouseout;
document.body.appendChild(d1);
}
Demo at: http://jsfiddle.net/vfVCm/
Upvotes: 0
Reputation: 48771
You don't need to select by ID. You already have the element, so go ahead and add handlers to it.
for(i=0;i<3;i++) {
var d1 = document.createElement('div');
d1.id = "div" + i;
var l1 = document.createElement('label');
l1.innerHtml = "Hello";
d1.appendChild(l1);
var line1 = document.createElement('hr');
d1.appendChild(line1);
document.body.appendChild(d1);
d1.onmouseover = function() {
this.style.color = "#00F";
};
d1.onmouseout = function() {
this.style.color = "";
};
}
Upvotes: 1