jQuery Scroll Timeout - javascript

I'm trying to put a delay on page scroll so if I put some animation, it will not ruin. Here is my code:
var lastScrollY = 0,
delayFlag = true,
delayTime = 1000;
$(window).on('scroll', function(e) {
if(delayFlag == true) {
delayFlag = false;
var posY = $(this).scrollTop(),
sectionH = $('.page').height(),
multiplier = (Math.round(lastScrollY / sectionH));
if(lastScrollY > posY) {
$(window).scrollTop((multiplier - 1) * sectionH);
}
else {
$(window).scrollTop((multiplier + 1) * sectionH);
}
lastScrollY = posY;
setTimeout(function() { delayFlag = true }, delayTime);
}
else {
e.preventDefault();
}
});
jQuery preventDefault() is not working. Is there any way I can put some delay on scroll event?

e.preventDefault(); is for preventing the default action of an event. For example, clicking on an anchor will cause the page to navigate to the address stored on the anchor's href, and calling e.preventDefault(); in an anchor's click event will cause this navigation to not happen.
e.preventDefault(); does not, however, cancel the event that just occurred. Calling it in the onchange event of a form input will not revert its value back to what it just was, and calling it in the scroll event will not cancel the scroll.

While I wouldn't recommend this, from a UX perspective (personally, I hate pages that stop me from going someplace in the site, just so I have to watch their ad or whathaveyou, and I'm fairly sure I'm not the only one...), what you might be able to do, rather than capture the scroll event, is turn off scrolling for the area to start with.
So, have something along these lines (example jsFiddle: http://jsfiddle.net/mori57/cmLun/):
In CSS:
.noscroll {
overflow:hidden;
}
And in your JS:
var lastScrollY = 0,
delayFlag = true,
delayTime = 1000;
$(function(){
$("body").addClass("noscroll");
window.setTimeout(function(){
$("body").removeClass("noscroll");
}, delayTime );
});

Related

jQuery "Snap To" Effect

I have a specific effect I want for a website I'm building. As you can see in this website, I want the screen to "snap to" the next section after the user scrolls, but only after (not the instant) the scroll event has fired. The reason I don't want to use a plugin like panelSnap is because I
1: Want smaller code and
2. Want the website, when viewed on mobile, to have more of the "instant snap" effect (try reducing the browser size in the website mentioned above). I know I theoretically could try combining two plugins, like panelsnap and scrollify, and activate them appropriately when the browser is a certain width, but I don't know if I want to do that... :(
So all of that said, here's the code:
var scrollTimeout = null;
var currentElem = 0;
var options = {
scrollSpeed: 1100,
selector: 'div.panels',
scrollDelay: 500,
};
$(document).ready(function() {
var $snapElems = $(options.selector);
console.log($($snapElems[currentElem]).offset().top);
function snap() {
if ($('html, body').scrollTop() >= $($snapElems[currentElem]).offset().top) {
if (currentElem < $snapElems.length-1) {
currentElem++;
}
}else{
if (currentElem > 0) {
currentElem = currentElem - 1;
}
}
$('html, body').animate({
scrollTop: $($snapElems[currentElem]).offset().top
}, options.scrollSpeed);
}
$(window).scroll(function() {
if ($(window).innerWidth() > 766) {
if (scrollTimeout) {clearTimeout(scrollTimeout);}
scrollTimeout = setTimeout(function(){snap()}, options.scrollDelay);
}else{
//I'll deal with this later
}
});
});
My problem is that every time the snap function is called, it triggers the scroll event, which throws it into a loop where the window won't stop scrolling between the first and second elements. Here's the poor, dysfunctional site: https://tcfchurch.herokuapp.com/index.html Thank for the help.
You can use a boolean to record when the scroll animation in snap is in progress and prevent your $(window).scroll() event handler from taking any action.
Here's a working example:
var scrollTimeout = null;
var currentElem = 0;
var options = {
scrollSpeed: 1100,
selector: 'div.panels',
scrollDelay: 500,
};
$(document).ready(function() {
var scrollInProgress = false;
var $snapElems = $(options.selector);
console.log($($snapElems[currentElem]).offset().top);
function snap() {
if ($('html, body').scrollTop() >= $($snapElems[currentElem]).offset().top) {
if (currentElem < $snapElems.length-1) {
currentElem++;
}
}else{
if (currentElem > 0) {
currentElem = currentElem - 1;
}
}
scrollInProgress = true;
$('html, body').animate({
scrollTop: $($snapElems[currentElem]).offset().top
}, options.scrollSpeed, 'swing', function() {
// this function is invoked when the scroll animate is complete
scrollInProgress = false;
});
}
$(window).scroll(function() {
if (scrollInProgress == false) {
if ($(window).innerWidth() > 766) {
if (scrollTimeout) {clearTimeout(scrollTimeout);}
scrollTimeout = setTimeout(function(){snap()}, options.scrollDelay);
}else{
//I'll deal with this later
}
}
});
});
The variable scrollInProgress is set to false by default. It is then set to true when the scroll animate starts. When the animate finishes, scrollInProgress is set back to false. A simple if statement at the top of your $(window).scroll() event handler prevents the handler from taking any action while the animate scroll is in progress.
Have you considered using the well known fullPage.js library for that? Check out this normal scroll example. The snap timeout is configurable through the option fitToSectionDelay.
And nothing to worry about the size... it is 7Kb Gzipped!
I know I theoretically could try combining two plugins, like panelsnap and scrollify, and activate them appropriately when the browser is a certain width, but I don't know if I want to do that
fullPage.js also provides responsiveWidth and responsiveHeight options to turn it off under certain dimensions.

Idle timeout warning modal working on screen reader

I need help with a modal that fires when user is idle. It works great until I test on Firefox with NVDA running. There are issues with focus when using the arrow keys and when I swipe on a mobile. When the modal appears and the user uses arrow or swipes the focus will bounce from the yes button to the header after a few seconds if I wait to click it. I have loaded the working example to: https://jsfiddle.net/ncanqaam/
I changed the idle time period to one minute and removed a portion which calls the server to extend the user's session.
var state ="L";
var timeoutPeriod = 540000;
var oneMinute = 60000;
var sevenMinutes = 60000;
var lastActivity = new Date();
function getIdleTime() {
return new Date().getTime() - lastActivity.getTime();
}
//Add Movement Detection
function addMovementListener() {
$(document).on('mousemove', onMovementHandler);
$(document).on('keypress', onMovementHandler);
$(document).on('touchstart touchend', onMovementHandler);
}
//Remove Movement Detection
function removeMovementListener() {
$(document).off('mousemove', onMovementHandler);
$(document).off('keypress', onMovementHandler);
$(document).off('touchstart touchend', onMovementHandler);
}
//Create Movement Handler
function onMovementHandler(ev) {
lastActivity = new Date();
console.log("Something moved, idle time = " + lastActivity.getTime());
}
function hide() {
$('#overlayTY').removeClass('opened'); // remove the overlay in order to make the main screen available again
$('#overlayTY, #modal-session-timeout').css('display', 'none'); // hide the modal window
$('#modal-session-timeout').attr('aria-hidden', 'true'); // mark the modal window as hidden
$('#modal-session-timeout').removeAttr('aria-hidden'); // mark the main page as visible
}
if (state == "L") {
$(document).ready(function() {
//Call Event Listerner to for movement detection
addMovementListener();
setInterval(checkIdleTime, 5000);
});
function endSession() {
console.log('Goodbye!');
}
var modalActive = false;
function checkIdleTime() {
var idleTime = getIdleTime();
console.log("The total idle time is " + idleTime / oneMinute + " minutes.");
if (idleTime > sevenMinutes) {
var prevFocus = $(document.activeElement);
console.log('previously: ' + prevFocus);
var modal = new window.AccessibleModal({
mainPage: $('#oc-container'),
overlay: $('#overlayTY').css('display', 'block'),
modal: $('#modal-session-timeout')
});
if (modalActive === false) {
console.log(modalActive);
$('#modal-session-timeout').insertBefore('#oc-container');
$('#overlayTY').insertBefore('#modal-session-timeout');
modal.show();
$('#modal-overlay').removeClass('opened');
modalActive = true;
console.log(modalActive);
console.log('the modal is active');
$('.js-timeout-refresh').on('click touchstart touchend', function(){
hide();
modalActive = false;
prevFocus.focus();
addMovementListener();
lastActivity = new Date();
});
$('.js-timeout-session-end').on('click touchstart touchend', function(){
hide();
$('#overlayTY').css('display', 'none');
endSession();
});
}
}
if ($('#overlayTY').css('display') === 'block'){
removeMovementListener();
}
if (idleTime > timeoutPeriod) {
endSession();
}
}
}
Possibles solutions
Disable pointer-events on body when overlay is visible. this will restrict keyboard/swipe events on body elements
Use JS/jQuery to trigger focus on the yes button
The issue is with Voiceover Safari when a user swipes on an anchor or button the focus is set on these elements; however, if the element is an H2 it will not receive focus because natively it is not supposed to receive any. To compensate I attempted to set gesture events on the H2 but, Voiceover Safari needs time to read the element text or label out load, so it prevents any event from firing and this creates a problem when trying to set focus on a modal which loads from a timeout function rather than a clickable element. Hopefully Apple will address this in the future.

vertical scroll two tables at the same time

I have two tables that must scroll together:
$('.vscroll').on('scroll', function (e) {
divTable1.scrollTop = e.scrollTop;
divTable2.scrollTop = e.scrollTop;
There's a little lag issue though. Table1 scrolls milliseconds before Table2.
I know scrollTop fires the scroll event, but is there a way to delay the scrolling of Table1 until Table2's scrollTop is also set?
Try using a setTimeout to trigger the scrolls, and then return false to cancel the original scrollevent:
var ignoreEvent = false;
$(".vscroll").on('scroll', function (e) {
if (!ignoreEvent) {
setTimeout(function() {
ignoreEvent = true;
table1.scrollTop = e.scrollTop;
table2.scrolLTop = e.scrollTop;
}, 100);
}
ignoreEvent = false;
return false; // cancels the original scroll event.
}
I'm using divs instead of tables but you get the idea
$("div").on("scroll",function(){
$("div:not(this)").scrollTop($(this).scrollTop());
});
DEMO

Setting a jScrollPane to autoscroll left and right, but pause on click?

Fiddle: http://jsfiddle.net/RJShm/
I have a jScrollPane that currently scroll from left, to right, then back left, and stops. What I'd like is for this to continually scroll from left to right, the right to left, then repeat. I have this fairly close to working by using pane.bind('jsp-scroll-x'..., but I can't seem to get it to scroll back to the right after one cycle. Current code for that:
pane.bind('jsp-scroll-x', function (event, pos_x, at_left, at_right) {
if (at_right)
{
api.scrollToX(0);
$(this).unbind(event);
}
});
I would also like for this to stop autoscrolling when anything in the pane is clicked (scroll bar, arrows, content, anything), and it would preferably restart after a few seconds of no clicks.
So, in short, how do I:
Make the jScrollPane scroll left/right automatically
Stop autoscrolling when clicked
Restart autoscrolling after a few seconds of no clicks inside the pane
Thanks
EDIT: jScrollPane Settings, and api for your convenience.
I have updated the handler for toggling the infinite scroll and also implemented click handler to pause the scroll and resume after a timeout (5 seconds). See draft code below and check the DEMO: http://jsfiddle.net/p6jLt/
var defaultSettings = {
showArrows: true,
animateScroll: true,
animateDuration: 5000
},
pauseSettings = {
showArrows: true,
animateScroll: false
};
var pane = $('.scroll-pane').jScrollPane(defaultSettings);
var api = pane.data('jsp');
var isFirst = true,
posX = 0,
isLeft = false,
timer;
pane.bind('jsp-scroll-x', scrollFx)
.mousedown(function () {
//lets make sure the below is
//executed only once after automatic croll
if (posX != -1) {
$(this).unbind('jsp-scroll-x');
api.scrollToX(posX);
api.reinitialise(pauseSettings); //no animation
posX = -1;
}
}).mouseup(function () {
clearTimeout(timer); //clear any previous timer
timer = setTimeout(function () {
isFirst = true;
posX = 0; //reset the killer switch
api.reinitialise(defaultSettings); //animateed scroll
pane.bind('jsp-scroll-x', scrollFx); //rebind
api.scrollToX(isLeft ? 0 : api.getContentWidth()); //resume scroll
}, 5000);
});
var scroll = api.scrollToX(api.getContentWidth());
function scrollFx(event, pos_x, at_left, at_right) {
if (posX == -1) { //kill scroll
$(this).unbind(event);
return false;
}
if (at_right) {
api.scrollToX(0);
isLeft = true; //used for restart
} else if (at_left && !isFirst) {
api.scrollToX(api.getContentWidth());
isLeft = false; //used for restart
}
isFirst = false;
posX = pos_x;
}
Issues: The plugin is little buggy with scroll sometimes, but it doesn't break the infinite scroll. You may find the little hicks on scroll, but it works for the most part. Test it out thoroughly and see how it goes.

Adding listener for position on screen

I'd like to set something up on my site where when you scroll within 15% of the bottom of the page an element flyouts from the side... I'm not sure how to get started here... should I add a listener for a scroll function or something?
I'm trying to recreate the effect at the bottom of this page: http://www.nytimes.com/2011/01/25/world/europe/25moscow.html?_r=1
update
I have this code....
console.log(document.body.scrollTop); //shows 0
console.log(document.body.scrollHeight * 0.85); //shows 1038.7
if (document.body.scrollTop > document.body.scrollHeight * 0.85) {
console.log();
$('#flyout').animate({
right: '0'
},
5000,
function() {
});
}
the console.log() values aren't changing when I scroll to the bottom of the page. The page is twice as long as my viewport.
[Working Demo]
$(document).ready(function () {
var ROOT = (function () {
var html = document.documentElement;
var htmlScrollTop = html.scrollTop++;
var root = html.scrollTop == htmlScrollTop + 1 ? html : document.body;
html.scrollTop = htmlScrollTop;
return root;
})();
// may be recalculated on resize
var limit = (document.body.scrollHeight - $(window).height()) * 0.85;
var visible = false;
var last = +new Date;
$(window).scroll(function () {
if (+new Date - last > 30) { // more than 30 ms elapsed
if (visible && ROOT.scrollTop < limit) {
setTimeout(function () { hide(); visible = false; }, 1);
} else if (!visible && ROOT.scrollTop > limit) {
setTimeout(function () { show(); visible = true; }, 1);
}
last = +new Date;
}
});
});
I know this is an old topic, but the above code that received the check mark was also triggering the $(window).scroll() event listener too many times.
I guess twitter had this same issue at one point. John Resig blogged about it here: http://ejohn.org/blog/learning-from-twitter/
$(document).ready(function(){
var ROOT = (function () {
var html = document.documentElement;
var htmlScrollTop = html.scrollTop++;
var root = html.scrollTop == htmlScrollTop + 1 ? html : document.body;
html.scrollTop = htmlScrollTop;
return root;
})();
// may be recalculated on resize
var limit = (document.body.scrollHeight - $(window).height()) * 0.85;
var visible = false;
var last = +new Date;
var didScroll = false;
$(window).scroll(function(){
didScroll = true;
})
setInterval(function(){
if(didScroll){
didScroll = false;
if (visible && ROOT.scrollTop < limit) {
hideCredit();
visible = false;
} else if (!visible && ROOT.scrollTop > limit) {
showCredit();
visible = true;
}
}
}, 30);
function hideCredit(){
console.log('The hideCredit function has been called.');
}
function showCredit(){
console.log('The showCredit function has been called.');
}
});
So the difference between the two blocks of code is when and how the timer is called. In this code the timer is called off the bat. So every 30 millaseconds, it checks to see if the page has been scrolled. if it's been scrolled, then it checks to see if we've passed the point on the page where we want to show the hidden content. Then, if that checks true, the actual function then gets called to show the content. (In my case I've just got a console.log print out in there right now.
This seems to be better to me than the other solution because the final function only gets called once per iteration. With the other solution, the final function was being called between 4 and 5 times. That's got to be saving resources. But maybe I'm missing something.
bad idea to capture the scroll event, best to use a timer and every few milliseconds check the scroll position and if in the range you need then execute the necessary code for what you need
Update: in the past few years the best practice is to subscribe to the event and use a throttle avoiding excessive processing https://lodash.com/docs#throttle
Something like this should work:
$(window).scroll(function() {
if (document.body.scrollTop > document.body.scrollHeight * 0.85) {
// flyout
}
});
document.body.scrollTop may not work equally well on all browsers (it actually depends on browser and doctype); so we need to abstract that in a function.
Also, we need to flyout only one time. So we can unbind the event handler after having flyed out.
And we don't want the flyout effect to slow down scrolling, so we will run our flytout function out of the event loop (by using setTimeout()).
Here is the final code:
// we bind the scroll event, with the 'flyout' namespace
// so we can unbind easily
$(window).bind('scroll.flyout', (function() {
// this function is defined only once
// it is private to our event handler
function getScrollTop() {
// if one of these values evaluates to false, this picks the other
return (document.documentElement.scrollTop||document.body.scrollTop);
}
// this is the actual event handler
// it has the getScrollTop() in its scope
return function() {
if (getScrollTop() > (document.body.scrollHeight-$(window).height()) * 0.85) {
// flyout
// out of the event loop
setTimeout(function() {
alert('flyout!');
}, 1);
// unbind the event handler
// so that it's not call anymore
$(this).unbind('scroll.flyout');
}
};
})());
So in the end, only getScrollTop() > document.body.scrollHeight * 0.85 is executed at each scroll event, which is acceptable.
The flyout effect is ran only one time, and after the event has returned, so it won't affect scrolling.

Categories

Resources