Trying to execute js code when the user scrolls - javascript

I am trying to execute some js code, right now they are replaced by alerts, when the scroll-bar has moved from the top to any other height.
So when the user scrolls for the first-time, the alert "scrolled" will fire.
and if the user scrolls back to the top, it resets and fires an alert "back at top".
I tried doing this with scrollTop, scrollHeight, and clientHeight, but it doesn't seem to fire the alert on scroll.
I'm not trying to fire the alert everytime the user scrolls, just on the first scroll.
But it resets and a new alert is fired if the user scrolls-back to the top.
So if they scroll from top to X, alert "scrolled" fires.
If they scroll from X to Y, nothing happens.
If the scroll from X or Y to top, "back at top" fires.
And then if the scroll from top to X or Y, it has reset and the alert "scrolled" fires (again).
Here is my code:
var body = $('body');
var scrollTop = body.scrollTop;
var difference = body.scrollHeight - body.clientHeight;
var percentScrolled = (scrollTop/difference)*100;
if(percentScrolled > 0){
alert("scrolled!");
}
Update:
I now have this working thanks to one of the comments, it fires the "back to top" alert when scrolled back to the top, but fires the alert "scrolled" on every scroll.
How can I get the "scrolled" alert to fire only when the scroll-bar moves from the top to any other location besides the top?
Here is the code:
window.onscroll = function () {
var doc = document.body,
scrollPosition = doc.scrollTop,
pageSize = (doc.scrollHeight - doc.clientHeight),
percentageScrolled = Math.floor((scrollPosition / pageSize) * 100);
if(percentageScrolled == 0){
alert("back at top");
}
else if(percentageScrolled > 0){
alert("scrolled");
}
};

Exmaple of using javascript to automaticly going back to the top after user scrolls x percent. And as noidea3p5 asked, what is it exactly you are trying to do..
var AllowedPercentageToScroll = 20;
window.onscroll = function () {
var doc = document.body,
scrollPosition = doc.scrollTop,
pageSize = (doc.scrollHeight - doc.clientHeight),
percentageScrolled = Math.floor((scrollPosition / pageSize) * 100);
if(percentageScrolled > AllowedPercentageToScroll){
window.scrollTo(0,0); // back to top
}
else if(percentageScrolled > 0){ // if user starts to scroll it will trigger
//do whatever you like, dont recommend alert though
}
};
Edit:
Shows status if at the top, and shows scrolling activity when starting to scroll
window.onscroll = function () {
var doc = document.body,
scrollPosition = doc.scrollTop,
pageSize = (doc.scrollHeight - doc.clientHeight),
percentageScrolled = Math.floor((scrollPosition / pageSize) * 100);
if(percentageScrolled == 0){
document.getElementById("status").innerHTML = "Your at the top";
}
else if(percentageScrolled > 1){
document.getElementById("status").innerHTML = percentageScrolled + "%";
}
};
</script>
<body>
<div style="width: 100%; position: fixed; top:0px; background-color:#c0c0c0;">
Scroll Position: <span id="status">0%</span>
</div>

Not sure what you are trying to do but it sounds like you may want some kind of flag:
var body = $('body');
var scrollTop = body.scrollTop;
var difference = body.scrollHeight - body.clientHeight;
var percentScrolled = (scrollTop/difference)*100;
if(percentScrolled > 0 && this.leftzero === undefined){
this.leftzero = true;
alert("scrolled!");
}

Related

Detect scroll up when your top of page

Im using a script to detect scroll up to click a previous link. I want to detect scroll up even when your top of the page and do a scroll up. Now I have to scroll down a bit then up again. How can I do this?
Code:
var lastScrollTop = 0, delta = 5;
jQuery(window).scroll(function(){
var nowScrollTop = jQuery(this).scrollTop();
if(Math.abs(lastScrollTop - nowScrollTop) >= delta){
if (nowScrollTop > lastScrollTop){
// ACTION ON
// SCROLLING DOWN
} else {
jQuery( 'a.action.previous' ).click ();
}
lastScrollTop = nowScrollTop;
}
});

Scrolling upwards

I want to make a function that will automatically display items as the user scrolls upwards. Think messages, where older ones are up top, but we start at the bottom with the newest ones. I have another function that loads items at the bottom of a container, and as it does so, the current items remain in position, and scrollbar is smaller. We are not scrolled to the bottom. However, with the other direction, when I prepend items to an array, it scrolls all the way to the top, displaying the top of the loaded items, instead of remaining in the same place and letting the user scroll up as needed.
My code for the bottom scroll is this:
attachScrollWatcher: function (element, offset, callback) {
console.log('scrolling');
var contentHeight = element.scrollHeight;
var yOffset = element.scrollTop;
var y = yOffset + element.offsetHeight;
if (y >= ( contentHeight - offset ))
{
callback();
}
}
This function is attached to an object's onscroll event. However, now I need to make a function that does the opposite, going upwards. Any ideas how this can be implemented?
Basically, when scrollTop === 0 then you're at the top and you need to load a new item..
attachScrollWatcher: function (element, offset, callback) {
if(!element.scrollHeight) callback();
}
The problem is, loading a new item will keep the scrollTop at zero, so the user would have to scroll down and then scroll back up in order for the callback to be triggered again. So, what you wanna do is calculate the scrollHeight before the new item is added and then again after the item is added and then manually set the scrollTop to the difference between the original and the new scrollHeight.
Check out my example attachScrollListener method below...
class upScroller{
constructor(ele = document.body){
this.renderedItems = 0;
this.ele = ele; var i=0;
this.initBoxContents();
}
initBoxContents(){
if(this.ele.scrollHeight == this.ele.clientHeight)
this.populateNextItem().then(()=>this.initBoxContents());
else{
this.ele.scrollTop = this.ele.clientHeight;
this.attachScrollListener();
}
}
getNextItem(){
// Do something here to get the next item to render
// preferably using ajax but I'm using setTimeout
// to emulate the ajax call.
return new Promise(done=>setTimeout(()=>{
this.renderedItems++;
done(`<p>This is paragraph #${this.renderedItems}</p>`);
},50));
}
populateNextItem(){
return new Promise(done=>{
this.getNextItem().then(item=>{
this.ele.insertAdjacentHTML('afterbegin', item);
done();
});
});
}
attachScrollListener(){
this.ele.addEventListener('scroll', ()=>{
if(this.ele.scrollTop) return;
var sh = this.ele.scrollHeight;
this.populateNextItem().then(()=>{
this.ele.scrollTop = this.ele.scrollHeight - sh;
});
});
}
}
var poop = document.getElementById('poop');
new upScroller(poop);
#poop{ height: 300px; overflow: auto; border:1px solid black;}
<div id=poop></div>
I've posted this here as well....
Something like this may work.
attachScrollWatcher: function (element, offset, callback) {
console.log('scrolling');
var contentHeight = element.scrollHeight;
var yOffset = element.scrollTop;
var y = yOffset + element.offsetHeight;
if (y >= ( contentHeight - offset ))
{
callback();
} else {
callbackGoingUp();
}
}

check if the user has reached to bottom of the page

I am trying to trigger an event when the users scrolls down and reaches to the bottom of the page.
I searched the internet and found some posts in stackoverflow but unexpectedly the answers did not work for me.
Ex: Check if a user has scrolled to the bottom
using the answers given for the above SO post, the event I am trying to trigger is executed when reaching the top of the page and not the bottom.
Please let me know if I am going wrong:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
loadmore();
}
});
function loadmore(){
var lastProd = $('.product_div').last();
var lastProdID = $('.product_div').last().prop('id');
//console.info(lastProdID); return false;
//var val = document.getElementById("row_no").value;
$.ajax({
type: 'post',
url: 'includes/load_products.php',
data: { getresult:lastProdID },
success: function (response) {
console.log(response);
//var content = document.getElementById("all_rows");
//content.innerHTML = content.innerHTML+response;
lastProd.after(response);
// We increase the value by 10 because we limit the results by 10
// document.getElementById("row_no").value = Number(val)+10;
}
});
}
Use window.innerHeight + window.scrollY to determine bottom position and check if document.body.offsetHeight is lower (equal won't work).
Credit goes to mVChr, see here.
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
alert("bottom of the page reached");
}
};
.jump {
height: 1000px;
}
<div class="jump"></div>
check the height and offset are equal
window.onscroll = function() {
var d = document.documentElement;
var offset = d.scrollTop + window.innerHeight;
var height = d.offsetHeight;
console.log('offset = ' + offset);
console.log('height = ' + height);
if (offset === height) {
console.log('At the bottom');
loadmore(); // call function here
}
};
The only proper way to do this, at time of writing Feb/11/2022, is here: Check if a user has scrolled to the bottom in subpixel precision era
That detects bottom of scroll for any element. To do this with the "window" in a default web page, you should set element to document.documentElement or document.scrollingElement to get the result you want.
Or, apply the same Math.abs trick as in that answer with window.scrollY, but not that that does not work with scrollable in any other elements, only the documentElement (that's what element is being scrolled when saying "window scroll", and it is the root <html> element).

Sticky Sidebar that only sticks when sidebar bottom is at window bottom

I have a 2 column layout. The left column is way longer than the sidebar. I want the sidebar only to stick when its bottom reaches the bottom of the browser window. So the user can continue to scroll down the left column content while the right sidebar sticks. I've seen a lot of sticky questions here, however this particular situation still stumps me. I also have a sticking headline bar on the left column that i've successfully gotten to stick.
Here's a demo of what I've done in jsfiddle!
and here's a quick look at the js I am trying out.
$(function(){
var headlineBarPos = $('.headlineBar').offset().top; // returns number
var sidebarHeight = $('.sticky-sidebar-wrap').height();
var sidebarTop = $('.sticky-sidebar-wrap').offset().top;
var windowHeight = $(window).height();
var totalHeight = sidebarHeight + sidebarTop;
$(window).scroll(function(){ // scroll event
var windowTop = $(window).scrollTop(); // returns number
// fixing the headline bar
if (headlineBarPos < windowTop) {
$('.headlineBar').addClass('sticky').css('top', '0');
}
else {
$('.headlineBar').removeClass('sticky').removeAttr('style');
}
if(sidebarHeight < windowTop) {
$('.sticky-sidebar-wrap').addClass('sticky').css('top', '0');
} else {
$('.sticky-sidebar-wrap').removeClass('sticky').removeAttr('style');
}
console.log(windowTop);
});
console.log(headlineBarPos);
console.log(sidebarHeight);
console.log(sidebarTop);
});
I hope I got it right, when the bottom of the sidebar comes into the view, then stick?
I created another div at the bottom of the sidebar (inside the sidebar).
When that comes into view, it sticks.
http://jsfiddle.net/Z9RJW/10/
<div class="moduleController"></div> //inside the sidebar
and in js
$(function () {
var headlineBarPos = $('.headlineBar').offset().top; // returns number
var moduleControllerPos = $('.moduleController').offset().top; // returns number
var sidebarHeight = $('.sticky-sidebar-wrap').height();
var sidebarTop = $('.sticky-sidebar-wrap').offset().top;
var windowHeight = $(window).height();
var totalHeight = sidebarHeight + sidebarTop;
$(window).scroll(function () { // scroll event
var windowTop = $(window).scrollTop(); // returns number
// fixing the headline bar
if (headlineBarPos < windowTop) {
$('.headlineBar').addClass('sticky').css('top', '0');
} else {
$('.headlineBar').removeClass('sticky').removeAttr('style');
}
if (moduleControllerPos < windowTop + windowHeight) {
$('.sticky-sidebar-wrap').addClass('sticky').css('top', '0');
} else {
$('.sticky-sidebar-wrap').removeClass('sticky').removeAttr('style'); }
console.log(windowTop);
});
console.log(headlineBarPos);
console.log(sidebarHeight);
console.log(sidebarTop);
});
I hope it helps.
Something like:
if (sidebar.top + sidebar.height < window.scrolltop + window.height) {
// set sticky
}
and set sticky needs to take into account that the sidebar may be higher than the viewport, so:
sidebar.top = sidebar.height - window.height // this will be a negative number

How to determine if vertical scroll bar has reached the bottom of the web page?

The same question is answered in jQUery but I'm looking for solution without jQuery.
How do you know the scroll bar has reached bottom of a page
I would like to know how I can determine whether vertical scrollbar has reached the bottom of the web page.
I am using Firefox3.6
I wrote simple Javascript loop to scroll down by 200 pixel and when the scroll bar reached the bottom of the page, I want to stop the loop.
The problem is scrollHeight() is returning 1989.
And inside loop scrollTop is incremented by 200 per iteration.
200 ==> 400 ==> 600 .... 1715
And from 1715, it won't increment so this loop continues forever.
Looks like scrollHeight() and scrollTop() is not right way to compare in order to determine the actual position of scrollbar? How can I know when the loop should stop?
code:
var curWindow = selenium.browserbot.getCurrentWindow();
var scrollTop = curWindow.document.body.scrollTop;
alert('scrollHeight==>' + curWindow.document.body.scrollHeight);
while(curWindow.document.body.scrollHeight > curWindow.document.body.scrollTop) {
scrollTop = curWindow.document.body.scrollTop;
if(scrollTop == 0) {
if(window.pageYOffset) { //firefox
alert('firefox');
scrollTop = window.pageYOffset;
}
else { //IE
alert('IE');
scrollTop = (curWindow.document.body.parentElement) ? curWindow.document.body.parentElement.scrollTop : 0;
}
} //end outer if
alert('current scrollTop ==> ' + scrollTop);
alert('take a shot here');
selenium.browserbot.getCurrentWindow().scrollBy(0,200);
} //end while
When you tell an element to scroll, if its scrollTop (or whatever appropriate property) doesn't change, then can't you assume that it has scrolled as far as is capable?
So you can keep track of the old scrollTop, tell it to scroll some, and then check to see if it really did it:
function scroller() {
var old = someElem.scrollTop;
someElem.scrollTop += 200;
if (someElem.scrollTop > old) {
// we still have some scrolling to do...
} else {
// we have reached rock bottom
}
}
I just read through the jQuery source code, and it looks like you'll need the "pageYOffset". Then you can get the window height and document height.
Something like this:
var yLeftToGo = document.height - (window.pageYOffset + window.innerHeight);
If yLeftToGo is 0, then you're at the bottom. At least that's the general idea.
The correct way to check if you reached the bottom of the page is this:
Get document.body.clientHeight = the height of the ACTUAL screen shown
Get document.body.offsetHeight or document.body.scrollHeight = the height of the entire page shown
Check if document.body.scrollTop = document.body.scrollHeight - document.body.clientHeight
If 3 is true, you reached the bottom of the page
function scrollHandler(theElement){
if((theElement.scrollHeight - theElement.scrollTop) + "px" == theElement.style.height)
alert("Bottom");
}
For the HTML element (like div) add the event -- onscroll='scrollHandler(this)'.
Here is some code I've used to power infinite scrolling list views:
var isBelowBuffer = false; // Flag to prevent actions from firing multiple times
$(window).scroll(function() {
// Anytime user scrolls to the bottom
if (isScrolledToBottom(30) === true) {
if (isBelowBuffer === false) {
// ... do something
}
isBelowBuffer = true;
} else {
isBelowBuffer = false;
}
});
function isScrolledToBottom(buffer) {
var pageHeight = document.body.scrollHeight;
// NOTE: IE and the other browsers handle scrollTop and pageYOffset differently
var pagePosition = document.body.offsetHeight + Math.max(parseInt(document.body.scrollTop), parseInt(window.pageYOffset - 1));
buffer = buffer || 0;
console.log(pagePosition + "px / " + (pageHeight) + "px");
return pagePosition >= (pageHeight - buffer);
}
<span id="add"></add>
<script>
window.onscroll = scroll;
function scroll () {
if (window.pageYOffset + window.innerHeight >= document.body.scrollHeight - 100) {
document.getElementById("add").innerHTML += 'test<br />test<br />test<br />test<br />test<br />';
}
}
</script>

Categories

Resources