Please help me to understand why js stop working after .load THE SAME CONTENT in div.
<main >
<div id="reload_div">
<div id="color_div" style="width:100px;height:100px; background:red; margin-bottom: 100px">
orig
</div>
<button id="make_it_green" type="submit" >
make it green
</button>
</div>
<button id="reload_btn" type="submit" style="margin-top:20px">
reload
</button>
</main>
<script>
$("#make_it_green").click(function(){
$("#color_div").css("background","green")
});
$("#reload_btn").click(function(){
$("#reload_div").fadeTo(300,0, function () {
$("#reload_div").load ("reload.php",
{ }, function () {
$("#reload_div").fadeTo(300,1, function () {
});
});
});
});
</script>
After .load the same content in "reload_div" #make_it_green button stop working! Why?
CodePudding user response:
When you run your code as you have posted it, the event handler is added to the make_it_green
button.
Once you load the new content with jQuery the element to which the handler was attached no longer exists, so the event handler no longer exists. You load a new element with the same name, but there's no event handler attached unless you attach the event handler again.
Alternatively, attach the event handler to the containing div
and delegate the event handling.
$("#reload_div").click(function(e){
e.preventDefault();
// Check the id of the original target element. If it's
// our button, change the colour.
if (e.target.id === "make_it_green") {
$("#color_div").css("background", "green");
}
});
See this page on MDN for a detailed discussion of event delegation