alias51
alias51

Reputation: 8608

How to use jquery on HTML loaded after document.ready()

I have several HTML elements, that are rendered by a javascript function on the page:

<a href="#" class="test1">Test</a>
<a href="#" class="test2">Test</a>
<a href="#" class="test3">Test</a>

I then have further javascript that I use to create a function when Test is clicked:

$(document).ready(function(){

   $( ".test1" ).click(function() {
   // Code here
   });

   $( ".test2" ).click(function() {
   // Different code here
   });

   $( ".test3" ).click(function() {
   // Different code here
   });

});

However, because the HTML inserted is not loaded at the same time the page loads (it is dynamically inserted after), my click function doesn't capture the event. How can I solve this?

Upvotes: 0

Views: 266

Answers (3)

Mattias &#197;slund
Mattias &#197;slund

Reputation: 3907

You can make your click events "live", so they attach to objects as they are introduced to the dom. Just change .click(function(){ .... }); to .live('click', function(){ .... });

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to use a delegated event handler:

$(document).ready(function(){
    $(document)
        .on('click', '.test1', function() {
            // Code here
        })
        .on('click', '.test2', function() {
            // Code here
        })
        .on('click', '.test3', function() {
            // Code here
        });
});

Note, for best performance document should be changed to the closest static parent element which is available on DOM load.

Upvotes: 1

Use .on()

As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.

$(document).on('click', '.test', function() { //code here });

Syntax

$( elements ).on( events, selector, data, handler );

Upvotes: 0

Related Questions