Trigger a function after scrolling x pixels from the top - javascript

I would like to trigger something once (and only once) a user has scrolled down 100 pixels from the top.
In the past I was given this code, but it doesn't seem to be working?
window.onscroll = function() {
var scrollLimit = 100;
var scrollValue = document.body.scrollTop;
if (scrollValue >= scrollLimit) {
alert("x")
}
};

You are using the wrong property here.
Instead of scrollTop property you need to use the Window.scrollY property.
This is how should be your code:
window.onscroll = function() {
var scrollLimit = 100;
if (window.scrollY >= scrollLimit) {
alert("x")
}
};
Note:
window.scrollY compatibility issues with IE:
Unfortunately window.scrollY doesn't work with IE browsers, for IE you can use window.pageYOffsetas a replacement, but it always gives hundreds rounded values (100, 200, 300, ...).
Otherwise you can check the accepted answer here it uses document.documentElement.scrollTop as a workaround.

Try this:
var scrollValue = window.scrollY;

scrollTop will give you the offset between the top of the element and the top of the document. Since the body of a html document by default starts at the top of the document, body.scrollTop always stays 0 unless you specifically used css to make the body not start at the top.
So you have to use scrollY instead of scrollTop. If the browser you use does not support scrollY ( eg. IE ) you can try pageYOffset.

Related

Why is Scroll Percentage more than 100

I am using this method to calculate Scroll Percentage (after reading a bunch of posts online). However, when I scroll to the very bottom the scroll percentage goes to > 100%. The values are:
Scroll values: ScrollHeight: 3405 scrollBarHeight: 1408 scrollTop: 1997.3333740234375 scrollPercentage: 100.01669374178455
I want to understand why is this happening and if my approach is wrong?
thanks.
// This is the container with the scrolbar. We are using this element as we want the inner div. document.documentElement is the full element
const scrollingElement: HTMLElement = document.getElementById(personalInsightsContainerId);
// If no scrollingElement is present, do not do anything.
if (scrollingElement) {
// The Element.scrollTop property gets or sets the number of pixels that the content of an element is scrolled upward.
// An element's scrollTop is a form of distance measurement regardingĀ an element's top to its topmost visible content.
// When an element content does not generate a vertical Scrollbar, then its scrollTop value defaults to 0.
const scrollTop: number = scrollingElement.scrollTop;
// The difference b/w scrolling point.
const scrollingDifference: number = scrollTop - this.lastScrollNumber;
// We want to scroll if: a) there is scrollElement defined b) either the scrolling is first time or the scrollDifference is > 100.
if (this.lastScrollNumber === 0 || scrollingDifference > 100) {
// The Element.scrollHeight read-only property is a measurement of the height of an element's content,
// Including content not visible on the screen due to overflow.
const scrollHeight = scrollingElement.scrollHeight;
// The HTMLElement.offsetHeight read-only property is the height of the element including vertical padding and borders, as an integer.
const scrollBarHeight = scrollingElement.offsetHeight;
if (scrollHeight && scrollBarHeight) {
this.lastScrollNumber = scrollTop;
const totalHeight = scrollHeight - scrollBarHeight;
const scrollPercentage = totalHeight > 0 ? (scrollTop / totalHeight) * 100 : -1;
}
}
try to use clientHeight instead of offsetHeight
What browser do you use? In chrome/FF Element.scrollTop is always integer value. Try to use const scrollTop: number = Math.floor(scrollingElement.scrollTop);

How to apply var height = $(window).height() - 20; to .followTo() function

I have this script. Its pretty simple. But my JS skills are shaky at best. It makes the navigation (which is positioned to the bottom of the window) scroll with the content until it reaches the top of the page then remains as fixed. Or as some would say "Sticky"
The issue im having is since my banner is 100% in height. The .followTo(830); only works on my screen resolution. How do I make followTo() find the windows current height and then follow to that height and then subtract 20px from the followTo value? That would be ideal. Can this be accomplished fairly simply?
var windw = this;
$.fn.followTo = function ( pos ) {
var $this = this,
$window = $(windw);
$window.scroll(function(e){
if ($window.scrollTop() > pos) {
$this.css({
position: 'fixed',
top: "20px"
});
} else {
$this.css({
position: 'absolute',
bottom: '0',
});
}
});
};
$('#mainNav').followTo(830);
Someone said I need to use var height = $(window).height() - 20; but I am not sure how to apply it and they refused to elaborate instead just downvoting my posts and refering me to the entire jquery API.. Which isnt my learning style.
Ive also attempted to use if ($(document).height() - $window.height() - $('#mainNav').scrollTop() < pos) I think im just messing up the syntax?
Just use the var height = $(window).height() - 20; in place of the 830 like this:
var height = $(window).height() - 20;
$('#mainNav').followTo(height);
Just keep in mind that the window size can change (for example the browser window gets resized or the device's orientation changes)

Javascript DIV Movement on scroll

NIm creating an animation that moves a div incrementally on scroll. I'm close but I don't think my code is the most efficient and I don't know how to adapt it to add more arguments. So for instance, hitting a certain height on the page will then move the object right and stop moving it down. Below is my JS and the codepen can be found at;
http://codepen.io/anon/pen/KxHwu - Original
http://codepen.io/anon/pen/DLxqg - Messing about with moving right
var lastScrollTop = 0;
var boxPosition = $('#box').position();
var row2Position = $('#row2').position();
var distance = $('#row2').offset().top,
$window = $(window);
console.log(distance);
$window.scroll(function() {
if ( $window.scrollTop() >= distance - 400 ) {
var st = $(window).scrollTop();
console.log(st);
$('#box').css({top: 0 + st});
//CODE NOT WORKING
if(st >= 270) {
var boxPos = $('#box').position();
console.log(boxPos.left);
$('#box').css({left: boxPos.left + st});
}
//
lastScrollTop = st;
}
});
I'm looking for the box to start scrolling like it does, then when it hits half of row 2 scroll right.
I hope I have explained this in an easy way!
Thanks
http://codepen.io/anon/pen/tHwlq
Here is an example of how to do it; you'll need to tweak the numbers to make it work as you plan.
var $window = $(window);
var $box = $("#box");
$window.scroll(function() {
var scrollTop = $window.scrollTop();
if (scrollTop >= 250 && scrollTop < 400) {
$box.css({top: -250 + scrollTop});
} else if(scrollTop >= 400 && scrollTop < 600) {
$box.css({left: (50+(scrollTop-400)/2)+"%"})
}
});
If your project has numerous elements like this, I'd recommend the ScrollMagic (http://janpaepke.github.io/ScrollMagic/) library.
As far as efficiency is concerned I'd recommend the following:
1) Cache the jQuery selectors (note $box variable). Otherwise, jQuery will have to query the DOM on every scroll event.
2) Cache scrollTop rather then querying it multiple times within the event callback.
3) Although left and top work, using the transform: translate() property is more efficient, especially on mobile devices. (https://developer.mozilla.org/en-US/docs/Web/CSS/transform). However, on most mobile devices, scroll events only fire at the completion of a scroll, not while a page is scrolling.

Get the position of the scrollbar using javascript

So I am trying to show a tooltip like box as I scroll my webpage and I would like it to follow the scrollbar along the right side of the page.
I looked around and found something to attempt to accomplish that as shown below:
function returnPercentHeight(){
var a = document.getElementById('rightPanel').scrollTop;
var b = document.getElementById('rightPanel').scrollHeight - document.getElementById('rightPanel').clientHeight;
return ((a/b) * 100);
}
I then append a % to the end and set the top margin of the tooltip to that returned value. This works pretty well (sort of) I have to adjust the return((a/b) * x) part (x) to make it follow the scrollbar based on the size of the browser window. Is there a better way to accomplish what I am trying to do? (NOTE: I can only use javascript, no JQuery please.)
EDIT:
Only the div given an ID of 'RightPanel' is scrolling, I am not using the scrollbar on the browser, but a scrollbar on an inner div.
There are three ways to do so:
First:
is to use the fixed position as following;
Position: Fixed;
Second:
With jQuery;
$(function(){
$(window).on('scroll', function() {
var scrollPOS = $(document).scrollTop();
$('.scroll').css({
top: scrollPOS
});
}).scroll();
});
Third:
Same as the previous, only animated;
$(window).on('scroll', function() {
$("#div").stop().animate({
"marginTop": ($(window).scrollTop()) + "px",
"marginLeft":($(window).scrollLeft()) + "px"}, "slow" );
});
Although IE doesn't support, this is the coolest I've seen:
// get
var x = window.scrollX,
y = window.scrollY;
// set
window.scrollTo(1, 2);

Change margin-top as user scrolls

I am trying to get a div to scroll up at the same amount of pixels as the user scrolls down the page. For example, in Google Chrome when using the mouse wheel, it scrolls down in about 20px intervals. But when you scroll down using the handle, the scrolling amount varies.
Here is my code so far:
var scrollCtr = 50;
$(window).scroll(function(){
scrollCtr = scrollCtr - 20;
$('div.nexus-files').css('margin-top', scrollCtr + 'px');
});
There are a few problems with this:
The user scrolling varies
It needs to subtract from margin-top if scrolling down and add to margin-top if scrolling up
Here is an example:
http://www.enflick.com/
Thanks for the help
You're doing it the wrong way, what you are trying to do should be done using position: fixed on div.nexus-files
div.nexus-files{position: fixed; top: 0;}
but anyway - if you still want to know what you can do with the scroll event - you better get to scrollTop of the document and set the margin-top to the same value
window.onscroll = function(event){
var doc = document.documentElement, body = document.body;
var top = (doc && doc.scrollTop || body && body.scrollTop || 0);
document.getElementById('nexus-files_id').style.marginTop = top+'px';
}
I'm using pure Javascript instead of jQuery because of the overhead that might be crucial when the browser need to calculate stuff in a very short amount of time (during the scrolling). [this can be done even more efficient by storing reference to the element and the doc... but you know..)
I used id based selector to get the specific element instead of class based
AND I SAY AGAIN - this is not how you should do what you were trying to do
Why not using the actual scroll offset as reference or position ?
// or whatever offset you need
var scrollOffset = document.body.scrollTop + 20;
// jQuery
var scrollOffset = $("body").scrollTop() + 20;
Finally Got it
Here is the code I used to accomplish the task.
Most of the code is from http://enflick.com and I modified it to work with my individual situation.
jQuery(window).load(function(){
initParallax();
});
// parallax init
function initParallax(){
var win = jQuery(window);
var wrapper = jQuery('#wrapper');
var bg1 = wrapper.find('.nexus-files');
var koeff = 0.55;
if (bg1.length) {
function refreshPosition(){
var scrolled = win.scrollTop();
var maxOffsetY1 = 450;
var offsetY1 = scrolled * koeff;
var offsetY2 = scrolled * koeff - (maxOffsetY1 * koeff - offsetY1);
if (offsetY1 <= maxOffsetY1 * koeff - offsetY1) {
bg1.css("margin-top", +-offsetY1+"px");
//alert(+-offsetY1+"px");
}
}
refreshPosition();
win.bind('resize scroll', refreshPosition);
}
}

Categories