user2371433
user2371433

Reputation: 43

Can't execute javascript on dynamically created html button

So im quite new to javascript/jquery, so i need some help. Here's the problem. I have a page, where a button triggers a jquery animation to reveal a log in form.(It just replaces the previous html that was in it's place) On the login form i have it dynamically create a button to hide the login form, and reveal the original html. But that button cannot be called by the .click method, or even the OnClick attribute does not work! Any Advice?

$(document).ready(function() {
$("#login_button").click(function() {
$("#menu").animate({height: "toggle"}, 500, function() {
$("#menu").empty();
$("#menu").append('<button id="back_button"></button>');
$("#menu").animate({height: "toggle"}, {duration: 500, queue: false});
});
});
});

And Then the code that listens for the "back_button" click:

$(document).ready(function() {
$("#back_button").click(function() {
$("#menu").animate({height: "toggle"}, 500, function() {
$("#menu").append(//Regular HTML);
$("#menu").animate({height: "toggle"}, {duration: 500, queue: false});
});
});
});

Can javascript not be executed on a element generated my another javascript? Any thoughts would be great! Thanks in advance!

Upvotes: 3

Views: 3314

Answers (4)

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

This is occuring because when the javascript for the back button is executed, the actual element doesn't exist.

Instead, use .on to bind the click event.

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

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

You need event delegation

$(document).on('click', '#back_button', function() {
  // do your stuff here
});

http://api.jquery.com/on/

Upvotes: 0

j08691
j08691

Reputation: 207891

Change the code for your back buttom from:

$("#back_button").click(function() {

to

$(document).on('click', "#back_button", function() {

When creating elements dynamically, you need to use jQuery's .on() function.

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.

Upvotes: 12

Adrian
Adrian

Reputation: 46423

You attempt to add the click handler on load, but the <button> hasn't been created yet. Add the click function in the same code that creates the button, after it's created.

Upvotes: 0

Related Questions