p_e_88
p_e_88

Reputation: 1037

Set overflow to hidden on body by click on menu

I tried to write a snippet of code, to set the body tag on overflow: hidden, when someone opens the menu (which is a fullscreen menu). It should also set it back to auto, when the user clicks on close. The problem that I have is, that it sets it to hidden, but don't reset it to auto, when the menu is closed. What am I doing wrong?

JavaScript

function() {
  $('.menu-button').click(function(e) {
    e.preventDefault();
    $('body').css('overflow', 'hidden');
  });

  $('.menu-button').click(function(e) {
    e.preventDefault();
    $('body').css('overflow', 'auto');
  });
});

HTML

<div class="menu-button w-nav-button">
    <a href="#" class="menu-icon w-inline-block w-clearfix">
        <div class="menu-icon__line left"></div>
        <div class="menu-icon__line"></div>
        <div class="menu-icon__line right"></div>
    </a>
</div>

Upvotes: 0

Views: 960

Answers (2)

Itang Sanjana
Itang Sanjana

Reputation: 717

JS

$('button').click(function(e) {
    $('body').toggleClass('overflow-hidden');
});

CSS

.overflow-hidden {overflow: hidden}

Replace .css() with .toggleClass()

Upvotes: 0

Jaromanda X
Jaromanda X

Reputation: 1

You need ONE and only ONE click handler, which toggles the overflow attribute

as follows

(function() {
  $('.menu-button').click(function(e) {
    e.preventDefault();
    $('body').css('overflow', $('body').css('overflow') == 'hidden' ? 'auto' : 'hidden');
  });
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="menu-button w-nav-button">
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
</div>

    $('body').css('overflow', $('body').css('overflow') == 'hidden' ? 'auto' : 'hidden');

could also be written

    $('body').css('overflow', $('body').css('overflow') == '' ? 'hidden' : '');

since "auto" is the "default" value for overflow

however, depending on the initial state of overflow, that may not work exactly right ... i.e. if initial state is hidden by a style sheet ... so in that case you'd invert the logic

$('body').css('overflow', $('body').css('overflow') == '' ? 'auto' : '');

Upvotes: 2

Related Questions