Reputation: 25465
Say I have some code like this which is called on $(document).ready()
$(".someClass").click(function(){
//do something
});
Later on I have some jquery to create an element with the class someClass
. Is there anyway to automatically attach the click from above or do I have to manually attach it again?
Upvotes: 2
Views: 232
Reputation: 146201
Use latest version of jquery and on
$(document).on('click', '.someClass', function(e){
//do something
});
Live
is deprecated but you can use it, anyway (not recommended).
$('.someClass').live('click', function(e){
//do something
});
Upvotes: 3
Reputation: 145408
Yes. It is possible.
$("body").on("click", ".someClass", function() {
// ...
});
Upvotes: 3
Reputation: 253318
There's two easy ways of doing this, the first is with on()
:
$(".someClassParentElementPresentInTheDOMonDOMReady").on('click','.someClass',
function(){
//do something
});
And the other is to simply assign the click-handler at the point of creation of the new element; I don't know how you're doing that, but an example is below:
$('#addElement').click(
function(){
var newElem = $('<div />',{'class' : 'someClass'}).click(function(){
// do something }).appendTo('.someClassParentElementPresentInTheDOMonDOMReady');
References:
on()
.Upvotes: 1
Reputation: 5795
There is live
, which also listens for new elements
$(".someClass").live('click', function(){
//do something
});
But, as of jquery 1.7 it has been deprecated. It's advised to use on
instead.
But in order to use on
, you need a container for the elements you want to bind a handler. Of course you could use body
or document
but it's better to use a more specific element
$(".someClassContainer").on('click', '.someClass' function(){
//do something
});
Upvotes: 1