Halnex Halnex - 2 months ago 10
Javascript Question

Background overlay doesn't go away when I close the off-canvas sidebar

I am using BigSlide JS to create an off-canvas sidebar. The plugin doesn't come with a feature to add a background overlay whenever the off-canvas sidebar is called into action, so I added my own.

This is the icon that shows the sidebar on click

<div class="icon menu1 menu-link">
<span></span>
<span></span>
<span></span>
</div>


And this is how I initialize

$('.menu-link').bigSlide({
menu: '#off-canvas-menu',
menuWidth: '270px',
easyClose: true
});


Now for the background overlay I created a new html div and placed it at the top of the content div

<div class="site-overlay"></div>


Then I added its CSS

.site-overlay {
display: none;
}
.menu-open .site-overlay {
display: block;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 9998;
background-color: rgba(0, 0, 0, 0.8);
-webkit-animation: fade 500ms;
animation: fade 500ms;
}


And I added a JS function to add the class
menu-open
to the
body
whenever the div with the classes
.menu-link
gets clicked on

$('.menu-link').click(function() {
$('body').addClass('menu-open');
});


But now when I close the sidebar, the background overlay remains and I have no idea how to make it go away.

jsFiddle: https://jsfiddle.net/v1w532d3/7/

Answer

try doing:

$('.menu-link').bigSlide({
   menu: '#off-canvas-menu',
   menuWidth: '270px',
   easyClose: true,
   afterOpen: function(){
      $('body').addClass('menu-open');
   },
   afterClose: function(){
    $('body').removeClass('menu-open');
   }
});

and remove:

$('.menu-link').click(function() {
   $('body').addClass('menu-open');
});

as you don't seem to need it since you use bigSlide for the off-canvas functionality.

See bigSlide's documentation here for all available options: https://github.com/ascott1/bigSlide.js