Event listener not working with dynamically added element

I am adding h1 tag to my document when submit button is clicked using jQuery. I want to interact with this h1 tag later (with mouse clicks), so I need to add an event handler to it. However, it doesn't seem to register clicks.

I saw this question asked by SO before and everyone says they are using .on () which I have, but still no luck. I don't get any errors either, so I don't know where to start.

Here is a jsFiddle of a very simplified version of everything. Thank.

$("h1").on("click", function(){
    alert("test");
    $("h1").css("color","red");
})

      

+3


source to share


2 answers


Use this:

$(document.body).on("click", "h1", function(){
    alert("test");
    $("h1").css("color","red");
})

      

The jquery set should contain, when you call on

on it, the elements that will contain h1

. You can replace document.body

with any item you are sure h1

will be.



Side note:

Are you sure you don't want $(this).css("color","red");

instead $("h1").css("color","red");

? Using $(this)

would change the color of the clicked h1

and not everything h1

.

+13


source


try it

JS CODE



$(document.body).on("click", "h1", function(){
    alert("test");
    $(this).css("color","red");
});

      

LIVE DEMO

-1


source







All Articles