Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to optimize jQuery code for adding classes (to different elements)?
    primarykey
    data
    text
    <p><strong>Example HTML</strong> (for the sake of clarity):</p> <pre><code>&lt;nav&gt; &lt;ul&gt; &lt;li class="top-navbar-channels"&gt; &lt;a href="#"&gt;&lt;/a&gt; &lt;div class="dropdown-menu"&gt;BLAH, BLAH, BLAH!&lt;/div&gt; &lt;/li&gt; &lt;li class="top-navbar-about"&gt; &lt;a href="#"&gt;&lt;/a&gt; &lt;div class="dropdown-menu-about"&gt;BLAH, BLAH, BLAH!&lt;/div&gt; &lt;/li&gt; &lt;li class="top-navbar-search"&gt; &lt;a href="#"&gt;&lt;/a&gt; &lt;div class="dropdown-menu-search"&gt;BLAH, BLAH, BLAH!&lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; </code></pre> <p><strong>Example jQuery code:</strong></p> <pre><code>jQuery(document).ready(function($){ $('.dropdown-menu').on('show', function () { $('.top-navbar-channels &gt; a').addClass('selected'); }); $('.dropdown-menu').on('hide', function () { $('.top-navbar-channels &gt; a').removeClass('selected'); }); $('.dropdown-menu-about').on('show', function () { $('.top-navbar-about &gt; a').addClass('selected'); }); $('.dropdown-menu-about').on('hide', function () { $('.top-navbar-about &gt; a').removeClass('selected'); }); $('.dropdown-menu-search').on('show', function () { $('.top-navbar-search &gt; a').addClass('selected'); }); $('.dropdown-menu-search').on('hide', function () { $('.top-navbar-search &gt; a').removeClass('selected'); }); }); </code></pre> <p><strong>For those who are curious...</strong> the jQuery code adds a new class <code>selected</code> to the active menu item's link. In my case it's <a href="http://twitter.github.com/bootstrap/javascript.html#collapse" rel="nofollow">Twitter Bootstrap-based collapsible menu</a>, where active means, the menu item is not collapsed i.e. open.</p> <p>Now, the question is, can the jQuery code be optimized (i.e. same functionality with less code)? If so, how?</p>
    singulars
    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