Question

The following code is toggling (inserting and removing) the class "menu-min" for every link that is clicked within the menu. I want this script to do so only when the link with the ID of #toggle-pane is clicked. I'm not sure how to do that. Any help is appreciated.

<ul class="cbp-vimenu">
        <li><a href="#" class="icon-logo">&nbsp;</a></li>
        <li>
            <a href="#" class="icon-archive"><span class="menu-text"> Dashboard </span></a>
        </li>
        <li>
            <a href="#" class="icon-search"><span class="menu-text"> Search </span></a>
        </li>
        <li>
            <a href="#" class="icon-location"><span class="menu-text"> Location </span></a>
        </li>
        <li>
            <a href="#" class="icon-images"><span class="menu-text"> Images </span></a>
        </li>
        <li>
            <a href="#" class="icon-download"><span class="menu-text"> Download </span></a>
        </li>
        <li>
            <a id="toggle-pane" href="#" class="icon-pencil"><span class="menu-text"> Add Class </span></a>
        </li>
        <!-- Example for active item:
        <li class="cbp-vicurrent"><a href="#" class="icon-pencil">Pencil</a></li>
        -->
    </ul>`

Here is my jQuery

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
    $( ".cbp-vimenu" ).click(function() {
        $( this ).toggleClass( "menu-min" );
    });
</script>
Was it helpful?

Solution

Register the click event only to the #toggle-pane element and then inside find the cbp-vimenu element and toggle its class

$("#toggle-pane").click(function () {
    $('.cbp-vimenu').toggleClass("menu-min");
    //or $(this).closest('.cbp-vimenu').toggleClass("menu-min");
    //I don't think you want to use closest since it doesn't look like you have many elements with class cbp-vimenu
});

OTHER TIPS

$("#toggle-pane").click(function () {
    $(this).closest('ul.cbp-vimenu').toggleClass("menu-min");
});

References

.closest()

id selector

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top