Daindi Daindi - 4 months ago 18
jQuery Question

collapse and expand onScroll



// Schlie├čen Button Hauptnavigation
$('button#collapse-button').click(function () {
$('nav#main-nav').toggleClass('closed');
});


$(window).on('scroll', function () {
if ($(window).scrollTop() >= 500) {
$('nav#main-nav').addClass('closed');
}
})

#header{
height:500px;
width:100%;
background-color:darkslateblue;
}
#content{
background:#ccc;
height:900px;
width:100%;
}
#main-nav{
width:200px;
height:300px;
background: #fff;
display:inline-block;
position:fixed;
left:0;
top:50px;
transition:all 400ms ease;
}
.closed{
left:-200px !important;
}
#collapse-button{
float:right;
width:20px;
background:yellow;
}
.closed button{
margin-right:-20px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
header
<br><br>
<nav id="main-nav">
<button id="collapse-button">X</button>
</nav>
</div>
<div id="content">
content
</div>




Hi all,
the navigation collapse after i scroll 500px down.
But if i open the navigation under the 500px(under purple header-div) by click and try to scroll, the navigation collapse again.

Can the click behavior are above the scroll behavior ? That is , if you've opened or closed manually by clicking that scrolling the navigation is no longer affected..

sry for bad english

Answer

If you want that once the user has clicked on the button to hide/show, then scroll code should not execute then , in click .off the scroll event.

$(window).off('scroll');

This will stop monitoring the scroll changes.

// Schlie├čen Button Hauptnavigation
    $('button#collapse-button').click(function () {
        $('nav#main-nav').toggleClass('closed');
        $(window).off('scroll');
    });
    
    
    $(window).on('scroll', function () {
        if ($(window).scrollTop() >= 500) {        
            $('nav#main-nav').addClass('closed');  
        }
    })
#header{
  height:500px;
  width:100%;
  background-color:darkslateblue;
}
#content{
  background:#ccc;
  height:900px;
  width:100%;
} 
#main-nav{
  width:200px;
  height:300px;
  background: #fff;
  display:inline-block;
  position:fixed;
  left:0;
  top:50px;
  transition:all 400ms ease;
}
.closed{
  left:-200px !important;
}
#collapse-button{
  float:right;
  width:20px;
  background:yellow;
}
.closed button{
  margin-right:-20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
header
<br><br>
<nav id="main-nav">
  <button id="collapse-button">X</button>
</nav>
</div>
<div id="content">
  content
</div>