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");
})
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
.
try this
JS CODE
$(document.body).on("click", "h1", function(){
alert("test");
$(this).css("color","red");
});
LIVE DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With