0

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?

alias51
  • 8,178
  • 22
  • 94
  • 166

3 Answers3

1

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

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 );
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

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(){ .... });

Mattias Åslund
  • 3,877
  • 2
  • 18
  • 17