Ash Burlaczenko
Ash Burlaczenko

Reputation: 25465

Automatically assign event handler to new element

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

Answers (4)

The Alpha
The Alpha

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

VisioN
VisioN

Reputation: 145408

Yes. It is possible.

$("body").on("click", ".someClass", function() {
    // ...
});

Upvotes: 3

David Thomas
David Thomas

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:

Upvotes: 1

keune
keune

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

Related Questions