imperium2335
imperium2335

Reputation: 24112

.on does not work in place of live

I have known for a while now that .on is supposed to replace .live, however I have never been able to get it to work at all.

I have tried:

$(this).on('click', function(){
    // Do something...
})

$(this).on({
    click: function(){ // Do something }
})

But it never works for me!

Specifically when I'm trying to bind events to elements that may not exist on the page initially.

Could someone please clear this up for me once and for all?


I'm using the latest version of jquery.

Upvotes: 2

Views: 74

Answers (3)

Mahbub
Mahbub

Reputation: 3118

For dynamically generated elements you need to use like

$(document).on('click','YOUR SELECTOR', function(){

});

It's because document is the container of your elements which can watch changes to the DOM. For every action, there needs to be an explicit event listener. If you bind something to $(this), it (the selector) might not exist when you remove it.

Upvotes: 2

Arvind Bhardwaj
Arvind Bhardwaj

Reputation: 5291

Do it like:

$(".parent").on('click', ".child", function(){
    // Do something...
})

The syntax you are using works just like bind. To bind event to all future elements, use above syntax.

Upvotes: 2

Amadan
Amadan

Reputation: 198324

You need to specify which elements.

$element.on('click', '.foo', handler)

will bind handler to all live .foo inside $element.

Upvotes: 1

Related Questions