javascriptwordpressunderscores-wp

Add noscroll class to body on menu click


I'm using underscores as a starter theme for Wordpress, and I'd like to add a 'noscroll' class to the body element when the menu button is toggled open, then remove it again when the menu is closed.

I've tried adding this kind of thing...

$('body').addClass('noscroll');

...to the existing navigation.js file that comes with underscores. Which looks like this...

https://github.com/Automattic/_s/blob/master/js/navigation.js

...but I just can't seem to find the right solution. Any help would be gratefully received and learnt from!


Solution

  • I don't recommend altering the navigation.js file as this some sort of pre-existing code that is not specific to your site.

    What you can do is try enqueueing your custom script in your theme functions.php file like so:

    function wpse39838169_addNoScroll() { ?>
    <script>
    $(".MENUBUTTONCLASS").on("click", function(e) {
        $('body').addClass('noscroll');
    });
    </script>
    <?php }
    add_action('wp_enqueue_scripts','wpse39838169_addNoScroll');
    

    Replace "MENUBUTTONCLASS" with the class of the button that will be clicked.