ScrollMagic and GSAP on mobile only - javascript

You can see from my codepen that I have a logo on my website that fades out as you scroll down the page, which is triggered after a certain trigger has been fired. This is working the way I want it, except I only want this to fire on mobile browsers and mobile screen sizes.
I'm using scrollmagic.js with this also.
Does anyone know how to set this up so the effect will only work on mobile and screen sizes < 768px.
I'm fairly new to JS and so would appreciate baby steps.
thanks
// When the DOM is ready
$(window).on('load', function() {
// Init ScrollMagic Controller
var scrollMagicController = new ScrollMagic();
// Create Animation for 0.5s
var tween = TweenMax.to('#animation', 0.5, {
opacity: 0
});
// Create the Scene and trigger when visible
var scene = new ScrollScene({
triggerElement: '.scene',
offset: 150 /* offset the trigger 150px below #scene's top */
})
.setTween(tween)
.addTo(scrollMagicController);
// Add debug indicators fixed on right side
scene.addIndicators();
});
Codepen of what I currently have

I would wrap the scrollMagic block on an if statement that checks if it is a touch device or if it has a minimum with, depending on which behaviour you are interested in.
With Modernzr:
var agent = navigator.userAgent.toLowerCase();
var onlyTaps = Modernizr.touch ||
(agent.match(/(iphone|ipod|ipad)/) ||
agent.match(/(android)/) ||
agent.match(/(iemobile)/) ||
agent.match(/iphone/i) ||
agent.match(/ipad/i) ||
agent.match(/ipod/i) ||
agent.match(/blackberry/i) ||
agent.match(/bada/i));
if (onlyTaps) {
//magicScroll block here
} else {
//something else here
}
Now, if you are only interested on the device width then you can use screen.width:
if (screen.width < 480) {
//magicScroll block here
} else {
//something else here
}
The only caveat is that screen.width might return real pixels or not on some high density devices. It works as expected on iPhones and Macbook Pro w/retina displays.

Related

Do not execute jQuery script if CSS is of particular value

On my website, I have a sidebar DIV on the left and a text DIV on the right. I wanted to make the sidebar follow the reader as he or she scrolls down so I DuckDuckGo'ed a bit and found this then modified it slightly to my needs:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(function(){
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
$window.scroll(function(){
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
})
});
});//]]>
</script>
And it works just like I want it to. However, my website uses Skeleton framework to handle responsive design. I've designed it so that when it goes down to mobile devices (horizontal then vertical), sidebar moves from being to the left of the text to being above it so that text DIV can take 100% width. As you can probably imagine, this script causes the sidebar to cover parts of text as you scroll down.
I am completely new to jQuery and I am doing my best through trial-and-error but I've given up. What I need help with is to make this script not execute if a certain DIV has a certain CSS value (i.e. #header-logo is display: none).
Ideally, the script should check for this when user resizes the browser, not on website load, in case user resizes the browser window from normal size to mobile size.
I imagine it should be enough to wrap it in some IF-ELSE statement but I am starting to pull the hair out of my head by now. And since I don't have too much hair anyway, I need help!
Thanks a lot in advance!
This function will execute on window resize and will check if #header-logo is visible.
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
});
I think you need to check this on load to, because you don't know if the user will start with mobile view or not. You could do something like this:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
}).resize();
This will get executed on load and on resize.
EDIT: You will probably need to turn off the scroll function if #header-logo is not visible. So, instead of create the function inside the scroll event, you need to create it outside:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
function myScroll() {
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
}
$window.on('scroll', myScroll);
} else {
$(window).off('scroll', myScroll);
}
});
Didn't test it, but you get the idea.
$("#headerLogo").css("display") will get you the value.
http://api.jquery.com/css/
I also see you only want this to happen on resize, so wrap it in jquery's resize() function:
https://api.jquery.com/resize/

How do I add break point to slide and push responsive menu

I have two menus on my responsive site. A horizontal menu when the browser width is greater than 1024px and the Slide and Push (Right) Menu when the browser window is less than 1024px (I'm using the slide push menu found: http://tympanus.net/codrops/2013/04/17/slide-and-push-menus/).
If the browser window is less than 1024px and I click the toggle button the menu works fine, but with the menu open, when I expand my browser window greater than 1024px the Slide and Push Menu is still open and my horizontal menu is also showing now. My questions is , using javascript, how can I retract or push the menu back once my browser window reaches 1024px or greater.
Here is a link to the working files http://tinyurl.com/qxp7gjn
Here is the javascript for my menu:
var menuRight = document.getElementById('cbp-spmenu-s2'),
showRightPush = document.getElementById('showRightPush'),
body = document.body;
showRightPush.onclick = function () {
classie.toggle(this, 'active');
classie.toggle(body, 'cbp-spmenu-push-toleft');
classie.toggle(menuRight, 'cbp-spmenu-open');
disableOther('showRightPush');
};
$(window).resize(function () {
// Window width with legacy browsers.
windowWidth = document.documentElement.clientWidth || document.body.clientWidth;
if (windowWidth > 800) {
classie.toggle(this, 'active');
classie.toggle(body, 'cbp-spmenu-push-toright');
classie.toggle(menuRight, 'cbp-spmenu-close');
disableOther('showRightPush');
}
});
function disableOther(button) {
if (button !== 'showRightPush') {
classie.toggle(showRightPush, 'disabled');
}
}
Subash is on the right path, but this is a higher-performance version w/ support for older browsers as well:
$(window).resize(function() {
// Window width with legacy browsers.
windowWidth = document.documentElement.clientWidth || document.body.clientWidth;
if (windowWidth > 1023) {
// Do opposite of showRightPush.onclick.
}
});
Speed comparison: http://jsperf.com/jq-width-vs-client-width/5
(shameless plug) check out Responsive Menus for examples.
I really like that style, codrops has great stuff. I'm going to add it to the RM module.
You can use window resize function to do so. Below is the sample code. Please note that code only demonstrates the idea. You need to complete it to get it working like you expect.
$(window).resize(function () {
windowWidth = $(this).width();
if (windowWidth >= 1224 ) {
// push back the menu
}
}

Fixing Jank on Movement locked to Scroll on Android

I am creating a header that acts like the Chrome for Android Address bar. The effect is that the header is a pseudo sticky header that scrolls out of view as you scroll down and then you you begin to scroll back up the header scrolls back into view.
Right now it works fine on the desktop (around 60fps) but on Chrome for Android (on Nexus 7 2013) it is full of jank.
Demo: jsFiddle
Both the header and content area are moved with transform translateY which are more performant than pos:top
I am also using requestAnimationFrame to debounce scrolling and only change properties when it is most convenient for the browser.
The header is position: fixed; top: 0; and then scrolled in and out of view with transform: translateY(...);. Also instead of using margin-top to get the content out from underneath the header, I am using transform: translateY(...);
The basic structure of my js looks like:
var latestScrollTop = 0;
var lastReactedScrollTop = 0;
var ticking = false;
function DoScroll()
{
var builtUpScrollTop = latestScrollTop - lastReactedScrollTop;
// Fold the top bar while we are scrolling (lock it to scrolling)
$('header.main-header').css('transform', 'translateY(' ... 'px)');
HeaderHeightChange();
lastReactedScrollTop = latestScrollTop;
ticking = false;
}
function HeaderHeightChange()
{
// We need to update the margin-top for the content so we don't overlap it
$('main.content-area').css('transform', 'translateY(' ... 'px)');
}
function requestTick() {
if(!ticking) {
requestAnimationFrame(function(){
DoScroll();
});
}
ticking = true;
}
$(window).on('scroll', function(e) {
latestScrollTop = $(window).scrollTop();
requestTick();
});
The effect is not complete as it needs to resolve the fold after you finish scrolling (and is coded) but I do not want to complicate the issue when just the scroll movement lock to header is causing jank. I see paint rectangles when scrolling up and down even though I am changing transform which I assume the gpu is handling and shouldn't be painting.
Edit: It seems when debugging with ADB that there is a a bunch of clear grey outlined time in each frame.
Turns out that even though I was using transform: translateY() that you still need to add translateZ(0) to see the benefit of layers and having it gpu accelerated.
But I did also update my code to use a object literal code style and got rid of the forced synchronous layout warning in the timeline by reading then writing. This is coupled along with requestAnimationFrame.
Demo: jsFiddle
var myUtils = {
clamp: function(min, max, value) {
return Math.min(Math.max(value, min), max);
},
getTranslateYFromTransform: function(rawTransform) {
return parseFloat(rawTransform.match(/^matrix\((([+-]?[0-9]*\.?[0-9]*),\s*?){5}([+-]?[0-9]*\.?[0-9]*)\)$/)[3])
}
};
var scrollHeader = {
latestScrollTop: 0,
lastReactedScrollTop: 0,
headerHeight: 0,
headerTransformTranslateY: 0,
ticking: false,
requestTick: function() {
if(!scrollHeader.ticking) {
requestAnimationFrame(function(){
scrollHeader.doHeaderFold();
});
}
scrollHeader.ticking = true;
},
doHeaderFold: function() {
var header = $('header.main-header');
var builtUpScrollTop = scrollHeader.latestScrollTop - scrollHeader.lastReactedScrollTop;
scrollHeader.headerHeight = header.outerHeight();
scrollHeader.headerTransformTranslateY = myUtils.clamp(-parseInt(scrollHeader.headerHeight), 0, (myUtils.getTranslateYFromTransform(header.css('transform')) - builtUpScrollTop));
// Fold the top bar while we are scrolling (lock it to scrolling)
header.css('transform', 'translateY(' + scrollHeader.headerTransformTranslateY + 'px) translateZ(0)');
scrollHeader.headerHeightChange();
scrollHeader.lastReactedScrollTop = scrollHeader.latestScrollTop;
scrollHeader.ticking = false;
},
headerHeightChange: function() {
// We need to update the margin-top for the content so we don't overlap it
$('main.content-area').css('transform', 'translateY(' + (scrollHeader.headerHeight + scrollHeader.headerTransformTranslateY) + 'px) translateZ(0)');
}
};
$(window).on('scroll', function(e) {
//console.log(e);
scrollHeader.latestScrollTop = $(window).scrollTop();
scrollHeader.requestTick();
});
This makes the timeline debugging on ADB (Nexus 7 2013) look like(very smooth):
Also to get rid of a small jump when first scrolling add transform: translateZ(0) to your element before animating it.

Hide address bar not working - bulletproof approach needed

At the moment I am writing some kind of web app and I want to hide the address bar on iOS devices and preferably also on Android devices.
Normally I do this with
window.addEventListener( 'load', function () {
setTimeout( function () {
window.scrollTo( 0, 1 );
}, 0 );
});
but this won't work now because the page hasn't enough content to scroll.
Now I know this is a common problem and I know that there are multiple solutions, but I would prefer a small, bulletproof solution.
Actually I was quite happy when I found this question: http://stackoverflow.com/questions/9678194/cross-platform-method-for-removing-the-address-bar-in-a-mobile-web-app
where this code was posted:
function hideAddressBar()
{
if(!window.location.hash)
{
if(document.height < window.outerHeight)
{
document.body.style.height = (window.outerHeight + 50) + 'px';
}
setTimeout( function(){ window.scrollTo(0, 1); }, 50 );
}
}
window.addEventListener("load", function(){ if(!window.pageYOffset){ hideAddressBar(); } } );
window.addEventListener("orientationchange", hideAddressBar );
Unfortunately, this doesn't work for me. I see that something happens because some elements that have padding-top set in percentages move down, but the address bar stays.
Of course I also did a Google search and tried many snippets I found. Some did nothing, some just moved the elements with padding-top down a bit.
The only working code I found is this:
var page = document.getElementById('page'),
ua = navigator.userAgent,
iphone = ~ua.indexOf('iPhone') || ~ua.indexOf('iPod'),
ipad = ~ua.indexOf('iPad'),
ios = iphone || ipad,
// Detect if this is running as a fullscreen app from the homescreen
fullscreen = window.navigator.standalone,
android = ~ua.indexOf('Android'),
lastWidth = 0;
if (android) {
// Android's browser adds the scroll position to the innerHeight, just to
// make this really difficult. Thus, once we are scrolled, the
// page height value needs to be corrected in case the page is loaded
// when already scrolled down. The pageYOffset is of no use, since it always
// returns 0 while the address bar is displayed.
window.onscroll = function() {
page.style.height = window.innerHeight + 'px'
}
}
var setupScroll = window.onload = function() {
// Start out by adding the height of the location bar to the width, so that
// we can scroll past it
if (ios) {
// iOS reliably returns the innerWindow size for documentElement.clientHeight
// but window.innerHeight is sometimes the wrong value after rotating
// the orientation
var height = document.documentElement.clientHeight;
// Only add extra padding to the height on iphone / ipod, since the ipad
// browser doesn't scroll off the location bar.
if (iphone && !fullscreen) height += 60;
page.style.height = height + 'px';
} else if (android) {
// The stock Android browser has a location bar height of 56 pixels, but
// this very likely could be broken in other Android browsers.
page.style.height = (window.innerHeight + 56) + 'px'
}
// Scroll after a timeout, since iOS will scroll to the top of the page
// after it fires the onload event
setTimeout(scrollTo, 0, 0, 1);
};
(window.onresize = function() {
var pageWidth = page.offsetWidth;
// Android doesn't support orientation change, so check for when the width
// changes to figure out when the orientation changes
if (lastWidth == pageWidth) return;
lastWidth = pageWidth;
setupScroll();
})();
Source
But I am not really happy with this solution as I am not a friend of UA sniffing.
Do you have any suggestions what I could try to make it work without UA sniffing? Can it be my HTML that causes problems with some scripts I posted?
Don't know if it's bulletproof, but it works on a bunch of devices. If you find caveat, let me know.
if (((/iphone/gi).test(navigator.userAgent) || (/ipod/gi).test(navigator.userAgent)) &&
(!("standalone" in window.navigator) && !window.navigator.standalone)) {
offset = 60;
$('body').css('min-height', (window.innerHeight + offset) + 'px');
setTimeout( function(){ window.scrollTo(0, 1); }, 1 );
}
if ((/android/gi).test(navigator.userAgent)) {
offset = 56;
$('html').css('min-height', (window.innerHeight + offset) + 'px');
setTimeout( function(){ window.scrollTo(0, 1); }, 0 );
}

How to detect/disable inertial scrolling in Mac Safari?

Is there a way to disable or detect that wheel events are from the "inertia" setting on a Mac?
I'd like to be able to tell the difference between real events and the others...or disable that kind of scrolling for a particular page.
I found a solution that works really well for this. Below is some pasted code from my project. It basically comes down to this logic:
A scroll event is from a human when ANY ONE of these conditions are true:
The direction is the other way around than the last one
More than 50 milliseconds passed since the last scroll event (picked 100ms to be sure)
The delta value is at least as high as the previous one
Since Mac spams scroll events with descreasing delta's to the browser every 20ms when inertial scrolling is enabled, this is a pretty failsafe way. I've never had it fail on me at least. Just checking the time since the last scroll won't work because a user won't be able to scroll again if the "virtual freewheel" is still running even though they haven't scrolled for 3 seconds.
this.minScrollWheelInterval = 100; // minimum milliseconds between scrolls
this.animSpeed = 300;
this.lastScrollWheelTimestamp = 0;
this.lastScrollWheelDelta = 0;
this.animating = false;
document.addEventListener('wheel',
(e) => {
const now = Date.now();
const rapidSuccession = now - this.lastScrollWheelTimestamp < this.minScrollWheelInterval;
const otherDirection = (this.lastScrollWheelDelta > 0) !== (e.deltaY > 0);
const speedDecrease = Math.abs(e.deltaY) < Math.abs(this.lastScrollWheelDelta);
const isHuman = otherDirection || !rapidSuccession || !speedDecrease;
if (isHuman && !this.animating) {
this.animating = true; // current animation starting: future animations blocked
$('.something').stop().animate( // perform some animation like moving to the next/previous page
{property: value},
this.animSpeed,
() => {this.animating = false} // animation finished: ready for next animation
)
}
this.lastScrollWheelTimestamp = now;
this.lastScrollWheelDelta = e.deltaY;
},
{passive: true}
);
There's one caveat by the way: Mac also has acceleration on the scrolling, i.e.: at first, the delta value is higher for each successive event. It seems like this does not last more than 100ms or so though. So if whatever action/animation you are firing as a result of the scroll event lasts at least 100ms and blocks all other actions/animations in the meantime, this is never a problem.
Yes and no.
You can use touchdown/up, and scroll as events to look for the page moving about but those won't trigger if the OS is doing an inertial scroll. Fun, right?
One thing that you can continually detect, however, is window.pageYOffset. That value will keep changing while an inertial scroll is happening but won't throw an event. So you can come up with a set of timers to keep checking for an inertial scroll and keep running itself until the page has stopped moving.
Tricky stuff, but it should work.
Oh how is this issue killing me :/
I'm in the process of creating "endless" scrolling large file viewer.
To make situation worse, this editor is embedded in page that has its own scroll bar, because its bigger than one screen.
U use overflow-x scroll for horizontal scroll, but for vertical scroll i need current line highlighter (as seen in most modern IDEs) so i'm using jquery mousewheel plugin, and scrolling moving content for line height up or down.
It works perfectly on ubuntu/chrome but on MacOS Lion/Chrome sometimes, and just sometimes,
when you scroll, it doesn't prevent default scroll on the editor element, and event propagates "up" and page it self starts to scroll.
I cant even describe how much annoying that is.
As for inertial scroll it self, i successfully reduced it with two timers
var self = this;
// mouse wheel events
$('#editorWrapper').mousewheel(function (event, delta, deltax, deltay) {
self._thisScroll = new Date().getTime();
//
//this is entirely because of Inertial scrolling feature on mac os :(
//
if((self._thisScroll - self._lastScroll) > 5){
//
//
// NOW i do actual moving of content
//
//
self._lastScroll = new Date().getTime();
}
5ms is value i found to have most natural feel on my MacBook Pro, and you have to scroll mouse wheel really fast to catch one of those..
Even still, sometimes on Mac listener on mac wrapper doesn't prevent default, and page scrolls down.
Well, (I might be wrong), I think that the "inertia" settings on the Mac are all computed by the system itself, the browser, or any program for that matter would just think that the user is scrolling quickly, rather than slowing down.
I'm not sure about other browsers, but the following event fires during inertial scroll on my Chrome, FF, Safari (mac):
var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";
function scrollEE (e) {
console.log(e);
}
window.addEventListener(mousewheelevt, scrollEE, false);
I had a big problem with an object animating based on scroll position after the scroll had completed, and the inertial scroll was really messing me around. I ended up calculating the velocity to determine how long the inertial scroll would last and used that to wait before animating.
var currentY = 0;
var previousY = 0;
var lastKnownVelocity = 0;
var velocityRating = 1;
function calculateVelocity() {
previousY = currentY;
currentY = $('#content').scrollTop();
lastKnownVelocity = previousY - currentY;
if (lastKnownVelocity > 20 || lastKnownVelocity < -20) {
velocityRating = 5;
} else {
velocityRating = 1;
}
}
$('#content').scroll(function () {
// get velocity while scrolling...
calculateVelocity();
// wait until finished scrolling...
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function() {
// do your animation
$('#content').animate({scrollTop: snapPoint}, 300);
}, 300*velocityRating)); // short or long duration...
});
There's a library that solves this problem.
https://github.com/d4nyll/lethargy
After installing it, use it like this:
var lethargy = new Lethargy();
$(window).bind('mousewheel DOMMouseScroll wheel MozMousePixelScroll', function(e){
if(lethargy.check(e) === false) {
console.log('stopping zoom event from inertia')
e.preventDefault()
e.stopPropagation();
}
console.log('Continue with zoom event from intent')
});
Following your instructions with my type of code, I had to set timeout of 270ms on each action activated by scroll to get it all smooth, so if anyone is using something similar to me here is my example if not ignore it, hope it will help you.
//Event action
function scrollOnClick(height) {
$('html').animate({
scrollTop: height
}, 'fast');
return false;
};
// Scroll on PC
let timer = false;
$(window).on('mousewheel', function (event) {
if(timer != true) {
var heightWindow = $(window).height();
var heightCurrent = $(window).scrollTop();
if (event.originalEvent.wheelDelta >= 1) {
if (heightWindow >= heightCurrent) {
timer= true;
scrollOnClick(0)
setTimeout(function (){
timer = false;
},270);
}
} else {
if (heightCurrent < heightWindow) {
timer= true;
scrollOnClick(heightWindow)
setTimeout(function (){
timer = false;
},270);
}
}
}
});

Categories

Resources