Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event on dynamic element WITHOUT jQuery

Tags:

javascript

dom

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

like image 245
Tony Avatar asked Mar 20 '11 23:03

Tony


People also ask

How do you bind a click event to dynamically created elements?

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.

How to bind click event in jQuery?

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.


1 Answers

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.

like image 101
Anurag Avatar answered Sep 30 '22 20:09

Anurag