Is there anyway of removing an if
statement after it has been fired once?
I have a menu container that shows on page load and want it so when the user scrolls 1px it slides away. I don't though want a the browser constantly tracking a scrollTop()
method because of the performance hit from this.
What's the best way to remove or cancel an if
statement after it has been used once?
The code is below and I have a codepen here: http://codepen.io/emilychews/pen/evbzMQ
jQuery(document).ready(function($) { $(window).scroll(function() { if ($(document).scrollTop() > 1) { $('.menubox').css('left', '-25%'); } }); $('.mybutton').on('click', function() { $('.menubox').css('left', '0%'); }); });
body { margin: 0; padding: 0; height: 200vh; } .menubox { top: 100; position: fixed; width: 20%; height: 100%; background: red; padding: 10px; color: white; transition: all 1s; } .mybutton { position: fixed; left: 40%; top: 50px; padding: 5px 10px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="menubox">Menu Box</div> <button class="mybutton">menu</button>
You can call off()
within the if
statement to remove the event handler.
Also note that if you're concerned about performance you can debounce the event handler so that it only executes the logic once scrolling stops for N ms:
var scrollTimer;
$(window).scroll(function() {
clearTimeout(scrollTimer)
scrollTimer = setTimeout(function() {
if ($(document).scrollTop() > 1) {
$('.menubox').css('left', '-25%');
$(window).off('scroll');
}
}, 150);
});
Sounds like you actually have two conditions. One is based on the scroll position, the other is based on some state to be tracked. So just add a variable to track that state. Maybe something like:
var scrolled = false;
$(window).scroll(function() {
if ( !scrolled && $(document).scrollTop() > 1) { // check the state
$('.menubox').css('left', '-25%');
scrolled = true; // update the state
}
});
$('.mybutton').on('click', function() {
$('.menubox').css('left', '0%');
scrolled = false; // don't forget to reset the state
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.