简体   繁体   中英

How to apply Javascript conditionally on a specific css-class only?

I am using a responsive JavaScript menu with a toggle button in a Wordpress Genesis site.

The page has a primary CSS menu ( .nav-primary ) and a secondary CSS menu ( .nav-secondary ). The main navigation styling classes are .genesis-nav-menu and .sub-menu .

The problem is that the responsive menu is applied to every navigation element on the site, ie you have at least 2 toogle bars. I would like to use it only for the primary menu ( .nav-primary ).

I already tried to substitute 'nav' with .nav-primary , which seems to work, however it makes the ´secondary-menu´ and all other navigation elements disappear.

I would appreciate your advice how to get this done.

The Javascript:

( function( window, $, undefined ) {
    'use strict';

    $( 'nav' ).before( '<button class="menu-toggle" role="button" aria-pressed="false"></button>' ); // Add toggles to menus
    $( 'nav .sub-menu' ).before( '<button class="sub-menu-toggle" role="button" aria-pressed="false"></button>' ); // Add toggles to sub menus

    // Show/hide the navigation
    $( '.menu-toggle, .sub-menu-toggle' ).on( 'click', function() {
        var $this = $( this );
        $this.attr( 'aria-pressed', function( index, value ) {
            return 'false' === value ? 'true' : 'false';
        });

        $this.toggleClass( 'activated' );
        $this.next( 'nav, .sub-menu' ).slideToggle( 'fast' );

    });

})( this, jQuery );

You need to use $(".nav-primary") selector for the class nav-primary, not $("nav-primary") .

Here you have information about jQuery selectors .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM