On scroll up/down trigger a function once - javascript

I need to load 2 different animated graphic on window scroll up/down on a website by triggering some functions, it's working but its buggy as the functions are triggered too many times when scrolling:
$(window).scroll(function() {
var scroll = $(window).scrollTop(),
headerHeight = $('.navbar').outerHeight();
if(scroll > headerHeight) {
loadLogoAnimeDown();
}else{
loadLogoAnimeUp();
}
});

You need a way to check if the functions have been called (and logo has been loaded), so you can use a variable for that. After the logo has been loaded, you set the variable as false, which prevents them from loading more than once.
var downNotLoaded = true;
var upNotLoaded = true;
$(window).scroll(function() {
var scroll = $(window).scrollTop(),
headerHeight = $('.navbar').outerHeight();
if(scroll > headerHeight) {
if(downNotLoaded){
loadLogoAnimeDown();
downNotLoaded = false;
}
}else{
if(upNotLoaded){
loadLogoAnimeUp();
upNotLoaded = false;
}
}
});

I think you might find this is a very hacky way to do it, but this should work.
var animated;
$(window).scroll(function() {
var scroll = $(window).scrollTop(),
headerHeight = $('.navbar').outerHeight();
if(scroll > headerHeight) {
if (animated == true) {
loadLogoAnimeDown();
animated = false;
}
} else{
if (animated == false) {
loadLogoAnimeUp();
animated = true;
}
}
});

Related

jQuery scrollTop() returns wrong offset on scroll-direction change

I'm trying to get the correct scroll direction via jQuery's "scroll" event.
For this, I'm using the solution here: https://stackoverflow.com/a/4326907/8407840
However, if I change the direction of my scroll, the offset returned by scrollTop is incorrect on the first time. This results in the following behavior:
Wheel down -> down
Wheel down -> down
Wheel up -> down
Wheel up -> up
Wheel down -> up
Wheel down -> down
... and so on, I think you get it.
var ACTIVE_SECTION = null;
var ANIMATION_DURATION = 700;
$(document).ready(function() {
ACTIVE_SECTION = $("section:first-of-type").get(0);
var prevPosition = $(window).scrollTop();
$(window).on("scroll", function() {
doScrollingStuff(prevPosition);
});
});
function doScrollingStuff(prevPosition) {
var ctPosition = $(window).scrollTop();
var nextSection = ACTIVE_SECTION;
// Remove and re-append event, to prevent it from firing too often.
$(window).off("scroll");
setTimeout(function() {
$(window).on("scroll", function() {
doScrollingStuff(prevPosition);
});
}, ANIMATION_DURATION + 100);
// Determine scroll direction and target the next section
if(ctPosition < prevPosition) {
console.log("up");
nextSection = $(ACTIVE_SECTION).prev("section").get(0);
} else if(ctPosition > prevPosition) {
console.log("down");
nextSection = $(ACTIVE_SECTION).next("section").get(0);
}
// If a next section exists: Scroll to it!
if(typeof nextSection != 'undefined') {
var offset = $(nextSection).offset();
$("body, html").animate({
scrollTop: offset.top
}, ANIMATION_DURATION);
ACTIVE_SECTION = nextSection;
} else {
nextSection = ACTIVE_SECTION;
}
console.log(ACTIVE_SECTION);
prevPosition = ctPosition;
}
section {
width:100%;
height:100vh;
padding:60px;
box-sizing:border-box;
}
section:nth-child(1) { background:#13F399; }
section:nth-child(2) { background:#14FD43; }
section:nth-child(3) { background:#4EE61E; }
section:nth-child(4) { background:#BEFD14; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="sect1">Section 1</section>
<section id="sect2">Section 2</section>
<section id="sect3">Section 3</section>
<section id="sect4">Section 4</section>
Here's a pen, where you can see my implementation: https://codepen.io/EigenDerArtige/pen/aVEyxd
I am trying to accomplish an autoscroll to the next or previous section, whenever the user scrolls or swipes up/down... Therefore I only fire the "scroll"-event once every second, to prevent multiple scrolljacks all happening at once... However the above behavior seems to result in the user being scrolled to the wrong section.
I've been trying for a couple of hours now to get it working, but to no avail. Help is greatly appreciated!
The problem lies in the assignment prevPosition = ctPosition.
Each time the scroll handler runs, var ctPosition = $(window).scrollTop(); is good for determining scroll direction, however it's not the value that should be rememberad as prevPosition.
prevPosition needs to be $(window).scrollTop() as measured after the animation has completed.
Try this :
$(document).ready(function() {
var ANIMATION_DURATION = 700;
var ACTIVE_SECTION = $("section:first-of-type").eq(0);
var prevPosition = $(window).scrollTop();
$(window).on("scroll", doScrollingStuff);
function doScrollingStuff(e) {
$(window).off("scroll");
var ctPosition = $(window).scrollTop();
var nextSection = (ctPosition < prevPosition) ? ACTIVE_SECTION.prev("section") : (ctPosition > prevPosition) ? ACTIVE_SECTION.next("section") : ACTIVE_SECTION; // Determine scroll direction and target the next section
// If next section exists and is not current section: Scroll to it!
if(nextSection.length > 0 && nextSection !== ACTIVE_SECTION) {
$("body, html").animate({
'scrollTop': nextSection.offset().top
}, ANIMATION_DURATION).promise().then(function() {
// when animation is complete
prevPosition = $(window).scrollTop(); // remember remeasured .scrollTop()
ACTIVE_SECTION = nextSection; // remember active section
$(window).on("scroll", doScrollingStuff); // no need for additional delay after animation
});
} else {
setTimeout(function() {
$(window).on("scroll", doScrollingStuff);
}, 100); // Debounce
}
}
});

jQuery: clone div multiple times on scroll

I'm trying to figure out how to repeatedly clone the contents of a div on scroll, thus giving the impression that the page goes on forever and ever. My markup thus far is as follows and a fiddle here too https://jsfiddle.net/guht49La/:
var inserated = false
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800 && inserated == false) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
inserated = true;
} else {
}
});
Although this only inserts it once, as I want to keep inserting it every 800px (for example) thus giving the impression that the page goes on forever and ever. Any suggestions on this would be greatly appreciated!
This will work
var inserated = false
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
inserated = true;
} else {
}
});
This is a complete guess, but perhaps give this a go:
var nextInsert = 800;
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= nextInsert) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
nextInsert += 800;
} else {
}
});
It is working, but it clones the div just once because you changed the inserated variable to true after inserting the first clone. It will work indefinitely if you delete it:
var inserated = false
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800 && inserated == false) {
var $button = $('.hd').clone();
($button).insertBefore('.ap');
// inserated = true;
} else {
}
});
Notice that inserated = true; is commented out.
That code, however, can (and almost certainly) creates a huge amount of clones, so I'd suggest controlling the scrolling insertion point using something along the lines of Nat Karmios answer
My suggestion is similar to jbmartinez answer, except I would drop the inserated variable altogether and use classes to determine elements to be cloned:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 800) {
var $button = $('.hd').not(".cloned").clone();
$button.addClass("cloned");
($button).insertBefore('.ap');
} else {
}
});
Would still need to adjust the scrolling mark as noted above tho.

If scrollTop is greater than value, then do this ONLY ONCE

When user scrolls past 10px from the top, I'd like to hijack their scroll and scroll them down to certain div. After this happens once, I'd like to release the scroll to be free to scroll wherever. How do I do this?
My current code works but it won't let user to scroll freely after that initial scroll:
$(window).scroll(function() {
//if I scroll more than 1000px...
if($(window).scrollTop() > 10){
$('html,body').animate({scrollTop : $('#main').offset().top}, 900, function(){
h = 2;
});
}
});
Try:
var scrolled = false;
$(window).scroll(function() {
//if I scroll more than 1000px...
if($(window).scrollTop() > 10 && scrolled == false){
$('html,body').animate({scrollTop : $('#main').offset().top}, 900, function(){
h = 2;
});
scrolled = true;
} else if($(window).scrollTop() == 0) {
scrolled = false;
}
});

How to find Multiple div reach top?

I have a survey page divided into sections. As the user scrolls, each section's header sticks to the top of the screen until the next section is reached. I was able to do it for the first and second section but I am not sure how to do it for the third one. There must be a better way to do this.
Here is my code and a jsfiddle
Thank you
var s = $("#block2 .question-title-block");
var pos = s.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
if ($(this).scrollTop() > 404) {
$('#block1 .question-title-block').addClass("sticky");
if (windowpos >= pos.top) {
$('#block2 .question-title-block').addClass("sticky");
$('#block1 .question-title-block').removeClass("sticky");
}
else{
$('#block2 .question-title-block').removeClass("sticky");
}
}
else{
$('#block1 .question-title-block').removeClass("sticky");
$('#block2 .question-title-block').removeClass("sticky");
}
})
If you want it to be applied to as many elements as you want, don't use them individually, use their class. Here is what you can do:
var titleBlocks = $(".question-title-block");
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
titleBlocks.each(function(){
$(this).toggleClass('sticky', $(this).parent().offset().top <= windowpos);
});
});
JS Fiddle Demo
try this (allows for any number of question blocks):
var containers = $('.question-block-container');
$(window).scroll(function () {
var windowpos = $(window).scrollTop();
containers.each(function () {
var container = $(this),
title = container.find('.question-title'),
contOffsetTop = container.offset().top,
conOffsetBottom = contOffsetTop + container.outerHeight() + 60; // 60 is margin bottom
if (windowpos >= contOffsetTop && windowpos <= conOffsetBottom) {
if (!title.hasClass("sticky")) {
title.addClass("sticky");
}
} else if (title.hasClass("sticky")) {
title.removeClass("sticky");
}
});
});
Example

Add class to element upon scroll

I'd like to add a class to an element when a user first scrolls away from the top of the page. If the user then scrolls back up and hits the top of the page I'd like that class removed.
Use of jQuery in the solution is fine.
try
$(window).scroll(function() {
$("id or class").removeClass("active");
var scroll = $(window).scrollTop();
if (scroll <= 500) {
$("#one").addClass("active");
}
else if (scroll <= 1000) {
$("#tow").addClass("active");
}
else {
$("#three").addClass("active");
}
}
So here is the solution you're looking for. Just customize it with your div tags.
$(document).ready(function () {
$(window).scroll(function(){
// get the height of #wrap
var h = $('#top').height();
var y = $(window).scrollTop();
if( y > (h*.25) ){
$("#sidef").fadeIn(1100);
} else {
$('#sidef').fadeOut(75);
}
});
});
var notAdded = true;
$(window).scroll(function(){
if( $(this).scrollTop() == 0){
$(elem).removeClass('classname');
notAdded = true;
}
else if(notAdded){
$(elem).addClass('classname');
notAdded = false;
}
});

Categories

Resources