getBoundingClientRect() showing different values on load vs scroll - javascript

I'm working on a site for a client and trying to implement custom parallax functionality. I have used the following code -
var inView = function(element) {
// get window height
var windowHeight = window.innerHeight;
// Get Element Height
var elementHeight = element.clientHeight;
// get number of pixels that the document is scrolled
var scrollY = window.scrollY || window.pageYOffset;
// get current scroll position (distance from the top of the page to the bottom of the current viewport)
var scrollPosition = scrollY + windowHeight;
var elementPosition = element.getBoundingClientRect().top + scrollY;
var elementScrolled = elementPosition + element.clientHeight + windowHeight
// is scroll position greater than element position? (is element in view?)
if (scrollPosition > elementPosition && scrollPosition < elementScrolled) {
return true;
}
return false;
}
// Get all the elements to be parallaxed
const parallaxElements = {
element: document.querySelectorAll('#header-image img'),
ratio: 0.25
}
// The parallax function
const parallax = elements => {
let items = [...elements.element],
itemRatio = elements.ratio
if ('undefined' !== items && items.length > 0 ) {
items.forEach( item => {
if ( inView(item) == true ) {
item.style.transform = 'translate3d(0, ' + (itemRatio * (window.innerHeight - item.getBoundingClientRect().top)) + 'px ,0)'
}
})
}
}
//If element is in viewport, set its position
parallax(parallaxElements)
//Call the function on scroll
window.onscroll = () => {
parallax(parallaxElements)
}
It's working ok except that when the page is loaded initially and the user starts scrolling, the position of element (#header-image img in this case) changes abruptly. I did some digging and noticed that the value of getBoundingClientRect().top is causing the issue.
When the page is loaded, it has some value, and as soon as the user starts scrolling, it abruptly changes to another value.
I am not able to figure out why this is happening. getBoundingClientRect().top is supposed to get the value of element from top of viewport, right?
Any help is greatly appreciated. Thanks!
Pls check the screenshot of inspect element here -
https://i.stack.imgur.com/RYDvK.jpg

Related

How to add a jQuery scrollTop offset?

I'm trying to get the div to snap to the center of the viewport, right now it just snaps to the top. I was trying to put an offset of 50% but can only get it in px's.
EDIT
I added a new fiddle where I tried to include $(window).scrollTop() / 2)
http://jsfiddle.net/kZY9R/84/
$("#item").offset().top - 100
var body = $("html, body");
var items = $(".item");
var animating = false;
$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
if (!animating) {
$.data(this, 'scrollTimer', setTimeout(function() {
items.each(function(key, value) {
if ($(value).offset().top > $(window).scrollTop()) {
animating = true;
$(body).stop().animate( { scrollTop: $(value).offset().top }, 1000,'swing');
setTimeout(function() { animating = false; }, 2000);
return false;
}
});
}, 50));
}
});
I found this:
$('html, body').animate({scrollTop: $('#your-id').offset().top -100 }, 'slow');
Source: Run ScrollTop with offset of element by ID
Here's the trick to keep your viewport centralized on a particular div.
Prerequisites
You need to take into account the following three criteria to be able to centralize the viewport on a given item:
height of the last item that appeared on the viewport.
The distance of the last item from the top of the page, i.e. the offset().top of the item.
The height value of the viewport (i.e the window object).
Calculating Vertical Position of the Item
The required scrollTop value for the window can be calculated as in the following:
var scrollValue = itemOffset // offset of the item from the top of the page
- .5 * windowHeight // half the height of the window
+ .5 * itemHeight; // half the height of the item
You are basically, moving the top of your viewport to the item under view's top offset initially. This, as you've already experienced, snaps the item to the top of the window.
The real magic part comes when you subtract half of the window's height to go halfway along it vertically, and then shifting your view back down by adding half the item's height. This makes the item appear vertically centralized with regards to the viewport.
Note:
To be able to query the last item that appeared on the viewport, you have to iterate over all of the elements that have a top offset value (i.e. offset().top) less than or equal to that of the window's scrollTop value:
$.each($('.item'), function(i, value) {
if ($(viewport).scrollTop() >= $(this).offset().top) {
lastItemInView = $(this);
}
});
With the above, the lastItemInView variable will always end up with the last element visible in the window.
Demo
Not sure if you figured this out yet or not but I took some code from this answer (How to tell if a DOM element is visible in the current viewport?) that shows how to tell if an element is visible in the view port.
Using that I modified your code to loop through each item and find the first visible one in the viewport and then center that one also factoring in the margin-top you have. Let me know if this helps!
Fiddle: http://jsfiddle.net/kZY9R/86/
var body = $("html, body");
var items = $(".item");
var animating = false;
$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
if (!animating) {
$.data(this, 'scrollTimer', setTimeout(function() {
items.each(function(key, value) {
if (elementInViewport(value)) {
animating = true;
var margin = parseInt($(value).css('margin-top'));
$('html,body').animate({
scrollTop: $(value).offset().top - ($(window).height() + margin - $(value).outerHeight(true)) / 2
}, 200);
setTimeout(function() {
animating = false;
}, 2000);
return false;
}
});
}, 50));
}
});
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while (el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}

Watching for multiple elements without multiple if statements

I have a snippet that on scroll it checks wether an element is in the current viewport.
I now want to add multiple elements into the mix, but I wanted to avoid doing multiple if statements checking for each, I know the following code doesn't work but it is an example of how I would like to do it, is there a way of doing it this way?
var listOfPanels = $('#item2, #item2, #item3, #item4, #item5');
$(window).scroll(function(event) {
// if the element we're actually looking for exists
if (listOfPanels.length){
// check if the element is in the current view using the attached function
// and the event hasn't already fired
if (isElementInViewport(listOfPanels)) {
// do something
}
}
});
try this:
function isElementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
var listOfPanels = $('#item2, #item2, #item3, #item4, #item5');
$(window).scroll(function(event) {
if (listOfPanels.length){
listOfPanels.each(function(){
if (isElementInViewport($(this)[0])) {
console.log($(this).attr('id') + ' in viewport');
}
});
}
});
(isElementInViewport js method brought from: How to tell if a DOM element is visible in the current viewport?)
hope that helps.

parallax scrolling issue - div element jerking when scrolling in webkit browsers

I have created a parallax scroll, which seem to be working fine in firefox however in the chrome browser there's a slight jump on the body text when scrolling. click here scroll to the about section. I am not sure if t this is a css or JS issue.. below is a snippet i have incorporated into my parallax function
Does anyone know how i an fix this issue?
$(document).ready(function(){
// Cache the Window object
$window = $(window);
// Cache the Y offset and the speed of each sprite
$('[data-type]').each(function() {
$(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
$(this).data('Xposition', $(this).attr('data-Xposition'));
$(this).data('speed', $(this).attr('data-speed'));
});
// For each element that has a data-type attribute
$('[data-type="background"]').each(function(){
// Store some variables based on where we are
var $self = $(this),
offsetCoords = $self.offset(),
topOffset = offsetCoords.top;
// When the window is scrolled...
$(window).scroll(function() {
// If this section is in view
if ( ($window.scrollTop() + $window.height()) > (topOffset) &&
( (topOffset + $self.height()) > $window.scrollTop() ) ) {
// Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -($window.scrollTop() / $self.data('speed'));
// If this element has a Y offset then add it on
if ($self.data('offsetY')) {
yPos += $self.data('offsetY');
}
// Put together our final background position
var coords = '50% '+ yPos + 'px';
// Move the background
$self.css({ backgroundPosition: coords });
$('[data-type="scroll-text"]', $self).each(function() {
var $text= $(this);
var pos = ($window.scrollTop()/10) * $text.data('speed');
var curP = $text.css('margin-top');
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(is_chrome) {
$text.animate({
paddingTop: pos,
}, 200, 'linear', function() {
// Animation complete.
});
} else {
$text.css('padding-top', pos);
}
});
}; // in view
}); // window scroll
}); // each data-type
}); // document ready
Some suggestions:
1.) Use position: fixed to avoid any jitter, as you'll be taking the element out of the document flow. You can then position it using z-index.
2.) Cache as much as you can to ease processing time.
3.) Math.round may not be necessary, but try adding this CSS to your moving areas: -webkit-transform: translate3d(0,0,0); This will force hardware acceleration in Chrome, which may ease some of the jittering. (It looked smoother on my screen when I added this with Inspector, but it didn't get rid of the jumpiness with the scroll wheel.) Note: Don't do this on your entire document (e.g. body tag), as it might cause some issues with your current layout. (Your navigation bar didn't stick to the top of the window, for instance.)
4.) If you have any animations running as part of your parallax logic (tweening the margin into place or something along those lines), remove it - that would probably cause the jump you see.
Hope this helps. Best of luck.
I see the same jittering in FireFox and Chrome (Mac). Looking at your containers, one thing that's glaring at me is the pixel position that's being calculated/used.
Chrome: <div id="about-title" style="margin-top: 1562.3999999999999px;">
FireFox: <div id="about-title" style="margin-top: 1562.4px;">
Browsers aren't going to allow content to sit at 1/2 pixel, let alone 0.3999999 of a pixel. I think it's moving it, and trying to calculate whether to round up or round down. It jitters because it's calculating with every click of your mouse wheel.
Thus, I'd try adding Math.round() to your positions so that the containers are never being left in limbo.
Take a look at the code here: http://webdesigntutsplus.s3.amazonaws.com/tuts/338_parallax/src/index.html
Firebug some of the elements, and you'll see that their only fraction of a pixel is '0.5'. Most of them (the bulk) go to round number values.
You are going to have to change the way that the scrolling works (i.e. change how the spacing is computed), but this can be fixed by adding the position:fixed CSS element to the page elements that are scrolling. The problem is coming from the time that it takes for the JavaScript to process and then render.
For example, on your page you would set each of the <div> tags containing text to have a fixed position and then use the JavaScript/JQuery function to update the top: CSS element. This should make the page scroll smoothly.
Have you tried adding the preventdefault inside the scroll function?
$(window).scroll(function(e) {
e.preventDefault();
// rest of your code
}
In a previous question I created a fairly good parallax scrolling implementation. Jquery Parallax Scrolling effect - Multi directional You might find it useful.
Here's the JSFiddle http://jsfiddle.net/9R4hZ/40/ use the up/down arrows or scroll wheel.
Using padding and margin for the positioning are probably why you're experiencing rendering issues. While my code uses scroll or keyboard input for the effect you can loop the relavent portion and check the $moving variable until you reach the desired element on screen.
function parallaxScroll(scroll) {
// current moving object
var ml = $moving.position().left;
var mt = $moving.position().top;
var mw = $moving.width();
var mh = $moving.height();
// calc velocity
var fromTop = false;
var fromBottom = false;
var fromLeft = false;
var fromRight = false;
var vLeft = 0;
var vTop = 0;
if($moving.hasClass('from-top')) {
vTop = scroll;
fromTop = true;
} else if($moving.hasClass('from-bottom')) {
vTop = -scroll;
fromBottom = true;
} else if($moving.hasClass('from-left')) {
vLeft = scroll;
fromLeft = true;
} else if($moving.hasClass('from-right')) {
vLeft = -scroll;
fromRight = true;
}
// calc new position
var newLeft = ml + vLeft;
var newTop = mt + vTop;
// check bounds
var finished = false;
if(fromTop && (newTop > t || newTop + mh < t)) {
finished = true;
newTop = (scroll > 0 ? t : t - mh);
} else if(fromBottom && (newTop < t || newTop > h)) {
finished = true;
newTop = (scroll > 0 ? t : t + h);
} else if(fromLeft && (newLeft > l || newLeft + mw < l)) {
finished = true;
newLeft = (scroll > 0 ? l : l - mw);
} else if(fromRight && (newLeft < l || newLeft > w)) {
finished = true;
newLeft = (scroll > 0 ? l : l + w);
}
// set new position
$moving.css('left', newLeft);
$moving.css('top', newTop);
// if finished change moving object
if(finished) {
// get the next moving
if(scroll > 0) {
$moving = $moving.next('.parallax');
if($moving.length == 0)
$moving = $view.find('.parallax:last');
} else {
$moving = $moving.prev('.parallax');
if($moving.length == 0)
$moving = $view.find('.parallax:first');
}
}
// for debug
$('#direction').text(scroll + " " + l + "/" + t + " " + ml + "/" + mt + " " + finished + " " + $moving.text());
}
May not be related to your specifics, but I had a jumpy parallax scrolling problem, I was able to solve it adding the following CSS for the fixed portions of the page:
#supports (background-attachment: fixed)
{
.fixed-background
{
background-attachment: fixed;
}
}
Not sure of all the specifics, but found at Alternate Fixed & Scroll Backgrounds

Auto-scroll to the bottom of a div

I have a div with overflow set to scroll which essentially streams data line by line off a file. I'd like to scroll automatically to the bottom of the div whenever the stream overflows, but without using a "Click here to scroll to bottom" button.
I already know of the scrollTop = scrollHeight solution, but that requires some kind of event trigger on the client's side. I don't want this element to be interactive; it should scroll by itself.
Is there any way to achieve this?
A lot of the scrollHeight implementations didn't work for me, offsetHeight seemed to do the trick.
Pretty sure that scrollHeight tries to move it to the bottom of the height of the static element, not the height of the scrollable area.
var pane = document.getElementById('pane');
pane.scrollTop = pane.offsetHeight;
There's no way to automatically scroll an element to the bottom. Use element.scrollTop = element.scrollHeight.
If you don't know when the element is going to resize, you could add a poller:
(function(){
var element = document.getElementById("myElement");
var lastHeight = element.scrollHeight;
function detectChange(){
var currentHeight = element.scrollHeight;
if(lastHeight != currentHeight){
element.scrollTop = currentHeight;
lastHeight = currentHeight;
}
}
detectChange();
setInterval(detectChange, 200); //Checks each 200ms = 5 times a second
})();
Some old code of mine with a running example that will stay at the bottom when new content is added, if the user scrolls it will not more it to the bottom.
var chatscroll = new Object();
chatscroll.Pane =
function(scrollContainerId)
{
this.bottomThreshold = 25;
this.scrollContainerId = scrollContainerId;
}
chatscroll.Pane.prototype.activeScroll =
function()
{
var scrollDiv = document.getElementById(this.scrollContainerId);
var currentHeight = 0;
if (scrollDiv.scrollHeight > 0)
currentHeight = scrollDiv.scrollHeight;
else
if (objDiv.offsetHeight > 0)
currentHeight = scrollDiv.offsetHeight;
if (currentHeight - scrollDiv.scrollTop - ((scrollDiv.style.pixelHeight) ? scrollDiv.style.pixelHeight : scrollDiv.offsetHeight) < this.bottomThreshold)
scrollDiv.scrollTop = currentHeight;
scrollDiv = null;
}

scroll page so that element is visible

I've just tried prototype's scrollTo function and as the documentation states, it
Scrolls the window so that element
appears at the top of the viewport
I'd like a function that
only scrolls if the element is not entirely visible within the viewport
scrolls so that the element appears at the center of the viewport
does anyone know of such a function in prototype, scriptaculous or stand-alone?
I guess you need something like this (demo):
window.height
function getWindowHeight() {
var body = document.body;
var docEl = document.documentElement;
return window.innerHeight ||
(docEl && docEl.clientHeight) ||
(body && body.clientHeight) ||
0;
}
Scroll
function scrollElemToCenter(id, duration) {
var el = document.getElementById(id);
var winHeight = getWindowHeight();
var offsetTop = el.offsetTop;
if (offsetTop > winHeight) {
var y = offsetTop - (winHeight-el.offsetHeight)/2;
// wo animation: scrollTo(0, y);
scrollToAnim(y, duration);
}
}
Animation (optional, you can use script.aculo.us, etc.)
function interpolate(source,target,pos) { return (source+(target-source)*pos); }
function easing(pos) { return (-Math.cos(pos*Math.PI)/2) + 0.5; }
function scrollToAnim(targetTop, duration) {
duration || (duration = 1000);
var start = +new Date,
finish = start + duration,
startTop = getScrollRoot().scrollTop,
interval = setInterval(function(){
var now = +new Date,
pos = (now>finish) ? 1 : (now-start)/duration;
var y = interpolate(startTop, targetTop, easing(pos)) >> 0;
window.scrollTo(0, y);
if(now > finish) {
clearInterval(interval);
}
}, 10);
}
get scroll root
var getScrollRoot = (function() {
var SCROLL_ROOT;
return function() {
if (!SCROLL_ROOT) {
var bodyScrollTop = document.body.scrollTop;
var docElScrollTop = document.documentElement.scrollTop;
window.scrollBy(0, 1);
if (document.body.scrollTop != bodyScrollTop)
(SCROLL_ROOT = document.body);
else
(SCROLL_ROOT = document.documentElement);
window.scrollBy(0, -1);
}
return SCROLL_ROOT;
};
})();
Here is an alternative approach, that uses some of Prototype's built in functionality for working with the viewport and scroll dimensions...
function scrollToCenterOfElement(id){
// Cache element and property lookups...
var element = $(id);
var height = element.measure('height');
var top = element.cumulativeOffset().top;
var scroll = document.viewport.getScrollOffsets();
var dimensions = document.viewport.getDimensions();
// Checks to see if the top offset plus the height of the element is greater
// than the sum of the viewport height and vertical scroll offset, which means
// that the element has yet to be fully scrolled in to view, or if the
// top offset is smaller than the vertical scroll offset, which means the element
// has already been (at least partly) scrolled out of view..
if ((top + height > dimensions.height + scroll.top) || (top < dimensions.height + scroll.top)) {
// Scroll window to sum of top offset plus half the height of the element
// minus half of the viewport height, thus centering the element vertically.
window.scrollTo(0, top + (height / 2) - (dimensions.height / 2));
}
}
scrollToCenterOfElement('my-element');
My solution does not cover 100% of what is requested, but perhaps someone finds it useful.
/**
* Scroll container so that given element becomes visible. Features:
* <ol>
* <li>If element is already visible, then no action is taken.
* <li>If element is above view port, the viewport is scrolled upwards so that element becomes visible at the top.
* <li>If element is below view port, the viewport is scrolled downwards so that element becomes visible at the bottom.
* </ol>
*
* #param element
* optional string (selector) or jQuery object that controls the scrolling of the element
* #param options
* optional extra settings
* #param options.animationSpeed
* if defined, then scrolling is animated; determines time in milliseconds after which the element should
* be scrolled into viewport
* #param options.heightScale
* double number from 0 to 1; when scrolling the element from bottom sometimes it is desirable to scroll
* element close to the top; e.g. to scroll it to the center specify 0.5; to scroll it to the top specify 0
* #param options.complete
* function to be called after animation is completed; if there is no animation, the function is called straight away
*/
$.fn.scrollTo = function(element, options) {
options = options || {};
var elementTop = element.offset().top;
var containerTop = this.offset().top;
var newScrollTop = null;
if (elementTop < containerTop) {
// Scroll to the top:
newScrollTop = Math.round(this.scrollTop() + elementTop - containerTop);
} else {
// Scroll to the bottom:
var elementBottom = elementTop + element.outerHeight(true);
var containerHeight = this.height();
if (elementBottom > containerTop + containerHeight) {
if (options.heightScale != null) {
if (options.heightScale === 0) {
// This will effectively turn the formulae below into "elementTop - containerTop":
containerHeight = element.outerHeight(true);
} else {
containerHeight *= options.heightScale;
}
}
newScrollTop = Math.round(this.scrollTop() + elementBottom - containerTop - containerHeight);
}
}
if (newScrollTop !== null) {
if (options && options.animationSpeed) {
this.animate({
scrollTop : newScrollTop
}, {
"duration" : options.animationSpeed,
"complete" : options.complete
});
} else {
this.scrollTop(newScrollTop);
if ($.isFunction(options.complete)) {
options.complete();
}
}
} else {
if ($.isFunction(options.complete)) {
options.complete();
}
}
return this;
};
Demo

Categories