Trigger Greensock animation if body hasClass - javascript

I have a class of .header-is-active that is applied to the <body> tag when a user scrolls.
I would like an animation to be triggered when the class is added and then the animation to run in reverse when the class is removed.
Everything happens as expected except for the animation. I'm using jQuery and Greensock to make everything happen.
Here's what I currently have:
$(function() {
var body = $('body');
var trigger = $('.trigger');
var tween = TweenMax.to(trigger, 0.5, {css:{height: "100vh"},});
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 50) {
body.addClass('header-is-active');
tween();
} else {
body.removeClass('header-is-active');
}
});
});
The issue I have is the tweened value height: 100vh is being applied regardless with .header-is-active or not. Is there something missing?

At the end of your $(window).scroll() function, give this a shot:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 50) {
body.addClass('header-is-active');
tween();
} else {
body.removeClass('header-is-active');
}
// jQuery way
if(body.hasClass('header-is-active')) {
// Run animation
} else {
// Run reverse animation
}
// Non-jQuery way (just for reference)
var body = document.body;
if(body.classList.contains('header-is-active') {
// Run animation
} else {
// Run reverse animation
}
});
If it doesn't work, since it's running async, you can add a setTimeout() to the above so it's called after your function. It should look something like this
setTimeout(function() {
if(body.hasClass('header-is-active')) {
// run animation
} else {
// run reverse
}
}, 0);

Related

jQuery "Snap To" Effect

I have a specific effect I want for a website I'm building. As you can see in this website, I want the screen to "snap to" the next section after the user scrolls, but only after (not the instant) the scroll event has fired. The reason I don't want to use a plugin like panelSnap is because I
1: Want smaller code and
2. Want the website, when viewed on mobile, to have more of the "instant snap" effect (try reducing the browser size in the website mentioned above). I know I theoretically could try combining two plugins, like panelsnap and scrollify, and activate them appropriately when the browser is a certain width, but I don't know if I want to do that... :(
So all of that said, here's the code:
var scrollTimeout = null;
var currentElem = 0;
var options = {
scrollSpeed: 1100,
selector: 'div.panels',
scrollDelay: 500,
};
$(document).ready(function() {
var $snapElems = $(options.selector);
console.log($($snapElems[currentElem]).offset().top);
function snap() {
if ($('html, body').scrollTop() >= $($snapElems[currentElem]).offset().top) {
if (currentElem < $snapElems.length-1) {
currentElem++;
}
}else{
if (currentElem > 0) {
currentElem = currentElem - 1;
}
}
$('html, body').animate({
scrollTop: $($snapElems[currentElem]).offset().top
}, options.scrollSpeed);
}
$(window).scroll(function() {
if ($(window).innerWidth() > 766) {
if (scrollTimeout) {clearTimeout(scrollTimeout);}
scrollTimeout = setTimeout(function(){snap()}, options.scrollDelay);
}else{
//I'll deal with this later
}
});
});
My problem is that every time the snap function is called, it triggers the scroll event, which throws it into a loop where the window won't stop scrolling between the first and second elements. Here's the poor, dysfunctional site: https://tcfchurch.herokuapp.com/index.html Thank for the help.
You can use a boolean to record when the scroll animation in snap is in progress and prevent your $(window).scroll() event handler from taking any action.
Here's a working example:
var scrollTimeout = null;
var currentElem = 0;
var options = {
scrollSpeed: 1100,
selector: 'div.panels',
scrollDelay: 500,
};
$(document).ready(function() {
var scrollInProgress = false;
var $snapElems = $(options.selector);
console.log($($snapElems[currentElem]).offset().top);
function snap() {
if ($('html, body').scrollTop() >= $($snapElems[currentElem]).offset().top) {
if (currentElem < $snapElems.length-1) {
currentElem++;
}
}else{
if (currentElem > 0) {
currentElem = currentElem - 1;
}
}
scrollInProgress = true;
$('html, body').animate({
scrollTop: $($snapElems[currentElem]).offset().top
}, options.scrollSpeed, 'swing', function() {
// this function is invoked when the scroll animate is complete
scrollInProgress = false;
});
}
$(window).scroll(function() {
if (scrollInProgress == false) {
if ($(window).innerWidth() > 766) {
if (scrollTimeout) {clearTimeout(scrollTimeout);}
scrollTimeout = setTimeout(function(){snap()}, options.scrollDelay);
}else{
//I'll deal with this later
}
}
});
});
The variable scrollInProgress is set to false by default. It is then set to true when the scroll animate starts. When the animate finishes, scrollInProgress is set back to false. A simple if statement at the top of your $(window).scroll() event handler prevents the handler from taking any action while the animate scroll is in progress.
Have you considered using the well known fullPage.js library for that? Check out this normal scroll example. The snap timeout is configurable through the option fitToSectionDelay.
And nothing to worry about the size... it is 7Kb Gzipped!
I know I theoretically could try combining two plugins, like panelsnap and scrollify, and activate them appropriately when the browser is a certain width, but I don't know if I want to do that
fullPage.js also provides responsiveWidth and responsiveHeight options to turn it off under certain dimensions.

How to animate with delay TweenMax.to?

I created an animation with TweenMax, that animate a div from 100% width of it's parent to zero. I have three divs next to each other, that are overlapping the image below. Now I would like that each preload div class will start some seconds after the previous one was triggered.
I try something like setTimeout, but I couldn't get it work.
How can I achieve above?
CodePen: https://codepen.io/anon/pen/aWVZXL
I have changed the script. Please refactor if you want.
$(document).ready(function() {
var toBeAnimated;
var currentAnimat = 0;
$('.link').click(function() {
toBeAnimated = $(".preloader");
console.log('lets start animation');
preload(toBeAnimated[currentAnimat]);
});
function preload(elem) {
var elem = $(elem);
var width = elem.outerWidth();
// Tween out preload div
TweenMax.to(elem, 1.4, {
width: 0,
right: 0,
onComplete: function() {
elem.remove();
currentAnimat++;
if(currentAnimat >= toBeAnimated.length) {
console.log('Animation done');
} else {
preload(toBeAnimated[currentAnimat]);
}
}
});
}
});

Slide div on and off the page on scroll without interrupting the animation when the user continues to scroll

I am trying to smoothly slide a div on and off the page (left to right) using jQuery only. I have accomplished the task, however if you continue to scroll up or down while the animation is still going, it will interrupt it in the middle of the action causing it to hesitate. I've run into this issue before and could never figure it out without using a plugin of some sort.
I know how to accomplish this with CSS transitions, jQuery UI, greensock, etc., but I am curious if there is a way to prevent that interruption with jQuery only. I am open to a pure JavaScript solution (no jQuery) as well if there is one.
My code:
var amountScrolled = 50;
$(window).scroll(function() {
if ($(window).scrollTop() > amountScrolled) {
$('#slide').stop().animate({marginLeft:"0px"}, 500);
} else {
$('#slide').stop().animate({marginLeft: "-400px"}, 500);
}
});
Example: https://jsfiddle.net/Hysteresis/hg9cvxop/6/
This works: JSFIDDLE link
It's all about the Callback Functions!
var amountScrolled = 50;
var loopRunning = 0;
$(window).scroll(function() {
if ($(window).scrollTop() > amountScrolled){
if(loopRunning === 0){
animateSlide("0px",500);
}
} else {
if(loopRunning === 0){
animateSlide("-400px",500);
}
}
});
function animateSlide(px, time){
loopRunning = 1;
$('#slide').stop().animate({marginLeft:px}, time, function(){
loopRunning = 0;
});
}
Well, to answer your question rather than provide advice on better ways to do it, I usually handle tasks like this by assigning a temporary class to denote that something is in the process of being animated. As somebody else said, the reason for the stuttering is because the scroll function is getting called multiple times, so you keep stopping and restarting the animation.
So you can try something like this (Fiddle):
var amountScrolled = 50;
$(window).scroll(function() {
if ($('#slide').hasClass('sliding')) {
return;
}
if ($(window).scrollTop() > amountScrolled) {
$('#slide').stop().addClass('sliding').animate({marginLeft:"0px"}, 500, function() {
$(this).removeClass('sliding');
});
} else {
$('#slide').stop().addClass('sliding').animate({marginLeft: "-400px"}, 500, function() {
$(this).removeClass('sliding');
});
}
});

Track the scroll position beyond elements

I'm putting together a jQuery plugin. The plugin takes panels, and auto-sizes their height. So I start off with something like this:
<div class="panel">Test 1</div>
<div class="panel">Test 2</div>
<div class="panel">Test 3</div>
The code for that looks something like:
sizePanels: function(){
panels.each(function(){
$(this).height(docHeight);
});
},
There is a down button, that when clicked, will take the user to the next $(".panel):
nextPanel: function(){
$.scrollTo($(".panel:eq(" + panelIndex + ")"), 250, { easing: "swing" });
}
With that, I'm keeping track of the panel index that their on:
if (panelIndex < (panelCount - 1) ) {
panelIndex += 1;
}
I'm trying to figure out a way to track if they happen to scroll manually, and pass one of the elements, to then increase the "panelIndex", so that the button doesn't move them up instead of down because it was never incremented properly due to the user using the scroll bar instead of the button. This is what I have so far:
$(window).scroll(function(){
panels.each(function(index){
if ($(window).scrollTop() > $(this).scrollTop()) {
panelIndex = index;
// console.log(index);
}
});
if (panelIndex < panelCount - 1){
s.showDownButton();
}
});
The code excessively checks and feels somewhat overboard. is there a better way to do it?
An easy optimization is to only calculate the scrollTop once and to exit the each loop when a match is found. You can exit a $.each loop by returning false.
$(window).scroll(function(){
var scrollTop = $(window).scrollTop();
panels.each(function(index){
if (scrollTop > $(this).scrollTop()) {
panelIndex = index;
} else {
return false;
}
});
if (panelIndex < panelCount - 1){
s.showDownButton();
}
});
The next way that I would suggest optimizing this is to pre-calculate the scrollTop of each panel on page load (and when the viewport is resized). If you store these values in an array, then you can loop through them very quickly.
Here is some rough code to illustrate the idea:
var panelTops = [];
findPanelTops(); // calculate on load
$(window).on("resize", findPanelTops); // calculate on resize
function findPanelTops() {
panelTops = [];
panels.each(function(index) {
panelTops.push($(this).scrollTop());
});
}
$(window).scroll(function(){
var scrollTop = $(window).scrollTop();
for (var i = 0; i < panelTops.length; i++) {
if (scrollTop > panelTops[i]) {
panelIndex = i;
} else {
break;
}
};
if (panelIndex < panelCount - 1){
s.showDownButton();
}
});
The scroll event can fire a lot and very quickly, so you want to keep the amount of computation as minimal as possible. One way to get around all of this is to implement a scrollend handler. This will only fire when the scroll event has appeared to have stopped.
Here is some basic code for doing that. It will fire when the scroll event has stopped for more than 500ms:
var scrollTimeout = null;
function onScroll() {
if (scrollTimeout) {
clearTimeout(scrollTimeout);
}
scrollTimeout = setTimeout(onScrollEnd, 500);
}
function onScrollEnd() {
// Scrolling has stopped
// Do stuff ...
scrollTimeout = null;
}
$(window).on("scroll", onScroll);

Adding listener for position on screen

I'd like to set something up on my site where when you scroll within 15% of the bottom of the page an element flyouts from the side... I'm not sure how to get started here... should I add a listener for a scroll function or something?
I'm trying to recreate the effect at the bottom of this page: http://www.nytimes.com/2011/01/25/world/europe/25moscow.html?_r=1
update
I have this code....
console.log(document.body.scrollTop); //shows 0
console.log(document.body.scrollHeight * 0.85); //shows 1038.7
if (document.body.scrollTop > document.body.scrollHeight * 0.85) {
console.log();
$('#flyout').animate({
right: '0'
},
5000,
function() {
});
}
the console.log() values aren't changing when I scroll to the bottom of the page. The page is twice as long as my viewport.
[Working Demo]
$(document).ready(function () {
var ROOT = (function () {
var html = document.documentElement;
var htmlScrollTop = html.scrollTop++;
var root = html.scrollTop == htmlScrollTop + 1 ? html : document.body;
html.scrollTop = htmlScrollTop;
return root;
})();
// may be recalculated on resize
var limit = (document.body.scrollHeight - $(window).height()) * 0.85;
var visible = false;
var last = +new Date;
$(window).scroll(function () {
if (+new Date - last > 30) { // more than 30 ms elapsed
if (visible && ROOT.scrollTop < limit) {
setTimeout(function () { hide(); visible = false; }, 1);
} else if (!visible && ROOT.scrollTop > limit) {
setTimeout(function () { show(); visible = true; }, 1);
}
last = +new Date;
}
});
});
I know this is an old topic, but the above code that received the check mark was also triggering the $(window).scroll() event listener too many times.
I guess twitter had this same issue at one point. John Resig blogged about it here: http://ejohn.org/blog/learning-from-twitter/
$(document).ready(function(){
var ROOT = (function () {
var html = document.documentElement;
var htmlScrollTop = html.scrollTop++;
var root = html.scrollTop == htmlScrollTop + 1 ? html : document.body;
html.scrollTop = htmlScrollTop;
return root;
})();
// may be recalculated on resize
var limit = (document.body.scrollHeight - $(window).height()) * 0.85;
var visible = false;
var last = +new Date;
var didScroll = false;
$(window).scroll(function(){
didScroll = true;
})
setInterval(function(){
if(didScroll){
didScroll = false;
if (visible && ROOT.scrollTop < limit) {
hideCredit();
visible = false;
} else if (!visible && ROOT.scrollTop > limit) {
showCredit();
visible = true;
}
}
}, 30);
function hideCredit(){
console.log('The hideCredit function has been called.');
}
function showCredit(){
console.log('The showCredit function has been called.');
}
});
So the difference between the two blocks of code is when and how the timer is called. In this code the timer is called off the bat. So every 30 millaseconds, it checks to see if the page has been scrolled. if it's been scrolled, then it checks to see if we've passed the point on the page where we want to show the hidden content. Then, if that checks true, the actual function then gets called to show the content. (In my case I've just got a console.log print out in there right now.
This seems to be better to me than the other solution because the final function only gets called once per iteration. With the other solution, the final function was being called between 4 and 5 times. That's got to be saving resources. But maybe I'm missing something.
bad idea to capture the scroll event, best to use a timer and every few milliseconds check the scroll position and if in the range you need then execute the necessary code for what you need
Update: in the past few years the best practice is to subscribe to the event and use a throttle avoiding excessive processing https://lodash.com/docs#throttle
Something like this should work:
$(window).scroll(function() {
if (document.body.scrollTop > document.body.scrollHeight * 0.85) {
// flyout
}
});
document.body.scrollTop may not work equally well on all browsers (it actually depends on browser and doctype); so we need to abstract that in a function.
Also, we need to flyout only one time. So we can unbind the event handler after having flyed out.
And we don't want the flyout effect to slow down scrolling, so we will run our flytout function out of the event loop (by using setTimeout()).
Here is the final code:
// we bind the scroll event, with the 'flyout' namespace
// so we can unbind easily
$(window).bind('scroll.flyout', (function() {
// this function is defined only once
// it is private to our event handler
function getScrollTop() {
// if one of these values evaluates to false, this picks the other
return (document.documentElement.scrollTop||document.body.scrollTop);
}
// this is the actual event handler
// it has the getScrollTop() in its scope
return function() {
if (getScrollTop() > (document.body.scrollHeight-$(window).height()) * 0.85) {
// flyout
// out of the event loop
setTimeout(function() {
alert('flyout!');
}, 1);
// unbind the event handler
// so that it's not call anymore
$(this).unbind('scroll.flyout');
}
};
})());
So in the end, only getScrollTop() > document.body.scrollHeight * 0.85 is executed at each scroll event, which is acceptable.
The flyout effect is ran only one time, and after the event has returned, so it won't affect scrolling.

Categories

Resources