Victor Zakharov
Victor Zakharov

Reputation: 26414

Process function for dynamically added DOM element

I would like to process certain initialization steps whenever an item with a certain class is added anywhere in the DOM. This includes applying some style attributes to its parent (this is why I cannot use CSS), and also binding to the click event.

The following code works when element is static (was already on the page after document.ready):

$(function(){
  //... global initialization code
  $('.myclass').each(function(){
    var parent = $(this).parent();
    parent.css({cursor:'pointer'}); //apply CSS style to the parent
    parent.click(function(event){
      //... event handler
    });        
  });    
});

Is it possible to convert it to handle dynamically added elements and how?

Upvotes: 0

Views: 184

Answers (2)

Kevin B
Kevin B

Reputation: 95027

There is no cross-browser "added" or "created" event, you'll have to find another way to accomplish it.

Make your CSS changes in a stylesheet:

.myClass {
    cursor: pointer;
}

and then use event delegation for the click event:

$(document).on("click",".myClass",function(){
    var parent = $(this).parent();
    parent.doSomething();
});

Another alternative (as pointed out in comments) is to trigger a custom event after you add the element.

$(document).on("added", ".myClass", function(){
    var parent = $(this).parent();
    parent.doSomething();
});
//... later on in your code ...
$('<div class="myClass"></div>').appendTo("#someotherel").trigger("added");

This is essentially the same thing as simply doing this, which is what i was mentioning in my comments:

var parent = $("#someotherel");
parent.append('<div class="myClass"></div>').css("cursor","pointer").click(...

Upvotes: 2

Adil Shaikh
Adil Shaikh

Reputation: 44740

Use .on() for dynamically added elements -

$(document).on('click','.myclass',function(event){
   //... event handler
}); 

Upvotes: 0

Related Questions