Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can't use <code>.on()</code> and <code>.off()</code> that way. Your <code>.on()</code> code is a delegated handler:</p> <pre><code>$('body').on('hover', '.button-container', function(){ $(this).append('&lt;p&gt;New text&lt;/p&gt;'); }); </code></pre> <p>It's an event handler attached to the body object and looking for hover events from any element with class of "button-container".</p> <p>You cannot then just do <code>.off()</code> on one particular element like you are trying to do with this:</p> <pre><code>$('body').off('hover',$(this).closest('.button-container')); </code></pre> <p>That doesn't match the <code>.on()</code> signature so there's no matching event handler to remove. With delegated event handler (like you're using here with <code>.on()</code>), it's either all of nothing. You either remove the entire event handler or not. You can't tell it to just stop delegating on behalf of only some objects.</p> <p>If your objects are not dynamic and thus you don't need delegated event handling, you can do this to remove the specific event handler you want to remove:</p> <pre><code>function addText() { $(this).append('&lt;p&gt;New text&lt;/p&gt;'); } $('.button-container').on('hover', addText); $('.button').on('click', function(){ $(this).closest('.button-container').off('hover', addText); }); </code></pre> <p>Working jsFiddle here: <a href="http://jsfiddle.net/jfriend00/R2eQx/" rel="nofollow">http://jsfiddle.net/jfriend00/R2eQx/</a>.</p> <hr> <p>Another approach that might be simpler is to just remove the class from the object like this:</p> <pre><code>&lt;div class="button-container active"&gt; &lt;div class="button" style="border: 1px solid #cc0000"&gt;Roll over me to make text appear / Click me to stop making text appear (doesn't work)&lt;/div&gt; &lt;/div&gt; $('body').on('hover', '.active', function(){ $(this).append('&lt;p&gt;New text&lt;/p&gt;'); }); $('body').on('click', '.button', function(){ $(this).closest(".button-container").removeClass("active"); }); </code></pre> <p>And a working jsFiddle here: <a href="http://jsfiddle.net/jfriend00/byFpx/" rel="nofollow">http://jsfiddle.net/jfriend00/byFpx/</a>.</p> <p>This leaves the event handler in place, but just removes the triggering class from the button-container so it won't match the event handler any more. This makes it easier to make it trigger again by just adding the class back again.</p>
 

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