I would like add an event such as onclick or mouseover to a dynamically created element (similar to the .live function in jQuery)...how do I do this using pure javascript without a framework such as jQuery?
document.getElementById('create').onclick = function(){
var newdiv = document.createElement('div');
newdiv.addClass('new');
document.body.appendChild(newdiv);
};
document.getElementsByClassName('newdiv').onclick = function(){
alert('Success');
};
#create {
width:150px;
height:25px;
margin-bottom:5px;
background:#ccc;
border:1px solid #222;
}
.new {
width:200px;
height:100px;
background:#ffccff;
border:1px solid #333;
}
<html>
<body>
<div id="create">
Click to create div
</div>
</body>
</html>
I would like to be able to do this from the newly created divs class instead of an id.
Any help would be greatly appreciated
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
jQuery bind() MethodUse the on() method instead. The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.
Create one handler on the document object. Check the target element's class and node name (tag). If they match, proceed with whatever needs to be done, otherwise ignore the click.
document.onclick = function(event) {
var el = event.target;
if (el.className == "new" && el.nodeName == "DIV") {
alert("div.new clicked");
}
};
Here's a fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With