How to change this script to autoscroll? - javascript

I have a script which has a button to scroll the site but I need it to scroll automatically on page load. I need the script to scroll exactly like shown below, except the button. Could anyone change it for me? I'm new to javascript, thanks..
function scroll(element, speed) {
var distance = element.height();
var duration = distance / speed;
element.animate({scrollTop: distance}, duration, 'linear');
}
$(document).ready(function() {
$("button").click(function() {
scroll($("html, body"), 0.015); // Set as required
});
});

Call the scroll function in on window load, this will scroll the page on load finished.
$(window).on('load', function(){
scroll($("html, body"), 0.015); // Set as required
})

You can try the below JavaScript code
var div = $('.autoscroller');
$('.autoscroller').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(evt) {
if (evt.type === 'DOMMouseScroll' || evt.type === 'keyup' || evt.type === 'mousewheel') {
}
if (evt.originalEvent.detail < 0 || (evt.originalEvent.wheelDelta && evt.originalEvent.wheelDelta > 0)) {
clearInterval(autoscroller);
}
if (evt.originalEvent.detail > 0 || (evt.originalEvent.wheelDelta && evt.originalEvent.wheelDelta < 0)) {
clearInterval(autoscroller);
}
});
var autoscroller = setInterval(function(){
var pos = div.scrollTop();
if ((div.scrollTop() + div.innerHeight()) >= div[0].scrollHeight) {
clearInterval(autoscroller);
}
div.scrollTop(pos + 1);
}, 50);
here on the load of the page. The text are auto-scrolled upto the end of the page.

Related

How do I hover on Browser's cancel button?

I am trying to populate a splash screen on my website and it is populating if scroll pos is between 1-120, using following JS code.
Please suggest what should be done if I want to execute this on hover browser's and tab's cancel button?
How to read that, cause $(window).scrollTop(); won't return anything if it is less that 0.
function setHeightToEmergencyContainer () {
var getWindowHeight = $(window).height();
var setHeight = (getWindowHeight - 123)/2;
}
setHeightToEmergencyContainer();
$(window).resize(function() {
setHeightToEmergencyContainer();
});
function addEvent(obj, evt, fn) {
if (obj.addEventListener) {
obj.addEventListener(evt, fn, false);
}
else if (obj.attachEvent) {
obj.attachEvent("on" + evt, fn);
}
}
addEvent(window,"load",function(e) {
addEvent(document, "mouseout", function(e) {
e = e ? e : window.event;
var from = e.relatedTarget || e.toElement;
if (!from || from.nodeName == "HTML") {
// stop your drag event here
// for now we can just use an alert
setHeightToEmergencyContainer();
var scroll = $(window).scrollTop();
console.log("scroll pos :: "+scroll);
if(scroll > 0 && scroll <= 120){
console.log("show popup "+scroll);
$(".tso_pop-container").css({"width":"1366px","height":"700px","overflow":"auto","right":"-296px","top":"106px"});
}
//$.cookie("dontShowUrgencyContainer","yes");
}
});
addEvent(document, "mouseover", function() {
$(".tso_pop-container").css({"width":"0px","height":"0px","overflow":"hidden","right":"50%","top":"50%"});
});
});
//}
window.onblur = function(event) {
$(".tso_pop-container").css({"width":"0px","height":"0px","overflow":"hidden","right":"50%","top":"50%"});
}
first to get scrolled position of document use :
$('body').scrollTop() // webkit
$('html').scrollTop() // moz
for browser hover use :
$(window).mouseenter(function(){
var stop = $('html').scrollTop() == 0 ? $('body').scrollTop() : $('html').scrollTop()
if(stop <= 120){
// your code
}
});
hope this helps you.

Trying to debug a custom .sort in a JS array

A link to the Plunker.
I've been working on a button and list system in jQuery for awhile now. Recently I decided to make my code more reproducible. I want to make it so I just have to add classes or IDs, and I don't have to add any additional code. I'm very close to doing that for my entire site. So if you go to this site specifically you will see it in action.
If you click on any buttons, in any order, it will arrange chronologically.
The bugs come from closing them.
If you click at least three, close the middle one, then click a new button, the sort function falls apart and that closed middle one is now floating with the wrong class.
Below is my current jQuery. On my site, ignore the "All Years" button. I'll work on that after I figure out this bug.
//the variables needed for the floating buttons
var groupArray = $(".yearGroup");
var buttonArray = $(".buttonGroup");
var hideGroupArray = $(".hideGroup");
var closeBarArray = $(".closeBar");
var closeBar = $("#allCloseBar");
var allButtonArray = [];
sortElements = function(a,b)
{
if (a.text() < b.text())
{
return -1;
}
else if (a.text() > b.text())
{
return 1;
}
else
{
return 0;
}
}
$.each(buttonArray, function(i, item) {
$(this).click(function(){
console.log($(buttonArray[i]).text())
console.log($(closeBarArray[i]).text())
//for removing the tooltip when the button is clicked. Mostly for Firefox bug
$(".ui-tooltip-content").parents('div').remove();
$(hideGroupArray[i-1]).slideToggle(slideToggleDuration, function(){
htmlBody.animate({scrollTop: $(groupArray[i-1]).offset().top - 25}, {duration: timeDuration, easing: 'easeOutBack'});
$(buttonArray[i]).toggleClass("float", 1200);
if ($(groupArray[i-1]).height() > 0)
{
//This will stop any animations if the user scrolls.
htmlBody.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e)
{
if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
htmlBody.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
}
});
closeBar.addClass("floatCloseBar");
$(closeBarArray[i]).hide();
allButtonArray.splice(0, 0, $(buttonArray[i]));
var timer;
var delay = 1500;
$(buttonArray[i]).hover(function() {
//This will stop any animations if the user scrolls.
htmlBody.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e)
{
if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
htmlBody.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
}
});
var link = $(groupArray[i-1]);
var offset = link.offset();
var top2 = offset.top;
var left = offset.left;
var bottom = top2 + $(groupArray[i-1]).outerHeight();
//bottom = Math.abs(bottom - offset.top);
var right = $(window).width() - link.width();
right = Math.abs(offset.left - right);
var scrollDuration = 0;
if (inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
//console.log("fast");
scrollDuration = 500;
//$(group).addClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top <= $(groupArray[i-1]).offset().top && allButtonArray.length == 1)
{
//console.log("fast");
scrollDuration = 500;
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 495 && $(buttonArray[i]).offset().top < 1700 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 1000;
//console.log("slow");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 1701 && $(buttonArray[i]).offset().top < 3000 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 1500;
//console.log("slower");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 3001 && $(buttonArray[i]).offset().top < 6000 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 2000;
//console.log("much slower");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 6001 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 2500;
console.log("the slowest");
//$(group).removeClass("hoverYear");
}
else
{
scrollDuration = 500;
}
//to prevent the various hover states to take control when the button isn't floating
if (!($(buttonArray[i])).hasClass("float"))
{
scrollDuration = 0;
console.log("doesnt have class")
}
// on mouse in, start a timeout
timer = setTimeout(function() {
//the delay for the hover scroll feature
htmlBody.animate({scrollTop: $(groupArray[i-1]).offset().top}, scrollDuration, 'easeInOutCubic');
}, delay);
}, function() {
// on mouse out, cancel the timer
clearTimeout(timer);
});
$.each(allButtonArray, function(j, val){
$(allButtonArray[j]).appendTo(closeBar);
console.log(allButtonArray.length);
arrowDown.show();
arrowUp.show();
arrowDown.prependTo(closeBar);
arrowUp.appendTo(closeBar);
//Changes the width of the buttons based upon how many are on the screen
if (allButtonArray.length > 7)
{
$("float").css('width', '7%');
$(val).css('width', '7%');
$(allButtonArray[0]).css('width','7%');
allButtonArray.sort(sortElements);
//console.log(val);
}
else if (allButtonArray.length <= 7)
{
$(val).css("width", '10%');
$("float").css("width", '10%');
allButtonArray.sort(sortElements);
//console.log(val);
}
});
}
if ($(groupArray[i-1]).height() == 0)
{
$(buttonArray[i]).css("width", '50%');
allButtonArray.splice(allButtonArray.indexOf($(buttonArray[i])), 1);
console.log(allButtonArray.length);
$(closeBarArray[i]).show();
$(buttonArray[i]).appendTo($(closeBarArray[i]));
arrowDown.show();
arrowUp.show();
arrowDown.prependTo(closeBar);
arrowUp.appendTo(closeBar);
}
if (group2001.height() == 0 && group2002.height() == 0 && group2003.height() == 0 && group2004.height() == 0 && group2005.height() == 0 && group2006.height() == 0 && group2007.height() == 0
&& group2008.height() == 0 && group2009.height() == 0 && group2010.height() == 0 && group2011.height() == 0 && group2012.height() == 0)
{
$(closeBarArray[i]).removeClass("floatCloseBar");
htmlBody.animate({scrollTop: revealAllButton.offset().top - 75}, 500);
arrowDown.hide();
arrowUp.hide();
//console.log($(document).height() + " the current height");
}
});
$(buttonArray[i]).toggleClass("openClose");
$(buttonArray[i]).toggleClass("openClose2");
});
});
function inRange(x, min, max){
return (x >= min && x <= max);
}
If you would like a reference to what worked previously, I could post that code. It is much more bulky and much less organized. I've tried many different things to eliminate the bug but I'm at a loss. My knowledge of JS scope is limited.
And thanks for any help, it is very much appreciated.

How to get a MouseWheel Event to fire only once in jQuery?

So I want to fire a function only once every time a user scrolls up or down via the Mousewheel. See: jsFiddle Demo. The issue is that even though I have the e.preventDefault(), the function still fires multiple times.
The goal is for the function to fire only once whenever a user scrolls up or down. Similar to this site.
Here is the code that I have so far:
var sq = {};
sq = document;
if (sq.addEventListener) {
sq.addEventListener("mousewheel", MouseWheelHandler(), false);
sq.addEventListener("DOMMouseScroll", MouseWheelHandler(), false);
} else {
sq.attachEvent("onmousewheel", MouseWheelHandler());
}
function MouseWheelHandler() {
return function (e) {
var e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
if (delta < 0) {
/* Scroll Down */
e.preventDefault();
console.log("Down. I want this to happen only once");
} else {
/* Scroll Up */
console.log("up. I want this to happen only once");
e.preventDefault();
}
return false;
}
return false;
}
This has helped me:
var isMoving=false;
$(document).bind("mousewheel DOMMouseScroll MozMousePixelScroll", function(event, delta) {
event.preventDefault();
if (isMoving) return;
navigateTo();
});
function navigateTo(){
isMoving = true;
setTimeout(function() {
isMoving=false;
},2000);
}
Basically you have a isMoving variable that is set depending on if your animation or whatever you do is in progress. Even though user scrolls multiple times with mousewheel in one "flick", the function fires only once.
​$(document).ready(function(){
var up=false;
var down=false;
$('#foo').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta /120 > 0 && up=false) {
up=true;
down=false;
$(this).text('scrolling up !');
}
elseif(e.originalEvent.wheelDelta /120 > 0 && down=false){
down=true;
up=false;
$(this).text('scrolling down !');
}
});
});
And here is a plug in you can use it

Autoscroll was but now isn't working

I was working on a project that, when you click the page, it scrolls the entire length of the page. But it does this at 20px intervals; this is to allow javascript to be executed while scrolling in iOS.
However, when uploading the final version, my ftp client has deleted some of the code and it's now not working. I can't see why.
Any suggestions?
var t;
var scrolling = false;
// doScroll sets the position in which to auto pause.
function doScroll() {
$('body').scrollTop($('body').scrollTop() + 20);
if($("#pause").offset().top >=300 && $("#pause").offset().top < 304){
ScrollIt();
} else
if($("#pause").offset().top >=4000 && $("#pause").offset().top < 4004){
ScrollIt() ;
} else
if($("#pause").offset().top >=7500 && $("#pause").offset().top < 7504){
ScrollIt() ;
}
}
// ScrollIt removes the interval for scrolling, pausing the scroll.
function ScrollIt() {
clearInterval(t);
scrolling = false;
return;
// playPause()
}
//Stop/start on click
$('#pause').on('click',function(){
ScrollIt();
scrolling = !scrolling;
if(!scrolling){
clearInterval(t);
return;
}
t = setInterval(doScroll, 5);
});
I create jsfiddle page for you.
http://jsfiddle.net/u32Nw/2/
I can see that it is working, but scrolling is not stopping.
var t;
var scrolling = false;
// doScroll sets the position in which to auto pause.
function doScroll() {
var $body = $("body"),
$pause = $("#pause");
$body.scrollTop($body.scrollTop() + 20);
var pauseTop = $pause.offset().top;
if (pauseTop >= 300 && pauseTop < 304 || pauseTop >= 4000 && pauseTop < 4004 || pauseTop >= 7500 && pauseTop < 7504) {
clearScrollInterval();
}
}
// scrollIt removes the interval for scrolling, pausing the scroll.
function clearScrollInterval() {
clearInterval(t);
scrolling = false;
return;
// playPause()
}
//Stop/start on click
$("#pause").on("click", function () {
clearScrollInterval();
scrolling = !scrolling;
t = setInterval(doScroll, 5);
});
This is exact same code, just refactored.
Try working from here. You need to refactor your code for debugging.

Treating each div as a "page" when scrolling

I have a page that I'm building and I would like to make it that when I scroll (up or down) the page scrolls to the next div (each div is 100% the height of the window). And gets "fixed" there until you scroll again. An example of what I'm trying to accomplish can be seen here:
http://testdays.hondamoto.ch/
You will notice that when you scroll down, it automatically moves you to the next "div".
What I've tried:
Using the jQuery .scroll event combined with:
function updatePosition() {
if(canScroll) {
var pageName;
canScroll = false;
var st = $(window).scrollTop();
if (st > lastScrollTop){
// downscroll code
if(pageNumber < 7) {
pageNumber++;
}
pageName = '#' + getPageToScrollTo().id;
$('body').animate({ scrollTop: $(pageName).offset().top }, 2000, function() {
canScroll = true;
});
} else {
// upscroll code
if(pageNumber > 0) {
pageNumber--;
}
pageName = '#' + getPageToScrollTo().id;
$('body').animate({ scrollTop: $(pageName).offset().top }, 2000, function() {
canScroll = true;
});
}
lastScrollTop = st;
}
}
But the scroll event was getting called when the page was scrolling (animating), AND when the user scrolled. I only need it to be called when the user scrolls.
Then I added:
var throttled = _.throttle(updatePosition, 3000);
$(document).scroll(throttled);
From the Underscore.js library - but it still did the same.
Finally, I browsed here a bit and found:
Call Scroll only when user scrolls, not when animate()
But I was unable to implement that solution. Is there anyone that knows of any libraries or methods to get this working?
EDIT:
Solution based on Basic's answer:
function nextPage() {
canScroll = false;
if(pageNumber < 7) {
pageNumber++;
}
pageName = getPageToScrollTo();
$('html, body').stop().animate({ scrollTop: $(pageName).offset().top }, 1000, function() {
canScroll = true;
});
}
function prevPage() {
canScroll = false;
if(pageNumber > 0) {
pageNumber--;
}
pageName = getPageToScrollTo();
$('html, body').stop().animate({ scrollTop: $(pageName).offset().top }, 1000, function() {
canScroll = true;
});
}
//--Bind mouseWheel
$(window).on(mousewheelevt, function(event) {
event.preventDefault();
if(canScroll){
if(mousewheelevt == "mousewheel") {
if (event.originalEvent.wheelDelta >= 0) {
prevPage();
} else {
nextPage();
}
} else if(mousewheelevt == "DOMMouseScroll") {
if (event.originalEvent.detail >= 0) {
nextPage();
} else {
prevPage();
}
}
}
});
Ok...
The relevant code for the Honda site can be found in http://testdays.hondamoto.ch/js/script_2.js. It seems to be doing some calculations to locate the top of the div then scroll to it. There are handlers for different types of scrolling.
Specifically, the movement is handled by function navigation(target)
the key bits is here...
$('html,body').stop().animate({
scrollTop: $(target).offset().top + newMargin
}, 1000,'easeInOutExpo',function(){
//Lots of "page"-specific stuff
}
});
There are handlers for the scroll types...
$('body').bind('touchstart', function(event) {
//if(currentNav!=3){
// jQuery clones events, but only with a limited number of properties for perf reasons. Need the original event to get 'touches'
var e = event.originalEvent;
scrollStartPos = e.touches[0].pageY;
//}
});
//--Bind mouseWheel
$('*').bind('mousewheel', function(event, delta) {
event.preventDefault();
//trace('class : '+$(this).attr('class') + ' id : '+$(this).attr('id'));
if(!busy && !lockScrollModel && !lockScrollMap){
if(delta<0){
nextPage();
}else{
prevPage();
}
}
});
You'll note that the navigate() function sets a busy flag which is unset when scrolling completes - which is how it suppresses all new scroll events during a scroll. Try changing the direction of scroll while the page is already scrolling and you'll notice user input is being ignored too.

Categories