Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>this <code>$('#categories &gt; div:hidden')</code> will always return jQuery object (which evaluates to true), even if there are no elements matching selector. Use jQuery's <code>.toggle()</code> instead of <code>if...else</code>:</p> <pre><code>$('#categories &gt; div').toggle(); </code></pre> <p>here's <a href="http://jsfiddle.net/Etkjr/" rel="nofollow">an example</a> to play with</p> <hr> <p><strong>Update</strong> in response to your comment: Updated example - <a href="http://jsfiddle.net/Etkjr/1/" rel="nofollow">http://jsfiddle.net/Etkjr/1/</a></p> <p>You are correct, event handlers are unbound on DOM change. To prevent, that you would need to use 2 jQuery functions: <code>.live()</code> and <code>.delegate</code>. Both of them monitor DOM changes and rebind events to selectors when the DOM is changed.</p> <p>You want click on a first li to expand dropdown menu - use</p> <pre><code>$('#categories li:first').live('click', function() {}) </code></pre> <p>this way clicking on a first li will trigger your handler, even if your <code>li</code> was just now moved to first position.</p> <pre><code>$('#categories').delegate('.dropdown a', 'click', functon(evt) {}) </code></pre> <p>This is an example of <code>.delegate()</code>. This means that when someone clicks element matching <code>.dropdown a</code> inside the <code>#categories</code> this handler will be called.</p> <p>Here you can use <code>.live()</code> instead, but <code>.delegate</code> makes more sense. Instead of assigning (copying) event handler to all matching elements, we <code>delegate</code> all clicks to a single event handler.</p> <p>I also updated "moving" code. Interesting side effect here, is that you don't need to <code>.hide()</code> dropdown inside the second handler. You see, when you click on a link inside dropdown, the link gets moved into first position. <code>.live()</code> detects that and assigns a <code>click()</code> handler to the link you just clicked. But event is still propagating, so after your second handler is finished, event bubbles up to <code>li</code>, and <code>$('.li').live('click', ...)</code> executes, hiding your dropdown div.</p> <p>Hope this makes sense.</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