reduce number of calls for .resize and .scroll methods - javascript

I'm using the following code to find out which part of the page the viewer is visiting (something like google books, to find out the page that's being viewed) :
$("#main-content").scroll(function () {
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select(undefined);
});
also in another part I use $(window).resize( ... ) to fit my content in current window size, which is called for every single resize . as you can imagine this slows down the page alot, specially on older hardwares. Is there any way to realise when scrolling or resizing is stopped and then start doing the stuff, so number of processes is reduced ? something like $("#main-content").scrollStop ???

You can do two things.
1.) Set up a timeout so that resize/scroll only happens after some idle state:
var timeout;
$("#main-content").scroll(function () {
clearTimeout(timeout);
timeout = setTimeout(function(){
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select(); // note: undefined is passed by default
}, 200);
});
2.) Limit the number of calls / sec:
var lastScroll = 0;
$("#main-content").scroll(function () {
var now = +new Date;
if (now - lastScroll > 100) { // only execute if (elapsed > 100ms)
Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
window.location.hash = "#"+Nx.curPage;
Nx.select();
lastScroll = now;
}
});
​

Try the function below. It checks if the user has scrolled past a certain no. of pixels, but the function only fires at set intervals (5 times a second in the example below) rather than continuously during scrolling.
var scrollCheck;
$(window).on('scroll', function() {
clearInterval(scrollCheck);
scrollCheck = setInterval(function(){
clearInterval(scrollCheck);
scrollPosition = $(this).scrollTop();
scrollAmount = 150 // no. of pixels that have been scrolled from top
if(scrollPosition > scrollAmount){
alert('scrolled past point')
}else{
alert('not scrolled past point')
}
},200);
});

Related

Infinite auto scroll top-to-bottom and back, how to control/configure speed, time of pause at end?

I'm trying to make a long page of images scroll up and down infinitely (for an exhibition).
This is what I've been working with (code I found here, so helpful!):
https://jsfiddle.net/p7r73tke/
It's mostly working ok for what I want, but I need more control over speed and pause.
How can I make the pause at the top longer?
is there a way to make it pause randomly for ~1 second ?
does anyone know of an easier way to do what I'm thinking of? maybe as samuel-liew suggests, javascript is not the best solution for the problem
thank u thank u!
function scrollpage() {
function f() {
window.scrollTo(0, i); //idk
if (status == 0) {
i = i + 50; //scroll speed top to bottom?
if (i >= Height) {
status = 30; //idk?
}
} else {
i = i - 10; //scroll speed bottom to top?
if (i <= 1) { // if you don't want continue scroll then remove this if condition
status = 0; //idk
}
}
setTimeout(f, 0.01); //idk
}
f();
}
var Height = 15000; //doc height input manually
var i = 1, //idk
j = Height,
status = 0; //idk
scrollpage();
(I'm new and tender to JavaScript, as you can see in the comments)
Thanks for any help!
jQuery solution:
var speed = 10000; // 10000 = 10 seconds
var doScroll = function() {
var direction = $(window).scrollTop() != 0 ? 0 : $(document).height() - $(window).height();
$('html, body').animate({ scrollTop: direction }, speed, 'linear');
}
doScroll(); // once on page load
setInterval(doScroll, speed + 10); // once every X ms
DEMO: http://jsfiddle.net/samliew/k35tbgau/
JavaScript:
Sorry, I do not recommend pure JavaScript for this as you have to take into account:
Cross-browser issues with getting window height, document height, and current scroll position
Recalculating the scroll speed based on content height every time the browser is resized
Programming an animation function
Keeping track of intervals and timeouts, and when you need to clear them
Direction/state of scroll
Taking into consideration if user manually scrolls the scrollbar
Probably lots more...

Efficient use jquery scroll function

I want to check if the scrollTop is greater than 1. But when I use the following code, the scroll event keeps firing when the user scrolls which leads to bad performance.
$(window).on('scroll', function(){
var scrollTop = $(this).scrollTop();
if(scrollTop > 1){
$('.header').addClass('active');
} else{
$('.header').removeClass('active');
}
});
Is there a more efficient way to do this, so performance stays in check?
For optimisations sake, stop requesting the header dynamically each time.
Store a reference to the header in the window object.
$(document).ready(function() {
window.headerObject = $('.header');
window.jQueryWindow = $(window);
});
$(window).on('scroll', function(){
var scrollTop = jQueryWindow.scrollTop();
if(scrollTop > 1){
window.headerObject.addClass('active');
} else{
window.headerObject.removeClass('active');
}
});
Instead of having to traverse the DOM to find .header multiple times each request and making a new jquery object of the window object each time, you simply store them, negating the initialisation cost improving speed.
if you want to comporare speeds:
$(document).ready(function() {
window.headerObject = $('.header');
window.jQueryWindow = $(window);
});
$(window).on('scroll', function(){
starttime = performance.now();
var scrollTop = jQueryWindow.scrollTop();
if(scrollTop > 1){
window.headerObject.addClass('active');
} else{
window.headerObject.removeClass('active');
}
console.log('scroll optimised took' + (performance.now() - starttime) + " milliseconds");
});
$(window).on('scroll', function(){
starttime = performance.now();
var scrollTop = $(this).scrollTop();
if(scrollTop > 1){
$('.header').addClass('active');
} else{
$('.header').removeClass('active');
}
console.log('scroll dynamic took' + (performance.now() - starttime) + " milliseconds");
});
scroll optimised took 0.060999998822808266 milliseconds
scroll dynamic took 0.26700000125856604 milliseconds
As you can see, the optimised code takes on average 0.06 milliseconds whilst the full dynamic selector takes 0.26 milliseconds.
Quite the performance gain.
The delay might come more though from the calculations needed for restyling active than the cost of this loop.

Javascript window.scrollBy speeds up

I have a project I'm working on with a site that receives information and displays it in a table. If the table is larger than the screen, the page will automatically scroll down, and when it hits the bottom, back up, and repeat, repeat, up and down.
The issue I'm having is that every time I send a chunk of data to the site, the speed of the scrollBy increases. Every refresh scroll incrementally faster, up and down.
Here is the code:
window.onload = function() {
...
buildHeader(event);
buildTable(event);
};
function buildTable(event) {
...
if((+tableHeight) > window.innerHeight){
pageScroll();
}
}
var scrollDirection = 1;
function pageScroll() {
window.scrollBy(0,scrollDirection); // horizontal and vertical scroll increments
scrolldelay = setTimeout('pageScroll()',50); // scrolls every 50 milliseconds
if ( (window.scrollY === 0) || (window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
scrollDirection = -1*scrollDirection;
}
}
I would like to know why each time the page is sent information the speed increases. Isit necessary to cancel an occurring scrollBy before calling it again?
Any help would be greatly appreciated.
Thanks
Josh
Yes, it is. If you call scrollby twice, it will scroll twice. You have a self-calling timeout, which means that it would repeatedly call the function. The timeout is async, and won't be cancelled just because something changed.
Luckily, setTimeout returns an ID that you can pass to clearTimeout().
So you can do something like this:
var currentTimeout;
function buildTable(event) {...
if ((+tableHeight) > window.innerHeight) {
window.clearTimeout(currentTimeout);
pageScroll();
}
}
function pageScroll() {
window.scrollBy(0, scrollDirection); // horizontal and vertical scroll increments
currentTimeout = setTimeout('pageScroll()', 50); // scrolls every 50 milliseconds
if ((window.scrollY === 0) || (window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
scrollDirection = -1 * scrollDirection;
}
}
Here's a simpler example to demonstrate the behavior. jsFiddle example.

smooth auto scroll by using javascript

I am trying to implement some code on my web page to auto-scroll after loading the page. I used a Javascript function to perform auto-scrolling, and I called my function when the page loads, but the page is still not scrolling smoothly! Is there any way to auto scroll my page smoothly?
Here is my Javascript function:
function pageScroll() {
window.scrollBy(0,50); // horizontal and vertical scroll increments
scrolldelay = setTimeout('pageScroll()',100); // scrolls every 100 milliseconds
}
It's not smooth because you've got the scroll incrementing by 50 every 100 milliseconds.
change this and the amount you are scrolling by to a smaller number to have the function run with the illusion of being much more 'smooth'.
turn down the speed amount to make this faster or slower.
function pageScroll() {
window.scrollBy(0,1);
scrolldelay = setTimeout(pageScroll,10);
}
will appear to be much smoother, try it ;)
Try to use jQuery, and this code:
$(document).ready(function(){
$('body,html').animate({scrollTop: 156}, 800);
});
156 - position scroll to (px), from top of page.
800 - scroll duration (ms)
You might want to look at the source code for the jQuery ScrollTo plug-in, which scrolls smoothly. Or maybe even just use the plug-in instead of rolling you own function.
Smoothly running animations depends on the clients machine. No matter how fairly you code, you will never be satisfied the way your animation runs on a 128 MB Ram system.
Here is how you can scroll using jQuery:
$(document).scrollTop("50");
You might also want to try out AutoScroll Plugin.
you can use jfunc function to do this.
use jFunc_ScrollPageDown and jFunc_ScrollPageUp function.
http://jfunc.com/jFunc-Functions.aspx.
Since you've tagged the question as 'jquery', why don't you try something like .animate()? This particular jquery function is designed to smoothly animate all sorts of properties, including numeric CSS properties as well as scroll position.
the numbers are hardcoded, but the idea is to move item by item (and header is 52px) and when is down, go back
let elem = document.querySelector(".spfxBirthdaysSpSearch_c7d8290b ");
let lastScrollValue = 0
let double_lastScrollValue = 0
let scrollOptions = { top: 79, left: 0, behavior: 'smooth' }
let l = console.log.bind(console)
let intScroll = window.setInterval(function() {
double_lastScrollValue = lastScrollValue //last
lastScrollValue = elem.scrollTop // after a scroll, this is current
if (double_lastScrollValue > 0 && double_lastScrollValue == lastScrollValue){
elem.scrollBy({ top: elem.scrollHeight * -1, left: 0, behavior: 'smooth' });
} else {
if (elem.scrollTop == 0){
elem.scrollBy({ top: 52, left: 0, behavior: 'smooth' });
} else {
elem.scrollBy(scrollOptions);
}
}
}, 1000);
Here's another take on this, using requestAnimationFrame. It gives you control of the scroll time, and supports easing functions. It's pretty robust, but fair warning: there's no way for the user to interrupt the scroll.
// Easing function takes an number in range [0...1]
// and returns an eased number in that same range.
// See https://easings.net/ for more.
function easeInOutSine(x) { return -(Math.cos(Math.PI * x) - 1) / 2; }
// Simply scrolls the element from the top to the bottom.
// `elem` is the element to scroll
// `time` is the time in milliseconds to take.
// `easing` is an optional easing function.
function scrollToBottom(elem, time, easing)
{
var startTime = null;
var startScroll = elem.scrollTop;
// You can change the following to scroll to a different position.
var targetScroll = elem.scrollHeight - elem.clientHeight;
var scrollDist = targetScroll - startScroll;
easing = easing || (x => x);
function scrollFunc(t)
{
if (startTime === null) startTime = t;
var frac = (t - startTime) / time;
if (frac > 1) frac = 1;
elem.scrollTop = startScroll + Math.ceil(scrollDist * easing(frac));
if (frac < 0.99999)
requestAnimationFrame(scrollFunc);
}
requestAnimationFrame(scrollFunc);
}
// Do the scroll
scrollToBottom(document.getElementById("data"), 10000, easeInOutSine);

infinite-scroll jquery plugin

I am trying to set up infinite-scroll on a site I am developing with Coldfusion, I am new to javascript and jquery so I am having some issues wrapping my head around all of this. Do I need to have pagination on my site in order to use the infinite-scroll plugin, or is there a way to do it with out it?
You do not need infinite scroll plug-in for this. To detect when scroll reaches end of page, with jQuery you can do
$(window).scroll(function () {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
//Add something at the end of the page
}
});
Demo on JsFiddle
I'm using Hussein's answer with AJAX requests. I modified the code to trigger at 300px instead of 10px, but it started causing my appends to multiply before the AJAX request was finished since the scroll call triggers much more frequently in a 300px range than a 10px range.
To fix this, I added a trigger that would be flipped on successful AJAX load. My code looks more like this:
var scrollLoad = true;
$(window).scroll(function () {
if (scrollLoad && $(window).scrollTop() >= $(document).height() - $(window).height() - 300) {
scrollLoad = false;
//Add something at the end of the page
}
});
then in my AJAX response, I set scrollLoad to true.
I built on top of Hussein's little example here to make a jQuery widget. It supports localStorage to temporarily save appended results and it has pause functionality to stop the appending every so often, requiring a click to continue.
Give it a try:
http://www.hawkee.com/snippet/9445/
$(function(){
$(window).scroll(function(){
if($(document).height()<=$(window).scrollTop()+$(window).height()+100){
alert('end of page');
}
});
});
Some one asked for explanation so here is the explanation
here $(document).height()-->is the height of the entire document.In most cases, this is equal to the element of the current document.
$(window).height()-->is the height of the window (browser) means height of whatever you are seeing on browser.
$(window).scrollTop()-->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 measurement of the distance of 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.
$(document).height()<=$(window).scrollTop()+$(window).height()+100
add $(window).scrollTop() with $(window).height() now check whether the result is equal to your documnet height or not. if it is equal means you reached at the end.we are adding 100 too because i want to check before the 100 pixels from the bottom of document(note <= in condition)
please correct me if i am wrong
I had same problem but didn't find suitable plugin for my need. so I wrote following code. this code appends template to element by getting data with ajax and pagination.
for detecting when user scrolls to bottom of div I used this condition:
var t = $("#infiniteContent").offset().top;
var h = $("#infiniteContent").height();
var ws = $(window).scrollTop();
var dh = $(document).height();
var wh = $(window).height();
if (dh - (wh + ws) < dh - (h + t)) {
//now you are at bottom of #infiniteContent element
}
$(document).ready(function(){
$.getJSON("https://jsonplaceholder.typicode.com/comments", { _page: 1, _limit:3 }, function (jsonre) {
appendTemplate(jsonre,1);
});
});
function appendTemplate(jsonre, pageNumber){
//instead of this code you can use a templating plugin like "Mustache"
for(var i =0; i<jsonre.length; i++){
$("#infiniteContent").append("<div class='item'><h2>"+jsonre[i].name+"</h2><p>"+jsonre[i].body+"</p></div>");
}
if (jsonre.length) {
$("#infiniteContent").attr("data-page", parseInt(pageNumber)+1);
$(window).on("scroll", initScroll);
//scroll event will not trigger if window size is greater than or equal to document size
var dh = $(document).height() , wh = $(window).height();
if(wh>=dh){
initScroll();
}
}
else {
$("#infiniteContent").attr("data-page", "");
}
}
function initScroll() {
var t = $("#infiniteContent").offset().top;
var h = $("#infiniteContent").height();
var ws = $(window).scrollTop();
var dh = $(document).height();
var wh = $(window).height();
if (dh - (wh + ws) < dh - (h + t)) {
$(window).off('scroll');
var p = $("#infiniteContent").attr("data-page");
if (p) {
$.getJSON("https://jsonplaceholder.typicode.com/comments", { _page: p, _limit:3 }, function (jsonre) {
appendTemplate(jsonre, p);
});
}
}
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div id="infiniteContent"></div>
If you have a scrollable element, like a div with scroll overflow, but no scrollable document/page, you can take this way.
$(function () {
var s = $(".your-scrollable-element");
var list = $("#your-table-list");
/* On element scroll */
s.scroll(function () {
/* The scroll top plus element height equals to table height */
if ((s.scrollTop() + s.height()) == list.height()) {
/* you code */
}
});
});
I wrote this function using Hussein and Nick's ideas, but I wanted it to use promises for the callback. I also wanted the infinite scrolling area to be on a fixed div and not just the window if the div is sent into the options object. There is an example of that in my second link below. I suggest using a promise library like Q if you want to support older browsers. The cb method may or may not be a promise and it will work regardless.
It is used like so:
html
<div id="feed"></div>
js
var infScroll = infiniteScroll({
cb: function () {
return doSomethingPossiblyAnAJAXPromise();
}
});
If you want the feed to temporarily stop you can return false in the cb method. Useful if you have hit the end of the feed. It can be be started again by calling the infiniteScroll's returned object method 'setShouldLoad' and passing in true and example to go along with the above code.
infScroll.setShouldLoad(true);
The function for infinite scrolling is this
function infiniteScroll (options) {
// these options can be overwritten by the sent in options
var defaultOptions = {
binder: $(window), // parent scrollable element
loadSpot: 300, //
feedContainer: $("#feed"), // container
cb: function () { },
}
options = $.extend(defaultOptions, options);
options.shouldLoad = true;
var returnedOptions = {
setShouldLoad: function (bool) { options.shouldLoad = bool; if(bool) { scrollHandler(); } },
};
function scrollHandler () {
var scrollTop = options.binder.scrollTop();
var height = options.binder[0].innerHeight || options.binder.height();
if (options.shouldLoad && scrollTop >= (options.binder[0].scrollHeight || $(document).height()) - height - options.loadSpot) {
options.shouldLoad = false;
if(typeof options.cb === "function") {
new Promise(function (resolve) {resolve();}).then(function() { return options.cb(); }).then(function (isNotFinished) {
if(typeof isNotFinished === "boolean") {
options.shouldLoad = isNotFinished;
}
});
}
}
}
options.binder.scroll(scrollHandler);
scrollHandler();
return returnedOptions;
}
1 feed example with window as scroller
2 feed example with feed as scroller

Categories

Resources