Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery html() method unbinding events to elements inside the inner html after swapping?
    primarykey
    data
    text
    <p>I ran into an interesting problem. On my site, i swap out content dynamically when hovering over a certain link. This is accomplished by something similar to:</p> <pre><code>$('#box').html($('#newcontent').html()); </code></pre> <p>Now inside this <code>#newcontent</code> part, there is a <code>&lt;button&gt;</code>-Element to which I assigned a click event like this: (inside the <code>$(document).ready()</code>-function)</p> <pre><code>$("button#buttonName").click(function(){ $("div#containerName").toggleClass("hidden"); } </code></pre> <p><code>hidden</code> is a css-Class doing the display:none magic. The container <code>#containerName</code> is <strong>outside</strong> both the element containing the button and the element containing the structure that is being changed with <code>html()</code>. </p> <p>Mockup of the structure at this point</p> <pre><code>&lt;div id="somethingthatwhenhoveredoverwillswapthecontent"&gt;Hover over me!&lt;/div&gt; &lt;div id="box"&gt;Change me!&lt;/div&gt; &lt;div id="newcontent" class="hidden"&gt;I am renewed! &lt;button id="buttonName"&gt;Show the weird box at the bottom&lt;/button&gt; &lt;/div&gt; &lt;div id="containerName" class="hidden"&gt; I am content that is only shown when the button is clicked &lt;/div&gt; </code></pre> <p>So what happens is this: the page is loaded, the content swapping script works fine, but the button will not fire it's click event, which for testing reasons didn't even give an <code>alert('whatever');</code>. It looks like once the html() swaps the content from the <code>&lt;div id="newcontent"&gt;</code> to the <code>&lt;div id="box"&gt;</code>, <strong>the event gets unbound</strong> (I suspect).</p> <p>Is this just me not grasping a concept or is the whole approach done wrong?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload