I have code below which reads window height and will do one action when less than 50% scrolled and another when scrolled more than 50% - this works fine - BUT, it repeatedly does the action after the scroll fires so ends up repeating the action thousands of times when scrolling - How can I modify this to just call once, then not again until the scroll height changes to the other threshold?
Code example here shows the problem - view the console.log to see the reoccurring actions
( function($) {
function homeMCformSwitching() {
var t=$(window).scrollTop() 1;
var c=$('html').outerHeight();
var p=(t/c*100).toFixed(0);
if (p<50) {
console.log("do action for top half");
}
if (p>50) {
console.log("do action for bottom half");
}
}
homeMCformSwitching();
$(window).scroll(function() { homeMCformSwitching(); });
})(jQuery);
div { height: 3000px; background: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
Check console to see the log firing many times over and over on scroll
</div>
CodePudding user response:
You have to store the last action you did when a scroll threshold is reached. So that on subsequent scrolls with the same threshold you can skip the same action.
Example:
( function($) {
var previousWidth = jQuery(window).width();
/** changed here **/
let lastAction = 0;
function homeMCformSwitching() {
var t=$(window).scrollTop() 1;
var c=$('html').outerHeight();
var p=(t/c*100).toFixed(0);
/** changed here **/
if (p<50 && lastAction != -1) {
lastAction = -1;
console.log("do action for top half");
}
/** changed here **/
if (p>50 && lastAction != 1) {
lastAction = 1;
console.log("do action for bottom half");
}
}
homeMCformSwitching();
$(window).scroll(function() { homeMCformSwitching(); });
})(jQuery);