jQuery page scroll event logic -- how to throttle - javascript

I have some jQuery listeners setup as follows:
$(document).scroll(function() {
if( $(this).scrollTop() < change1) {
updateBarChart('valuem', 'opencomparison');
} else if ( $(this).scrollTop() > change1 && $(this).scrollTop() < change2) {
updateBarChart('valuef', 'opencomparison');
} else if ($(this).scrollTop() > change2) {
updateBarChart('valuem', 'remove')
//updateSteamChart('','steam')
}
});
Straightforward enough. Some charts are updated when scrolling changes.
My issue is, this is sending too many function updates. I'd like if there were a way to throttle the .scroll(function() {}) That way, fewer event updates are fired.
Ideas?

A fairly simple way of achieving throttling might be to add a check against a random value so that it only fires a certain percentage of the time:
$(document).scroll(function() {
//Only fires 10% of the time
if (Math.random() < 0.1) {
if( $(this).scrollTop() < change1) {
updateBarChart('valuem', 'opencomparison');
} else if ( $(this).scrollTop() > change1 && $(this).scrollTop() < change2) {
updateBarChart('valuef', 'opencomparison');
} else if ($(this).scrollTop() > change2) {
updateBarChart('valuem', 'remove');
}
}
});
Alternatively, you could use a timer so that it only fires once per x miliseconds:
$(document).scroll(function() {
//Only fires at most once every half-second
if (timer > 500) {
timer = 0;
if( $(this).scrollTop() < change1) {
updateBarChart('valuem', 'opencomparison');
} else if ( $(this).scrollTop() > change1 && $(this).scrollTop() < change2) {
updateBarChart('valuef', 'opencomparison');
} else if ($(this).scrollTop() > change2) {
updateBarChart('valuem', 'remove');
}
}
});
var timer = 0;
setInterval(function () { timer += 50; }, 50);

Related

Why doesn't this JS work? (window.scrollTop)

The class 'stuck-sm' is added, but 'stuck-md' is not.
if ($(window).scrollTop() >= 285) {
$('.something').addClass('stuck-sm');
} else if ($(window).scrollTop() >= 430) {
$('.something').addClass('stuck-md');
} else {
$('.something').removeClass('stuck-sm','stuck-md');
}
else if is reachable only if the value is less than 285 which means second else if block won't get execute. Below is the correct solution.
if ($(window).scrollTop() >= 430) {
$('.something').addClass('stuck-md');
} else if ($(window).scrollTop() >= 285) {
$('.something').addClass('stuck-sm');
} else {
$('.something').removeClass('stuck-sm','stuck-md');
}

JAVASCRIPT only the first function is working on my window.onscroll function

I am new to javascript and I am trying to make both of these functions run at different times depending on the scroll position but only the first function 'myFunction1' is running. Please help.
<script>
window.onscroll = function redblob() {myFunction()
function myFunction() {
if (document.body.scrollTop > 250 && document.body.scrollTop < 1200 ||
document.documentElement.scrollTop > 250 && document.documentElement.scrollTop < 1200 ) {
document.getElementById("redblob").classList.add('scale-transition');
}
else {
document.getElementById("redblob").classList.remove('scale-transition');
}
}
function myFunction2() {
if (document.body.scrollTop > 1200 && document.body.scrollTop < 1700 ||
document.documentElement.scrollTop > 1200 && document.documentElement.scrollTop < 1700 ) {
document.getElementById("blueblob").classList.add('scale-transition');
}
else {
document.getElementById("blueblob").classList.remove('scale-transition');
}
}
};
</script>
You were reusing the function name myFunction(). I renamed the second one to myFunction1() (this is what you said it should be named in your question) and added a function declaration before it. This caused the errors to go away.
<script>
window.onscroll = function redblob() {
function myFunction() {
function myFunction1() {
if ((document.body.scrollTop > 250) && (document.body.scrollTop < 1200) || (document.documentElement.scrollTop > 250) && (document.documentElement.scrollTop < 1200)) {
document.getElementById("redblob").classList.add('scale-transition');
} else {
document.getElementById("redblob").classList.remove('scale-transition');
}
}
function myFunction2() {
if (document.body.scrollTop > 1200 && document.body.scrollTop < 1700 || document.documentElement.scrollTop > 1200 && document.documentElement.scrollTop < 1700) {
document.getElementById("blueblob").classList.add('scale-transition');
} else {
document.getElementById("blueblob").classList.remove('scale-transition');
}
}
}
}
</script>
Thank you for your help Daniel, as you noticed i did reuse the function name myFunction. I changed the name to function1 and added that to the first function and it worked perfectly.
window.onscroll = function functionname() { myFunction2(); myFunction1();
function myFunction1() {
if (document.body.scrollTop > 250 && document.body.scrollTop < 1200 ||
document.documentElement.scrollTop > 250 && document.documentElement.scrollTop < 1200 ) {
document.getElementById("redblob").classList.add('scale-transition');
}
else {
document.getElementById("redblob").classList.remove('scale-transition');
}
}
function myFunction2() {
if (document.body.scrollTop > 1200 && document.body.scrollTop < 1700 ||
document.documentElement.scrollTop > 1200 && document.documentElement.scrollTop < 1700 ) {
document.getElementById("blueblob").classList.add('scale-transition');
}
else {
document.getElementById("blueblob").classList.remove('scale-transition');
}
}
};

My JQuery Scroll Down works but scroll up doesn't work at all

I've put in a html several divs with IDs in a row prepended with the letter d, e.g: #d1, #d2, #d3... Then i created the javascript code below:
var pos = 0;
$("#button-up").on('click', function(e) {
e.preventDefault();
if(pos > 1){
pos -= 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
});
$("#button-down").on('click', function(e) {
e.preventDefault();
if(pos < 10){
pos += 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
});
window.addEventListener("scroll", function(event) {
var posi = this.pageYOffset;
if(posi-(pos-1)*1070+50 >= 1070){pos += 1} else if((pos-1)*1070+50-posi <= -1070){pos -= 1};
});
Finally my site scrolls down when i click the button-down, but i need to click twice the button-up for it scrolls up. Why? Is there a better way than this that gets the expected result?
I made it work changing this part:
window.addEventListener("scroll", function(event) {
var posi = this.pageYOffset;
if(posi-(pos-1)*1070+50 >= 1070){pos += 1} else if((pos-1)*1070+50-posi <= -1070){pos -= 1};
});
with this one:
window.addEventListener("mousewheel", function(e) {
e.preventDefault();
console.log('passou por 6');
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
if(pos > 1){
console.log('passou por 3');
pos -= 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
//scroll up
console.log('cima');
}
else{
if(pos < 10){
pos += 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
console.log('baixo');
//scroll down
};
});
Use jquery scoll function
$(window).scroll(function(event){
// your code
});

If statement with scrolltop does not work

I am trying to make an animation happen once the webpage is at a certain part of the page. I have looked at other people queries and my problem is similar but it does not work.
here is the code:
if($('html,body').scrollTop() > 400) {
$('.fish_one').animate({"margin-left":"+=65%"},1000);
$('.fish_two').animate({"margin-left":"-=10%"},1000);
$('.left').animate({"opacity":"+=1"},1000);
$('header').css({"background-color":"#fff"});
$('header a').css({"color":"#94d9f8"});
}
You need to check the if statement every time the page scrolls, not just on load. Use $(window).scroll(function(){
$(window).scroll(function(){
if($(window).scrollTop() > 400) {
alert("lower");
}
});
Fiddle
EDIT: to prevent the function from repeating itself:
var pos = false;
$(window).scroll(function(){
if(($(window).scrollTop() > 400) !== pos ){
alert("changed");
}
pos = $(window).scrollTop() > 400;
});
OR
var pos = false;
$(window).scroll(function(){
if(($(window).scrollTop() > 400) && !pos ){
alert("just passed breakpoint");
}
pos = $(window).scrollTop() > 400;
});
New Fiddle
Try adding it to an event listener like this:
var eventTriggered=false;
$(document).on( 'scroll', function(){
if($(document).scrollTop() > 400 && !eventTriggered) {
alert("success");
eventTriggered=true;
}else if($(document).scrollTop() < 400){
eventTriggered=false;
}
});
This one works

prototype: show a element when scroll page pased 800px

If user up, then hide the element. A div.
i have something:
<script>
window.onscroll = function()
{
if (document.documentElement.scrollTop > 900 || self.pageYOffset > 900) {
$('#divId').css('display','block');
} else if (document.documentElement.scrollTop < 900 || self.pageYOffset < 900) {
$('#divId').css('display','none');
}
}
</script>
But not work.
Something like this:
$(window).scroll(function () {
var $someDiv = $("#someDiv"),
top = $(this).scrollTop();
if (top > 200) {
$someDiv.show();
} else {
$someDiv.hide();
}
});​
See this Fiddle.

Categories