Pepe Pepe - 1 year ago 63
Javascript Question

Add "onClick" event to a dynamic div with jquery

I have a dynamic created div:

<div id="submit"></div>

and I only want to add a sessionStorage with "onclick", like this:

<div id="submit" onClick="sessionStorage.setItem('status', '2')></div>

I try something like:

$("#submit").click(function(){ sessionStorage.setItem('status', '2'); });

... but it doesnt work. Maybe I dont add the sessionStorage correctly inside the function? Can anybody help me?

Thats my test-fiddle:

Answer Source

As elements are dynamically created, use Event delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

Note: Use .on instead of click for dynamically added elements

$(document).on('click', '#submit', function(){ sessionStorage.setItem('status', '2'); });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download