Pepe Pepe - 7 months ago 25
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:

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


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

Thats my test-fiddle:
https://jsfiddle.net//dwcujtvk/

Answer

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'); });
Comments