How to change scrollbar position? - javascript

Is it possible to change the scrollbar position when the user reaches a certain point scrolling down a web page? For example once you reached half way down down the page the scrollbar would move automatically back to the top.

You can calculate the percentage of the current position of the scrollbar using the onscroll event, and if it reaches the 50 % the scroll position can be set to the top of the page with the scrollTo function:
window.onload = function () {
window.onscroll = function () {
var doc = document.body,
scrollPosition = doc.scrollTop,
pageSize = (doc.scrollHeight - doc.clientHeight),
percentageScrolled = Math.floor((scrollPosition / pageSize) * 100);
if (percentageScrolled >= 50){ // if the percentage is >= 50, scroll to top
window.scrollTo(0,0);
}
};
};
You can check my example here.

Yup, I've seen it a few times. Here is some JS code:
window.scrollBy(0,50)
50 is the amount of pixels you want to scroll by.

The three scrolling functions you'll want to concern yourself with are window.scroll(x,y), window.scrollBy(dx,dy), and window.scrollTo(x,y).
As David mentioned you'll need the scroll position to know where you are and use the window.onscroll event to fire off this calculation.

(window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop) ought to give you the current scroll position in just about any browser.

Related

Reduce logo size for sticky header based on scroll position

This question has been asked here many times but I am looking to do this differently using Vanilla Javascript and not jQuery.
I need to reduce the logo size based on the scroll position but not suddenly. Adding a class to reduce the logo size is understood but I am looking to have the logo grow/shrink based on the exact scroll position.
The logo needs to stop at 200px wide down from 300px wide on scroll down.
When the user scrolls back up to a certain point the logo begins to increase back to 300px but still based on scroll position and not instantly based on a point.
Something similar to this on Codepen:
https://codepen.io/jonathanphz/pen/NAXRKG
var expandDiv = document.getElementById("expand");
var speed = 5;
function expanding() {
var scrolltop = window.pageYOffset; // get number of pixels document has scrolled vertically
var scrollAndSpeed = (scrolltop / speed);
//Expand using transform
//expandDiv.style.transform = "scalex( " + Math.min(Math.max(scrollAndSpeed, 1), 10) + ")";
//Or using width
expandDiv.style.width = Math.min(Math.max(scrollAndSpeed, 20), 95) + "%";
}
window.addEventListener('scroll', function() { // on page scroll
requestAnimationFrame(expanding); // call parallaxing()
}, false);```
You can use window.onscroll in vanilla JavaScript.
add condition with document.body.scrollTop and compare it, then change the styling(width and height) accordingly.
It will help you.

detect the total added up scroll distance

I want to detect the total distance the user scrolled on a website. Therefore I want to add up the scroll distance downwards as well as the scroll distance upwards.
So for example: the user scrolls 150px downwards and scroll back to the top of the page the result should be 300px.
With window.pageYOffset I can detect the distance downwards. How can I add both directions up?
// edit:
You need a counter – totalOffset. You need to check current scroll position – currOffset. You need a function that fires on scroll and calculates the distance between current and cached position and that updates the counter and the cached position.
let totalOffset = 0;
let currOffset = window.pageYOffset;
window.addEventListener(
"scroll",
() => {
let addedOffset = Math.abs(currOffset - window.pageYOffset);
totalOffset += addedOffset;
currOffset = window.pageYOffset;
console.log('the total scroll in px is: ', totalOffset);
},
false
);
<div style="min-height:2000px">
<div>
It might not work ideally in SO snippet runner, but it seems to work fine in a browser.

Floating elements on scroll

I was wondering how sites like Facebook, with their timeline feature, float a certain element (usually a menu bar, or sometimes a social plugin, etc) when the user has scrolled past a point such that the top of the element is off the screen, etc.
This could be seen as a more general JavaScript (jQuery?) event firing when the user has scrolled to a certain element, or scrolled down a certain number of pixels.
Obviously it would require toggling the CSS property from:
#foo { position: relative; }
to
#foo { position: fixed; }
Or with jQuery, something like:
$('#foo').css('position', 'fixed');
Another way I have seen this implemented is with blogs, where a popup will be called when you reach the bottom, or near the bottom of a page. My question is, what is firing that code, and could you link or provide some syntax/ semantics/ examples?
Edit: I'm seeing some great JS variants coming up, but as I am using jQuery, I think the plugin mentioned will do just nicely.
Take a look at this jsfiddle: http://jsfiddle.net/remibreton/RWJhM/2/
In this example, I'm using document.onscroll = function(){ //Scroll event } to detect a scroll event on the document.
I'm then calculating the percentage of the page scrolled based on it's height. (document.body.scrollTop * 100 / (document.body.clientHeight - document.documentElement.clientHeight)).
document.body.scrollTop being the number of pixels scrolled from the top, document.body.clientHeight being the height of the entire document and document.documentElement.clientHeight being the visible portion of the document, a.k.a. the viewport.
Then you can compare this value to a target percentage, an execute JavaScript. if(currentPercentage > targetPercentage)...
Here's the whole thing:
document.onscroll = function(){
var targetPercentage = 80;
var currentPercentage = (document.body.scrollTop * 100 / (document.body.clientHeight - document.documentElement.clientHeight));
console.log(currentPercentage);
if(currentPercentage > targetPercentage){
document.getElementById('pop').style.display = 'block';
// Scrolled more than 80%
} else {
document.getElementById('pop').style.display = 'none';
// Scrolled less than 80%
}
}
​If you prefer jQuery, here is the same example translated into everybody's favorite library: http://jsfiddle.net/remibreton/8NVS6/1/
$(document).on('scroll', function(){
var targetPercentage = 80;
var currentPercentage = $(document).scrollTop() * 100 / ($(document).height() - $(window).height());
if(currentPercentage > targetPercentage){
$('#pop').css({display:'block'});
//Scrolled more than 80%
} else {
$('#pop').css({display:'none'});
//Scrolled less than 80%
}
});​
An idea would be to handle the window.scroll event and determine if the user has scrolled to the bottom of the page. Here is an example:
http://chrissilich.com/blog/load-more-content-as-the-user-reaches-the-bottom-of-your-page-with-jquery/
Hope it helps!
There is a jquery plugin that might help you in the right direction.
http://imakewebthings.com/jquery-waypoints/
I just answered basically the same question here. In that case it was a table and its header, and the basic idea is like this:
function placeHeader(){
var $table = $('#table');
var $header = $('#header');
if ($table.offset().top <= $(window).scrollTop()) {
$header.offset({top: $(window).scrollTop()});
} else {
$header.offset({top: $table.offset().top});
}
}
$(window).scroll(placeHeader);
Here's a demo.
Quoting myself:
In other words, if the top of the table is above the scrollTop, then
position the header at scrollTop, otherwise put it back at the top of
the table. Depending on the contents of the rest of the site, you
might also need to check if you have scrolled all the way past the
table, since then you don't want the header to stay visible.
To answer your question directly, it is triggered by checking the scrollTop against either the position of an element, or the height of the document minus the height of the viewport (for the scrolled to bottom use case). This check is done every time the scroll event is fired (bound using $(window).scroll(...)).

On scroll load data on demand

I am implementing on demand loading of data through scrolling.
I have register the function in document.ready for a div.
The data should only be populated once the scroll is reached to the last. so to identify whether the scroll has reached till the last i am using the below function.
$("#tree").scroll(function () {
if (isScrolledToBottom(this)) {
}
});
But the function is not returning the correct value. What I mean is it should return the a true value when scroll has reached to its last.
function isScrolledToBottom(object) {
return ($(object).attr('scrollHeight') - $(object).scrollTop() - 1) <= $(object).height();
};
Try this instead :
return ($(object).attr('offsetHeight') + $(object).attr('scrollTop') >= $(object).attr('scrollHeight'));
If you want to do infinite scrolling, check out my answer here:
How to load the web page content based on user scrolling
This demo is triggered at a certain Y scroll position. If you are looking to accomplish this specifically when a user reaches a certain item, you might want to look at the Waypoints plugin.
http://imakewebthings.com/jquery-waypoints/
Infinite scroll Demo: http://imakewebthings.com/jquery-waypoints/infinite-scroll/
$('.theItems:last').waypoint(function(event, direction) {
//Ajax fetch here
});
var scrollHeight = $(object).prop("scrollHeight"); // total scrollable height of the element
var scrollTop = $(object).scrollTop(); // how far you have come from the top while scrolling vertically
var height = $(object).height(); // the constant height of the portion in display at all times
if (scrollHeight === (scrollTop + height)) {
//console.log("fetching page");
fetchNextPage();
}

Changing div postion depending on page scroll

I have the following code below that changes a div's position to fixed once an element scrollTop is greater than a number. I am trying to either amend this script or find a different solution so that the div will scroll between a range and STOP scrolling at some point ( so the div doesn't go off the page or overlap with footer elements.
I don't know if the right way is to say that IF scrollTop is greater than 150 then position=fixed, and if it's greater than 600 then position goes back to absolute, or if there's a better way, like distance from the bottom...
AND I use MooTools, not jQuery. I know there are a few jQuery options / plugins that do this. Thanks in advance!
window.onscroll = function()
{
if( window.XMLHttpRequest ) { // IE 6 doesnt implement position fixed nicely...
if (document.documentElement.scrollTop > 150) {
$('tabber').style.position = 'fixed';
$('tabber').style.top = '0';
} else {
$('tabber').style.position = 'absolute';
$('tabber').style.top = 'auto';
}
}
}
the script above is wrong on many levels.
don't use window.onscroll but window.addEvent("scroll", function() {});
cache selectors. using $("tabber") 3 times on each scroll when the element does not change is expensive.
just do var tabber = $("tabber") and reference that.
you don't need to do
$("tabber").style.position = ...
$("tabber").style.top = ...
do:
tabber.setStyles({
position: "fixed",
top: 12123,
right: 24
});
There are mootools plugins for this, eg scrollSpy by David Walsh: http://davidwalsh.name/mootools-scrollspy
it can allow you to set scripted events upon reaching various scrolling destinations or events, look at the examples.
or you could just write it yourself, eg, this took me 15 mins to do:
http://jsfiddle.net/dimitar/u9J2X/ (watch http://jsfiddle.net/dimitar/u9J2X/show/) - it stops being fixed when it reaches to 20 px of the footer. and then goes back to fixed if scrolling up again.

Categories