Michael
Michael

Reputation: 33297

How to bind behavior on newly inserted Dom elements?

In my website I have buttons that are loaded via AJAX. How can I ensure that my jQuery hide() operation is applied to all buttons that are inserted into the DOM in future? As far as I know on() works only when you register events like click for example.

<button class="myButtton">Button</button>

JavaScript:

$(".myButton").hide();

Upvotes: 0

Views: 152

Answers (3)

PSR
PSR

Reputation: 40318

.myButton {
  display: none;
}

While adding the content apply myButton class to the element

Upvotes: 1

JMParsons
JMParsons

Reputation: 506

It's easier to just use css to have a hidden button upon being inserted. jQuery.hide() is basically in css display: none. http://api.jquery.com/hide/.

.myButton {
  display: none;
}

Then when you are ready to show it just use $(".myButton").show(); aka display: block.

Upvotes: 0

Michiel
Michiel

Reputation: 4260

you can use the jquery function .on() This will apply the behavior also to element that are added to the dom later.

$(document).on('click','.elementClass' , function(e){
     // do something
});

Upvotes: 0

Related Questions