user1137403
user1137403

Reputation: 45

Buttons on externally loaded HTML files will not work

I am using AJAX to load html files. Each html file has a vote up and vote down button.

The script that runs these two buttons are in a document.ready function in the main(index) html file.

When I directly insert the html into the main file, the document.ready function works. But when I ajax load the html files, the contents of the document.ready function will not run.

What am I doing wrong?

Upvotes: 1

Views: 69

Answers (3)

Bassam Mehanni
Bassam Mehanni

Reputation: 14944

Your elements that gets loaded with ajax don't get binded to the events that where defined in document.ready because they did not exist when the document was ready.

You will need to use either live or on.

for example:

$('#buttonLoadedUsingAjax').live('click', function() {});

or if you are using jquery >1.7:

$(document).on("click", "#buttonLoadedUsingAjax", function(){ }); 

Upvotes: 1

Quentin
Quentin

Reputation: 943759

When you load them with Ajax the function has already run. There is nothing happening that would make it run again.

Use event delegation instead of binding the event handlers directly to the elements.

Upvotes: 0

powerbuoy
powerbuoy

Reputation: 12838

Because your script that binds event handlers to your buttons is run before the buttons exist, newly added buttons won't have any event handlers.

What you can do is attach the event handler to a parent element of the buttons and then use the event object's target property to figure out if a button was clicked. That will ensure dynamically generated buttons also work.

If you're using jQuery you can use its on() method.

Upvotes: 0

Related Questions