React scroll animation flickery - javascript

I created a simple scroll animation to fill a vertical timeline based on the scrolling position. Link to working example
My problem is that the animation is still quite flickery, especially on mobile devices. Is there any way to make the animation more smooth? I already tried to solve this with css transition, but that didn't work.

It’s simply because you keep changing the value instantly on scroll.
I tried and made it smooth by adding a very simple css transition to App.css in the code:
* {
transition: 150ms all;
}
Once it works, you can change the selector * to the vertical line element, because we dont want it applied to all elements right, this is only for demo.
Also another approach for this. I think by not changing height value all the time but when a certain difference is met.
For example change component to this code, maybe you can try it, at least on my PC it's smooth enough
let lastValue = 0;
function App() {
useEffect(() => {
const timeline = document.querySelector(".timeline");
const timelineDraw = document.querySelector(".timeline__draw");
const bodyRect = document.body.getBoundingClientRect();
const timelineOffset = timeline.getBoundingClientRect().top - bodyRect.top;
var moveIndicator = function () {
var viewportHeight = window.innerHeight;
var hasScrolled = window.pageYOffset;
const scrolledFurther = hasScrolled - timelineOffset + viewportHeight / 4;
lastValue = lastValue === 0 ? scrolledFurther:lastValue;
if (scrolledFurther && scrolledFurther > 0) {
if (scrolledFurther > timeline.clientHeight) {
timelineDraw.style.height = `${timeline.clientHeight}px`;
return;
}
if (Math.abs(lastValue - scrolledFurther) > 2){
lastValue = scrolledFurther;
timelineDraw.style.height = `${scrolledFurther}px`;
}
return;
}
timelineDraw.style.height = "0px";
};

Related

scrolling horizontally on section to create a conveyor belt effect on page scroll

Okay so I have been at this for quite some time. I have an example of what I am trying to do here
I have two rows on a fixed page. When i scroll on the page I want them to each scroll on the opposite direction. where I am failing at is that the rows are not infinite.
Is it so simple as to add children on scroll? When I do that it kind of works I guess but, I am unable to remove the first eight children without causing the whole thing to break. Any leads?
I have some code in this codepen
const row = document.getElementById('row');
const rowReverse = document.getElementById('row-reverse');
window.addEventListener('scroll', () => {{
row.appendChild(row.children[0].cloneNode(true));
rowReverse.style.transform = `translateX(-${window.scrollY}px) rotate(360deg) scaleX(-1)`;
row.style.transform = `translateX(${window.scrollY}px)`;
}});
const children = row.children.length;
const childrenArray = Array.from(row.children);
const lastChild = childrenArray[children - 1].getBoundingClientRect().right;
const windowWidth = window.innerWidth;
if (lastChild < windowWidth) {
childrenArray.forEach((child) => {
row.appendChild(child.cloneNode(true));
rowReverse.appendChild(child.cloneNode(true));
});
}

Animating a view change in iPhone and Android

Im trying to make a "UINavigationController type animation" in a Titanium project, however currently when I do the animation it does sort of a "pop back" animation where the view "comes out" of where the other one "went to". I have managed to figure out what's the value that determines where the animation ends, that is, the left property of the animation, but how do I set where the animation starts?
code to control animation:
function hideOldWindow() {
window.animate(animateOut, function(){});
}
function showNewWindow() {
var old = views[currentView];
window.remove(old);
currentView = (currentView + 1) % views.length;
var win = views[currentView];
viewControllers[currentView].onBecomeVisible();
window.add(win);
window.animate(animateIn, function(){});
}
var animateIn = Titanium.UI.createAnimation();
animateIn.left = 0;
animateIn.duration = 250;
animateIn.curve = Ti.UI.ANIMATION_CURVE_EASE_OUT;
var animateOut = Titanium.UI.createAnimation();
animateOut.left = -screenWidth + 1;
animateOut.duration = 250;
animateOut.curve = Ti.UI.ANIMATION_CURVE_EASE_OUT;
I don't know how is UINavigationController type animation, but to control where the animation starts, you have to set the left property of the view (this works for views I didn't try it on windows).
For example, to animate a view to appear, from left of the screen to the center, you can change the showNewWindow method to this:
function showNewWindow() {
var old = views[currentView];
window.remove(old);
currentView = (currentView + 1) % views.length;
var win = views[currentView];
viewControllers[currentView].onBecomeVisible();
window.add(win);
// NEW LINE
window.left = -screenWidth + 1;
window.animate(animateIn, function(){});
}
Now, window would appear from -screenWidth + 1 to left = 0.
Maybe you have to add a timeout before you animate the window to get it works.
Hope it helps

Synchronized scrolling using jQuery?

I am trying to implement synchronized scrolling for two DIV with the following code.
DEMO
$(document).ready(function() {
$("#div1").scroll(function () {
$("#div2").scrollTop($("#div1").scrollTop());
});
$("#div2").scroll(function () {
$("#div1").scrollTop($("#div2").scrollTop());
});
});
#div1 and #div2 is having the very same content but different sizes, say
#div1 {
height : 800px;
width: 600px;
}
#div1 {
height : 400px;
width: 200px;
}
With this code, I am facing two issues.
1) Scrolling is not well synchronized, since the divs are of different sizes. I know, this is because, I am directly setting the scrollTop value. I need to find the percentage of scrolled content and calculate corresponding scrollTop value for the other div. I am not sure, how to find the actual height and current scroll position.
2) This issue is only found in firefox. In firefox, scrolling is not smooth as in other browsers. I think this because the above code is creating a infinite loop of scroll events.
I am not sure, why this is only happening with firefox. Is there any way to find the source of scroll event, so that I can resolve this issue.
Any help would be greatly appreciated.
You can use element.scrollTop / (element.scrollHeight - element.offsetHeight) to get the percentage (it'll be a value between 0 and 1). So you can multiply the other element's (.scrollHeight - .offsetHeight) by this value for proportional scrolling.
To avoid triggering the listeners in a loop you could temporarily unbind the listener, set the scrollTop and rebind again.
var $divs = $('#div1, #div2');
var sync = function(e){
var $other = $divs.not(this).off('scroll'), other = $other.get(0);
var percentage = this.scrollTop / (this.scrollHeight - this.offsetHeight);
other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
// Firefox workaround. Rebinding without delay isn't enough.
setTimeout( function(){ $other.on('scroll', sync ); },10);
}
$divs.on( 'scroll', sync);
http://jsfiddle.net/b75KZ/5/
Runs like clockwork (see DEMO)
$(document).ready(function(){
var master = "div1"; // this is id div
var slave = "div2"; // this is other id div
var master_tmp;
var slave_tmp;
var timer;
var sync = function ()
{
if($(this).attr('id') == slave)
{
master_tmp = master;
slave_tmp = slave;
master = slave;
slave = master_tmp;
}
$("#" + slave).unbind("scroll");
var percentage = this.scrollTop / (this.scrollHeight - this.offsetHeight);
var x = percentage * ($("#" + slave).get(0).scrollHeight - $("#" + slave).get(0).offsetHeight);
$("#" + slave).scrollTop(x);
if(typeof(timer) !== 'undefind')
clearTimeout(timer);
timer = setTimeout(function(){ $("#" + slave).scroll(sync) }, 200)
}
$('#' + master + ', #' + slave).scroll(sync);
});
This is what I'm using. Just call the syncScroll(...) function with the two elements you want to synchronize. I found pawel's solution had issues with continuing to slowly scroll after the mouse or trackpad was actually done with the operation.
See working example here.
// Sync up our elements.
syncScroll($('.scroll-elem-1'), $('.scroll-elem-2'));
/***
* Synchronize Scroll
* Synchronizes the vertical scrolling of two elements.
* The elements can have different content heights.
*
* #param $el1 {Object}
* Native DOM element or jQuery selector.
* First element to sync.
* #param $el2 {Object}
* Native DOM element or jQuery selector.
* Second element to sync.
*/
function syncScroll(el1, el2) {
var $el1 = $(el1);
var $el2 = $(el2);
// Lets us know when a scroll is organic
// or forced from the synced element.
var forcedScroll = false;
// Catch our elements' scroll events and
// syncronize the related element.
$el1.scroll(function() { performScroll($el1, $el2); });
$el2.scroll(function() { performScroll($el2, $el1); });
// Perform the scroll of the synced element
// based on the scrolled element.
function performScroll($scrolled, $toScroll) {
if (forcedScroll) return (forcedScroll = false);
var percent = ($scrolled.scrollTop() /
($scrolled[0].scrollHeight - $scrolled.outerHeight())) * 100;
setScrollTopFromPercent($toScroll, percent);
}
// Scroll to a position in the given
// element based on a percent.
function setScrollTopFromPercent($el, percent) {
var scrollTopPos = (percent / 100) *
($el[0].scrollHeight - $el.outerHeight());
forcedScroll = true;
$el.scrollTop(scrollTopPos);
}
}
If the divs are of equal sizes then this code below is a simple way to scroll them synchronously:
scroll_all_blocks: function(e) {
var scrollLeft = $(e.target)[0].scrollLeft;
var len = $('.scroll_class').length;
for (var i = 0; i < len; i++)
{
$('.scroll_class')[i].scrollLeft = scrollLeft;
}
}
Here im using horizontal scroll, but you can use scrollTop here instead. This function is call on scroll event on the div, so the e will have access to the event object.
Secondly, you can simply have the ratio of corresponding sizes of the divs calculated to apply in this line $('.scroll_class')[i].scrollLeft = scrollLeft;
I solved the sync scrolling loop problem by setting the scroll percentage to fixed-point notation: percent.toFixed(0), with 0 as the parameter. This prevents mismatched fractional scrolling heights between the two synced elements, which are constantly trying to "catch up" with each other. This code will let them catch up after at most a single extra step (i.e., the second element may continue to scroll an extra pixel after the user stops scrolling). Not a perfect solution or the most sophisticated, but certainly the simplest I could find.
var left = document.getElementById('left');
var right = document.getElementById('right');
var el2;
var percentage = function(el) { return (el.scrollTop / (el.scrollHeight - el.offsetHeight)) };
function syncScroll(el1) {
el1.getAttribute('id') === 'left' ? el2 = right : el2 = left;
el2.scrollTo( 0, (percentage(el1) * (el2.scrollHeight - el2.offsetHeight)).toFixed(0) ); // toFixed(0) prevents scrolling feedback loop
}
document.getElementById('left').addEventListener('scroll',function() {
syncScroll(this);
});
document.getElementById('right').addEventListener('scroll',function() {
syncScroll(this);
});
I like pawel's clean solution but it lacks something I need and has a strange scrolling bug where it continues to scroll and my plugin will work on multiple containers not just two.
http://www.xtf.dk/2015/12/jquery-plugin-synchronize-scroll.html
Example & demo: http://trunk.xtf.dk/Project/ScrollSync/
Plugin: http://trunk.xtf.dk/Project/ScrollSync/jquery.scrollSync.js
$('.scrollable').scrollSync();
If you don't want proportional scrolling, but rather to scroll an equal amount of pixels on each field, you could add the value of change to the current value of the field you're binding the scroll-event to.
Let's say that #left is the small field, and #right is the bigger field.
var oldRst = 0;
$('#right').on('scroll', function () {
l = $('#left');
var lst = l.scrollTop();
var rst = $(this).scrollTop();
l.scrollTop(lst+(rst-oldRst)); // <-- like this
oldRst = rst;
});
https://jsfiddle.net/vuvgc0a8/1/
By adding the value of change, and not just setting it equal to #right's scrollTop(), you can scroll up or down in the small field, regardless of its scrollTop() being less than the bigger field. An example of this is a user page on Facebook.
This is what I needed when I came here, so I thought I'd share.
From the pawel solution (first answer).
For the horizzontal synchronized scrolling using jQuery this is the solution:
var $divs = $('#div1, #div2'); //only 2 divs
var sync = function(e){
var $other = $divs.not(this).off('scroll');
var other = $other.get(0);
var percentage = this.scrollLeft / (this.scrollWidth - this.offsetWidth);
other.scrollLeft = percentage * (other.scrollWidth - other.offsetWidth);
setTimeout( function(){ $other.on('scroll', sync ); },10);
}
$divs.on('scroll', sync);
JSFiddle
An other solution for multiple horizontally synchronized divs is this, but it works for divs with same width.
var $divs = $('#div1, #div2, #div3'); //multiple divs
var sync = function (e) {
var me = $(this);
var $other = $divs.not(me).off('scroll');
$divs.not(me).each(function (index) {
$(this).scrollLeft(me.scrollLeft());
});
setTimeout(function () {
$other.on('scroll', sync);
}, 10);
}
$divs.on('scroll', sync);
NB: Only for divs with same width
JSFiddle

Change margin top of div based on window scroll

I have a bar at the top of my page that is position fixed. When the user scrolls to a certain point I want the bar to start moving up as if it was relatively or absolutely positioned.
Right now the css of the bar changes from fixed to absolutely positioned but of course this sets the div straight to the top of the page.
I have been looking at this for ages and cannot get my head around how I would push the bar up one pixel at a time for every pixel scrolled past the _triggerOffset
Can anyone enlighten me?
function banner(){
var _barOffset = $('#top-bar').outerHeight(),
_navOffset = $('#navigation').offset().top,
_triggerOffset = _navOffset-_barOffset;
$(window).scroll(function() {
var _scroll = $(window).scrollTop();
if (_scroll >= _triggerOffset) {
$('#top-bar').css({'position':'absolute'});
}
});
}
banner();
I have done a fiddle.
Check this fiddle
Working Demo
$(document).ready(function() {
var postionToTriggerMove = 500;
var positioninitial = $(window).scrollTop();
var positioninitialLine = $(".line").offset().top;
$(window).scroll(function() {
var _scroll = $(window).scrollTop();
if(_scroll > positioninitial) {
if(_scroll >= (postionToTriggerMove - 5) && _scroll <= (postionToTriggerMove + 5) )
{
var topBarPostion = $(".line").offset().top;
$('.line').css({'position':'absolute',"top":topBarPostion});
}
}
else {
if(_scroll >= (postionToTriggerMove - 5) && _scroll <= (postionToTriggerMove + 5) )
{
var topBarPostion = $(".line").offset().top;
$('.line').css({'position':'fixed',"top":positioninitialLine});
}
}
positioninitial = _scroll;
});
});
You could try something like the below:
function banner(){
var _barOffset = $('#top-bar').outerHeight(),
_navOffset = $('#navigation').offset().top,
_triggerOffset = _navOffset-_barOffset;
$(window).scroll(function() {
var _scroll = $(window).scrollTop();
if (_scroll >= _triggerOffset) {
$('#top-bar').css({'position':'absolute','top':_triggerOffset - (_scroll-_triggerOffset)});
}
});
}
banner();
This code is highly untested, however what we are doing is initially setting the element to an absolute position and defining the top of this element as the _triggerOffset, then we take the difference between the current scroll and the triggerOffset and subtract this from the top position to make the bar move up the more you scroll down.
Not sure if that's what you had in mind, but I'd look at a solution like this. You might want to add some conditions in there to ensure that top never goes below 0 or the nav will go off the screen.
Thanks, had a play around with both examples and they worked pretty good.
In the end I tweaked my code and instead of making the bar position top 0px I made it position top with the pixels equal to the offset distance. Don't know why I didn't think of this before.
On another note I am using Shinov's code for anoher project as I quite like it :)
Thanks
function banner(){
var _barOffset = $('#top-bar').outerHeight(),
_navOffset = $('#navigation').offset().top,
_triggerOffset = _navOffset-_barOffset;
$(window).scroll(function() {
var _scroll = $(window).scrollTop();
if (_scroll >= _triggerOffset) {
$('#top-bar').css({'position':'absolute', 'top':_triggerOffset+'px'});
}else if (_scroll <= _triggerOffset){
$('#top-bar').css({'position':'fixed', 'top':'0px'});
}
});
}

scroll then snap to top

Just wondering if anyone has an idea as to how I might re-create a nav bar style that I saw a while ago, I just found the site I saw it on, but am not sure how they might have gotten there. Basically want it to scroll with the page then lock to the top...
http://lesscss.org/
Just do a quick "view source" on http://lesscss.org/ and you'll see this:
window.onscroll = function () {
if (!docked && (menu.offsetTop - scrollTop() < 0)) {
menu.style.top = 0;
menu.style.position = 'fixed';
menu.className = 'docked';
docked = true;
} else if (docked && scrollTop() <= init) {
menu.style.position = 'absolute';
menu.style.top = init + 'px';
menu.className = menu.className.replace('docked', '');
docked = false;
}
};
They're binding to the onscroll event for the window, this event is triggered when the window scrolls. The docked flag is set to true when the menu is "locked" to the top of the page, the menu is set to position:fixed at the same time that that flag is set to true. The rest is just some simple "are we about to scroll the menu off the page" and "are we about back where we started" position checking logic.
You have to be careful with onscroll events though, they can fire a lot in rapid succession so your handler needs to be pretty quick and should precompute as much as possible.
In jQuery, it would look pretty much the same:
$(window).scroll(function() {
// Pretty much the same as what's on lesscss.org
});
You see this sort of thing quite often with the "floating almost fixed position vertical toolbar" things such as those on cracked.com.
mu is too short answer is working, I'm just posting this to give you the jquery script!
var docked = false;
var menu = $('#menu');
var init = menu.offset().top;
$(window).scroll(function()
{
if (!docked && (menu.offset().top - $("body").scrollTop() < 0))
{
menu.css({
position : "fixed",
top: 0,
});
docked = true;
}
else if(docked && $("body").scrollTop() <= init)
{
menu.css({
position : "absolute",
top: init + 'px',
});
docked = false;
}
});
Mu's answer got me far. I tried my luck with replicationg lesscss.org's approach but ran into issues on browser resizing and zooming. Took me a while to find out how to react to that properly and how to reset the initial position (init) without jQuery or any other library.
Find a preview on JSFiddle: http://jsfiddle.net/ctietze/zeasg/
So here's the plain JavaScript code in detail, just in case JSFiddle refuses to work.
Reusable scroll-then-snap menu class
Here's a reusable version. I put the scrolling checks into a class because the helper methods involved cluttered my main namespace:
var windowScrollTop = function () {
return window.pageYOffset;
};
var Menu = (function (scrollOffset) {
var Menu = function () {
this.element = document.getElementById('nav');
this.docked = false;
this.initialOffsetTop = 0;
this.resetInitialOffsetTop();
}
Menu.prototype = {
offsetTop: function () {
return this.element.offsetTop;
},
resetInitialOffsetTop: function () {
this.initialOffsetTop = this.offsetTop();
},
dock: function () {
this.element.className = 'docked';
this.docked = true;
},
undock: function () {
this.element.className = this.element.className.replace('docked', '');
this.docked = false;
},
toggleDock: function () {
if (this.docked === false && (this.offsetTop() - scrollOffset() < 0)) {
this.dock();
} else if (this.docked === true && (scrollOffset() <= this.initialOffsetTop)) {
this.undock();
}
}
};
return Menu;
})(windowScrollTop);
var menu = new Menu();
window.onscroll = function () {
menu.toggleDock();
};
Handle zoom/page resize events
var updateMenuTop = function () {
// Shortly dock to reset the initial Y-offset
menu.undock();
menu.resetInitialOffsetTop();
// If appropriate, undock again based on the new value
menu.toggleDock();
};
var zoomListeners = [updateMenuTop];
(function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0];
var lastWidth = 0;
function pollZoomFireEvent() {
var widthNow = w.innerWidth || e.clientWidth || g.clientWidth;
if (lastWidth == widthNow) {
return;
}
lastWidth = widthNow;
// Length changed, user must have zoomed, invoke listeners.
for (i = zoomListeners.length - 1; i >= 0; --i) {
zoomListeners[i]();
}
}
setInterval(pollZoomFireEvent, 100);
})();
Sounds like an application of Jquery ScrollTop and some manipulation of CSS properties of the navbar element. So for example, under certain scroll conditions the navbar element is changed from absolute positioning with calculated co-ordinates to fixed positioning.
http://api.jquery.com/scrollTop/
The effect you describe would usually start with some type of animation, like in TheDeveloper's answer. Default animations typically slide an element around by changing its position over time or fade an element in/out by changing its opacity, etc.
Getting the "bouce back" or "snap to" effect usually involves easing. All major frameworks have some form of easing available. It's all about personal preference; you can't really go wrong with any of them.
jQuery has easing plugins that you could use with the .animate() function, or you can use jQueryUI.
MooTools has easing built in to the FX class of the core library.
Yahoo's YUI also has easing built in.
If you can remember what site it was, you could always visit it again and take a look at their source to see what framework and effect was used.

Categories

Resources