So i have this 2 jQuery functions stored in a .js file and .js file is loaded before head tag
what is in .js file:
$(document).ready(function(){
$("#button1").click(function(){
$.ajax({
type: 'GET',
url: 'button2.php',
success:
function(html){
$('#button_div').html(html)
}
,
});
});
$("#button2").click(function(){
$.ajax({
type: 'GET',
url: 'button1.php',
success:
function(html){
$('#button_div').html(html)
}
,
});
});
});
So after body I have:
<div id="button_div"><input type="button" id="button1" value="Press"></div>
when the button1 is pressed will load php file named button2.php with the div and button2 code, but here when button2 is pressed will not execute the button2 click function.
Why?
If I put the jQuery code of button2 inside button2.php file after elements will work fine. But I don’t want that. I want to keep the jQuery lines saved only in a .js file and only before </head> tag. I don’t want to use jQuery lines after elements.
When you call
$("#button2").click(),#button2does not exist yet, so you are calling it on nothing. In order to have the click event work, you need to use event delegation (i.e. bind to an element that exists) like so:Then, any time
#button2gets added, clicking it will trigger that event callback.(I use
documentas an example, but try to use an ancestor that is closer to#button2than that).