Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 449
user2371433 Avatar asked May 05 '26 05:05

user2371433


1 Answers

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.

like image 191
j08691 Avatar answered May 06 '26 20:05

j08691