Search code examples
javascripthtmlcsstoggleclass

Use Javascript to change body CSS upon clicking a label


I am working on a website for a friend. I use an off-screen CSS menu. The button that invokes the menu is not an HTML button, its listed as a Input and Label.

When using the menu you can still scroll on the main body of the pag. I would like to disable that. The only way I can see how that's possible is to change the body CSS upon clicking the menu label, but i've been at it for a few hours and had no luck. I was planning on adding the following to the body class upon opening the menu:

overflow: hidden;
position: static;

Here's the javascript I have landed on most recently, to no avail. I've tried a boatload, but the HTML "onclick" and then running a script that toggles the body class was my best theory.

HTML

<input data-function='swipe' id='swipe' type='checkbox' value="button"/>
<label data-function='swipe' for='swipe' onclick='noScroll()' value="button">&#xf0c9;</label>


<div class='sidebar'>
    <nav class='menu'>
        <li><a href='#'>Home</a></li>
        <li class='active'><a href='#'>About</a></li>
        <li><a href='#'>Imprint</a></li>
        <li><a href='#'>Imprint</a></li>
    </nav>

</div>

Javascript

noScroll({
    $('#swipe').toggleClass('body bodynoscroll');
    })

CSS

.body {
    font: 12px/1 'Open Sans', sans-serif;
    color: $c;
    background: $c;
    overflow-x: hidden;
}

.bodynoscroll {
    font: 12px/1 'Open Sans', sans-serif;
    color: $c;
    background: $c;
    overflow-x: hidden;
    overflow: hidden!important;
    position: static!important;
}

Website

https://www.brotherhoodgaming.net

Any help is appreciated! I am terrible with javascript, so I'm learning.


Solution

  • Give your label an ID to bind a event to it. Something like this:

    <label id="menubuttonlabel" data-function='swipe' for='swipe' onclick='noScroll()' value="button">&#xf0c9;</label>
    

    And then your JS code would look like:

    $(document).on('click', '#menubuttonlabel', function(){
        if ($('body').css('overflow') == 'auto'){
              $('body').css("overflow", "hidden");
              }else{
                  $('body').css("overflow", "auto"); 
              }   
    });