"on" and "live" in jQuery 1.10.2

1.10.2 How to apply to newly created elements. Which were created by:

$('#ids').append('<div class="sel_option" value="'+i+'">'+i+'</div>');

How to catch a click? Or how to create elements which could be addressed ...

Upvotes: 3

Views: 8074

Answers (2)

Hugo Tostes
Hugo Tostes

Reputation: 412

$(document).ready(function(){
  var content = $(document);

  content.delegate(".sel_option","click",function(){alert("Hello")});
  // with the delegate function, you can put any event in any element

});

Upvotes: 1

.on()

As your contents are loaded dynamically you can't access them directly.

At the load time i.e DOM ready dynamically loaded contents are not part of DOM.

So you have to use event Delegation.

So bind the event on the element which is present in the DOM at page load

$('#ids').on('click', '.sel_option', function () {
    alert('clicked');
});

Upvotes: 11

Related Questions