0

Here's a simplified version of my jQuery script that I cannot force to work properly.

http://jsfiddle.net/qk2nupq6/ (code's also below)

There's a "#press" div within a "#container". After pressing "#press", the content of "#container" is changed via .html() but the "#press" is still there so that is can be pressed again and the function can be run again.

For some reason, after pressing the button once, the function does not run again and I do not really have any clue why is that so.

HTML

<div id="container">
    <div id="press">press </div>
</div>

JS

$(document).ready(function(){
    $("#press").click(function(e){
        console.log("x");
        $("#container").html($("#container").html()+"<div>added</div>");
    })
})
Grzegorz G.
  • 417
  • 3
  • 6
  • 15
  • You are destroying the existing elements (including any handler that is bound to them) and create new ones. – Felix Kling Sep 20 '15 at 14:49
  • That is true, thank you. I was not sure what should I Google for (so that could find the post you mentioned). Your suggestion and link to the other post about the issue solves my problem. – Grzegorz G. Sep 20 '15 at 14:53

2 Answers2

2

When you replace the innerHTML of the element the events bound to the elements are removed. So, when you replace the HTML even with the same content, previously bound events will not work.

Use event delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

Use on to bind event

$('#container').on('click', '#press', function() {

Demo

$(document).ready(function() {
  $("#container").on('click', "#press", function(e) {
    $("#container").html($("#container").html() + "<div>added</div>");
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="container">
  <div id="press">press</div>
</div>
Tushar
  • 85,780
  • 21
  • 159
  • 179
2

You can use .append() like this:

$(document).ready(function(){
    $("#press").on('click', function(e){
        console.log("x");
        $("#container").append("<div>added</div>");
    })
})

Here is the FIDDLE.

Explanation:

You were replacing the html of the element so, any event bound to it were removed.

  1. Use Event Delegation:

Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future. Inside the Event Handling Function.

  1. Or Append new data to existing element
Abhishekh Gupta
  • 6,206
  • 4
  • 18
  • 46