user969068
user969068

Reputation: 2943

Body overflow hide on click

My Html

<html>
...
<body>
 <div id="topContent">...</div>
 <div id="clickMe">Show TopContent</div>
...

</body>

By clicking div #clickMe above div #topContent slide down with jQuery, it was adding an overflow so I added a class to body and used toggleClass() to hide the overflow

.hiddenOverflow { overflow:hidden }

JavaScript:

  $("#clickMe").click(function(){
    $("#topContent").slideToggle('slow');
    $('html,body').toggleClass('hiddenOverflow');
  });

issue is when I click first time, it slideDown perfectly but when I click again to slideUp, an overflow is added to the body until #topContent is hidden and that overflow disappear when #topContent is fully disappear.

How can I prevent not to display overflow on slideUp?

Upvotes: 0

Views: 115

Answers (1)

samrap
samrap

Reputation: 5673

Why not in your CSS, just declare the overflow-x to be hidden:

body {
    overflow-x: hidden;
}

In most cases you never want the horizontal content to overflow in the body. If this doesn't suit your needs, you can pass a callback function to the slideToggle function that will be executed when the animation is complete:

$("#clickMe").click(function(){
    $("#topContent").slideToggle('slow', function() {
        $('html,body').toggleClass('hiddenOverflow');
    });
});

However, this will only reverse your issue. If you then slide it open, the class will not be added until after it opens, most likely causing the same issue. To prevent this, you will have to keep track of the state of your #topContent div (opened or closed) and use the slideUp and slideDown functions instead. slideUp would take the callback function to remove the class, where slideDown would not take a function and would instead toggle the class immediately.

Upvotes: 1

Related Questions