Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event listener not working on dynamically added element

I'm adding, an h1 tag to my document when a submit button is pressed, using jQuery. I want to interact with this h1 tag at a later time (with mouse clicks), so I need to add an event handler to it. However, it does not seem to be registering the clicks.

I've seen this question asked on SO before and they all say use .on(), which I have, but still no luck. I'm not receiving any errors either so don't know where to begin.

Here is the jsFiddle of a very simplified version of it all. Thanks.

$("h1").on("click", function(){
    alert("test");
    $("h1").css("color","red");
})
like image 718
Lars Avatar asked Dec 06 '22 09:12

Lars


2 Answers

Use this :

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

The jquery set must contain, when you call on on it, the elements that will contain the h1. You might replace document.body with any element in which you're sure the h1 will be.

Side note :

Are you sure you don't want $(this).css("color","red"); instead of $("h1").css("color","red"); ? Using $(this) would change the color of the clicked h1 and not all h1.

like image 128
Denys Séguret Avatar answered Dec 11 '22 12:12

Denys Séguret


try this

JS CODE

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

LIVE DEMO

like image 22
Codegiant Avatar answered Dec 11 '22 10:12

Codegiant