Can't change scrollbar values - javascript

I've made a simple code to change the value of a scrollbar along with document.scrollTop but i can't get it to work.
var scroll = document.scrollTop;
var container = document.getElementById('test');
container.innerHTML = scroll;
var pb = document.getElementById('progress-bar');
pb.value = 2;
var change = function()
{ pb.value = 2;
pb.value++;
};
if (scroll > 0){
change();
};
Can someone tell me where i've made a mistake(s) ?

Problem:
You haven't shared many details in your post but from what you have posted we can notice that you have some problems in your current code:
As stated in comments you need to use document.body.scrollTop
because document.scrollTop is undefined as the scroll is attached
to document body and not to the document itself.
And with your actual code you are not changing the progress bar value, because the change() function isn't attached to any event but it's just called on document load.
Solution:
If you want to change the progress bar value when the page is scrolled, you need to do it in the onscroll event of the body.
Demo:
I made a sample Demo to show you how it should work, and how the progress bar is changing when we scroll in the view:
document.body.onscroll = function() {
var pb = document.getElementById('progress-bar');
var fullHeight = document.body.scrollHeight;
var value = 100 - (document.body.scrollTop / fullHeight) * 100;
pb.value = value;
};
#progress-bar {
margin-top: 200px;
}
<div style="width:250px; height:1400px">
<progress id="progress-bar" value="100" max="100"></progress>
</div>
The above function is attached to the onscroll event of the document.body, and whenever the body is scrolled it calculates the scrolled height (document.body.scrollTop) compared with the full scrollable height (document.body.scrollHeight) and put this value in the progress bar.

Related

Recalculate getBoundingClientRect() on resize of browser for fixed button?

In a nutshell I'm creating a sticky button that shows after the scroll position pass a target element on the page. I'm trying to calculate the distance from the top of the page to the bottom of the target element. The script below seems to work find on load but if I resize the browser the numbers are not recalculated to get the correct distance. I know I should be using another event listener like "on resize" but I can't seem to get the logic right with my current code. Any help is welcome thanks!
Current Code
$(function(){
function ctaBundle(){
//target element
var cardsContainer = document.querySelector('.card-block');
// calculate the distance from top to the bottom of target element plus padding offset
var elDistanceToTop = window.pageYOffset + cardsContainer.getBoundingClientRect().bottom - 48;
//using to only trigger on mobile using mql
var mq = window.matchMedia('(max-width: 30em)');
//function with if statement to fade in if you pass target element
$(window).on('scroll', function() {
if ($(this).scrollTop() > elDistanceToTop && mq.matches) {
$(".sticky-cta-double").fadeIn();
}else{
$(".sticky-cta-double").hide();
}
});
}
ctaBundle();
});
I think I figured it out. By removing the on scroll event in the function and adding both event listeners after the function it seems to work.
$(function(){
function ctaBundle(){
var cardsContainer = document.querySelector('.card-block');
var bundleHeader = document.querySelector('.bundle-header');
var elDistanceToTop = window.pageYOffset + cardsContainer.getBoundingClientRect().bottom - 48;
var mq = window.matchMedia('(max-width: 30em)');
if ($(this).scrollTop() > elDistanceToTop && mq.matches) {
$(".sticky-cta-double").fadeIn();
}else{
$(".sticky-cta-double").hide();
}
}
ctaBundle();
window.addEventListener('resize', ctaBundle, false);
window.addEventListener('scroll', ctaBundle, false);
});
If anyone has a better answer/logic please let me know but this seems to be working as intended now.

javascript to be activate on page scroll

i've got some code from codepen where a progress bar fills up depending on a given number out of 100. i want it to activate when it is scrolled to, instead of on reload, which it currently is set to. I cant find anything on here already.
Javascript is new to me, so trying to get the hang of it, thanks
$('.progress-wrap').each(function(){
percent = $(this);
bar = $(this).children('.progress-bar');
moveProgressBar(percent, bar);
});
// on browser resize...
$(window).resize(function() {
$('.progress-wrap').each(function(){
percent = $(this);
bar = $(this).children('.progress-bar');
moveProgressBar(percent, bar);
});
});
// SIGNATURE PROGRESS
function moveProgressBar(percent, bar) {
var getPercent = (percent.data('progress-percent') / 100);
var getProgressWrapWidth = percent.width();
var progressTotal = getPercent * getProgressWrapWidth;
var animationLength = 1000;
// on page load, animate percentage bar to data percentage length
// .stop() used to prevent animation queueing
bar.stop().animate({
left: progressTotal
}, animationLength);
}
<div class="progress-wrap progress star" data-progress-percent="70">
<div class="progress-bar progress"></div>
</div>
This should work:
Replace #someElement with the Id of the element that when in view fires the function you want.
someFunction() is the function that you want to run when the element is in view
$(document).on('scroll', function() {
if( $(this).scrollTop() >= $('#someElement').position().top ) {
someFunction();
}
});
Looks like you are using jquery - it would be easier to do this in vanilla javascript like so:
window.onscroll = function (e) {
// called when the window is scrolled.
}
You may want to have a look at: Detect if user is scrolling for jquery options.

jQuery scroll event: how to determine amount scrolled (scroll delta) in pixels?

I have this event:
$(window).scroll(function(e){
console.log(e);
})
I want to know, how much I have scroll value in pixels, because I think, scroll value depends from window size and screen resolution.
Function parameter e does not contains this information.
I can store $(window).scrollTop() after every scroll and calculate difference, but can I do it differently?
The "scroll value" does not depend on the window size or screen resolution. The "scroll value" is simply the number of pixels scrolled.
However, whether you are able to scroll at all, and the amount you can scroll is based on available real estate for the container and the dimensions of the content within the container (in this case the container is document.documentElement, or document.body for older browsers).
You are correct that the scroll event does not contain this information. It does not provide a delta property to indicate the number of pixels scrolled. This is true for the native scroll event and the jQuery scroll event. This seems like it would be a useful feature to have, similar to how mousewheel events provide properties for X and Y delta.
I do not know, and will not speculate upon, why the powers-that-be did not provide a delta property for scroll, but that is out of scope for this question (feel free to post a separate question about this).
The method you are using of storing scrollTop in a variable and comparing it to the current scrollTop is the best (and only) method I have found. However, you can simplify this a bit by extending jQuery to provide a new custom event, per this article: http://learn.jquery.com/events/event-extensions/
Here is an example extension I created that works with window / document scrolling. It is a custom event called scrolldelta that automatically tracks the X and Y delta (as scrollLeftDelta and scrollTopDelta, respectively). I have not tried it with other elements; leaving this as exercise for the reader. This works in currrent versions of Chrome and Firefox. It uses the trick for getting the sum of document.documentElement.scrollTop and document.body.scrollTop to handle the bug where Chrome updates body.scrollTop instead of documentElement.scrollTop (IE and FF update documentElement.scrollTop; see https://code.google.com/p/chromium/issues/detail?id=2891).
JSFiddle demo: http://jsfiddle.net/tew9zxc1/
Runnable Snippet (scroll down and click Run code snippet):
// custom 'scrolldelta' event extends 'scroll' event
jQuery.event.special.scrolldelta = {
delegateType: "scroll",
bindType: "scroll",
handle: function (event) {
var handleObj = event.handleObj;
var targetData = jQuery.data(event.target);
var ret = null;
var elem = event.target;
var isDoc = elem === document;
var oldTop = targetData.top || 0;
var oldLeft = targetData.left || 0;
targetData.top = isDoc ? elem.documentElement.scrollTop + elem.body.scrollTop : elem.scrollTop;
targetData.left = isDoc ? elem.documentElement.scrollLeft + elem.body.scrollLeft : elem.scrollLeft;
event.scrollTopDelta = targetData.top - oldTop;
event.scrollTop = targetData.top;
event.scrollLeftDelta = targetData.left - oldLeft;
event.scrollLeft = targetData.left;
event.type = handleObj.origType;
ret = handleObj.handler.apply(this, arguments);
event.type = handleObj.type;
return ret;
}
};
// bind to custom 'scrolldelta' event
$(window).on('scrolldelta', function (e) {
var top = e.scrollTop;
var topDelta = e.scrollTopDelta;
var left = e.scrollLeft;
var leftDelta = e.scrollLeftDelta;
// do stuff with the above info; for now just display it to user
var feedbackText = 'scrollTop: ' + top.toString() + 'px (' + (topDelta >= 0 ? '+' : '') + topDelta.toString() + 'px), scrollLeft: ' + left.toString() + 'px (' + (leftDelta >= 0 ? '+' : '') + leftDelta.toString() + 'px)';
document.getElementById('feedback').innerHTML = feedbackText;
});
#content {
/* make window tall enough for vertical scroll */
height: 2000px;
/* make window wide enough for horizontal scroll */
width: 2000px;
/* visualization of scrollable content */
background-color: blue;
}
#feedback {
border:2px solid red;
padding: 4px;
color: black;
position: fixed;
top: 0;
height: 20px;
background-color: #fff;
font-family:'Segoe UI', 'Arial';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='feedback'>scrollTop: 0px, scrollLeft: 0px</div>
<div id='content'></div>
Note that you may want debounce the event depending on what you are doing. You didn't provide very much context in your question, but if you give a better example of what you are actually using this info for we can provide a better answer. (Please show more of your code, and how you are using the "scroll value").
To detemine how many pixels were scrolled you have to keep in mind that the scroll event gets fired almost every pixel that you move. The way to accomplish it is to save the previous scrolled value and compare that in a timeout. Like this:
var scrollValue = 0;
var scrollTimeout = false
$(window).scroll(function(event){
/* Clear it so the function only triggers when scroll events have stopped firing*/
clearTimeout(scrollTimeout);
/* Set it so it fires after a second, but gets cleared after a new triggered event*/
scrollTimeout = setTimeout(function(){
var scrolled = $(document).scrollTop() - scrollValue;
scrollValue = $(document).scrollTop();
alert("The value scrolled was " + scrolled);
}, 1000);
});
This way you will get the amount of scrolled a second after scrolling (this is adjustable but you have to keep in mind that the smooth scrolling that is so prevalent today has some run-out time and you dont want to trigger before a full stop).
The other way to do this? Yes, possible, with jQuery Mobile
I do not appreciate this solution, because it is necessary to include heavy jQuery mobile. Solution:
var diff, top = 0;
$(document).on("scrollstart",function () {
// event fired when scrolling is started
top = $(window).scrollTop();
});
$(document).on("scrollstop",function () {
// event fired when scrolling is stopped
diff = Math.abs($(window).scrollTop() - top);
});
To reduce the used processing power by adding a timer to a Jquery scroll method is probably not a great idea. The visual effect is indeed quite bad.
The whole web browsing experience could be made much better by hiding the scrolling element just when the scroll begins and making it slide in (at the right position) some time after. The scrolling even can be checked with a delay too.
This solution works great.
$(document).ready(function() {
var element = $('.movable_div'),
originalY = element.offset().top;
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
element.hide();
element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + 35
}, 2000,function(){element.slideDown(500,"swing");});
});
});
Live demo here

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

How to do an infinite scroll in plain Javascript

I want to avoid using jQuery or another library for the sake of keeping my code minimal, I need very little in the way of features, I just want to append to a list when the user scrolls to the bottom. How would I do this in plain Javascript?
Basicaly you just need to hook the event scroll, check if the user scrolled down enough and add some content if so:
<html><body>
<div id="test">scroll to understand</div>
<div id="wrapper" style="height: 400px; overflow: auto;">
<div id="content"> </div>
</div>
<script language="JavaScript">
// we will add this content, replace for anything you want to add
var more = '<div style="height: 1000px; background: #EEE;"></div>';
var wrapper = document.getElementById("wrapper");
var content = document.getElementById("content");
var test = document.getElementById("test");
content.innerHTML = more;
// cross browser addEvent, today you can safely use just addEventListener
function addEvent(obj,ev,fn) {
if(obj.addEventListener) obj.addEventListener(ev,fn,false);
else if(obj.attachEvent) obj.attachEvent("on"+ev,fn);
}
// this is the scroll event handler
function scroller() {
// print relevant scroll info
test.innerHTML = wrapper.scrollTop+"+"+wrapper.offsetHeight+"+100>"+content.offsetHeight;
// add more contents if user scrolled down enough
if(wrapper.scrollTop+wrapper.offsetHeight+100>content.offsetHeight) {
content.innerHTML+= more;
}
}
// hook the scroll handler to scroll event
addEvent(wrapper,"scroll",scroller);
</script>
</body></html>
For achieving this behaviour you don't need jQuery or a jQuery plugin. You can use only CSS or JavaScript (if you want to cover all browsers).
But don't use onScroll: you can do all of this with just vanilla JS and the Intersection Observer API.
All you need to do is place elements and listen for when they become available in the screen. The Intersection Observer API is very customisable to fit all your needs.
In summary: you accomplish that with a few JavaScript & HTML lines and it's much more performant than listening for scroll events in the browser.
Excellent demo code for infinite scroll. Goes to show that you don't need jQuery and Angular for any browser independent work. But new boys today are out of touch with pure Javascript that we old guys still trust and use. Here I have simplified the code further:
// we will add this content, replace for anything you want to add
var wrapper, content, test;
var more = '<div style="height:1000px; background:#EEE;"></div>';
// this is the scroll event handler
function scroller() {
// print relevant scroll info
test.innerHTML = wrapper.scrollTop + " + " + wrapper.offsetHeight + " + 100 > " + content.offsetHeight;
// add more contents if user scrolled down enough
if (wrapper.scrollTop + wrapper.offsetHeight + 100 > content.offsetHeight) {
content.innerHTML += more; // NK: Here you can make an Ajax call and fetch content to append to content.innerHTML
}
}
wrapper = document.getElementById("wrapper");
content = document.getElementById("content");
test = document.getElementById("test");
content.innerHTML = more;
// hook the scroll handler to scroll event
if (wrapper.addEventListener) // NK: Works on all new browsers
wrapper.addEventListener("scroll", scroller, false);
else if (wrapper.attachEvent) // NK: Works on old IE
wrapper.attachEvent("onscroll", scroller);
<div id="test">scroll to understand</div>
<div id="wrapper" style="height: 400px; overflow: auto;">
<div id="content"> </div>
</div>
domElem.addEventListener(
'scroll',
function(evt) { ... },
false
);
and handle evt/scroll position appropriately.
I see great answers to your question, but for a scrolling that is not associated with any HTML element or content (just an empty HTML page), here is how I did it:
document.querySelector("body").style.height = "1000px";
window.addEventListener("scroll", function() {
var body = document.querySelector("body");
var height = body.style.height;
height = height.slice(0, -2);
height = Number(height);
return function() {
if(height - window.scrollY < 700) {
height += height / 2;
}
body.style.height = height + "px";
};
}());
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
I hope this helps someone out there :)
Assume HTML:
<div class="container"></div>
let container = document.querySelector('.container');
// when user scrolls to last list item in view, wait for 1.5seconds and load next 10 list items, and continue thus.
window.addEventListener('scroll', function(){
setTimeout(() => {
loadMoreList(5);
}, 1500);
});
loadMoreList(20); // load first 20 list items.
function loadMoreList(num) {
let scrollY = window.scrollY;
let innerHeight = window.innerHeight;
let offsetHeight = document.body.offsetHeight;
if (scrollY + innerHeight > offsetHeight - 100) {
let item = 1;
let ul = document.createElement('ul');
for (var i = 0; i < num; i++) {
let li = document.createElement('li');
li.innerText = 'List Item ' + item++;
ul.appendChild(li);
container.appendChild(ul);
}
}
}
Note: The more important parts are: the scroll event listener and the loadMoreList function. You don't necessarily need the argument num.
The for loop just ensures that on load, the function is called and 20 items are uniquely created and displayed.

Categories

Resources