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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

If I have a whole bunch of functions, can I nest them under (document).on? If so, what would be the syntax?
It depends on the structure of those functions, and how logic flows between them. Can you edit your question to include those functions.
Thanks, this doesn't seem to solve my problem. What's the best way to debug it?
The same as all javascript - the console. Press F12 in your browser to see it.
Just to be clear, you still need your document ready handler. Check my update
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 );

2 Comments

Thanks, why use (document).ready at all then? What are the advantages/disadvantages of this?
@alias51 Read This
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(){ .... });

1 Comment

No, no. .live() has been deprecated. Use .on() instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.