Reputation: 8458
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");
})
Upvotes: 6
Views: 6953
Reputation: 2150
try this
JS CODE
$(document.body).on("click", "h1", function(){
alert("test");
$(this).css("color","red");
});
Upvotes: 1
Reputation: 382092
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
.
Upvotes: 15