auto scroll: stop jumps back to top of page - javascript

I have a page in which the user clicks one link to start scrolling down the page automatically for ease in reading. There is another link the user clicks to stop the scrolling. The former works perfectly, but the latter makes the page jump back to the top when clicked instead of stopping the scrolling at the that place on the page. Any ideas?
function pageScroll() {
window.scrollBy(0,1); // horizontal and vertical scroll increments
scrolldelay = setTimeout('pageScroll()',50); // scrolls every 100 milliseconds
}
function stopScroll() {
clearTimeout(scrolldelay);
}
I tried to add return false; to the second function from something I read on another post, but it didn't help. I don't fully understand the use of return anyhow. Thanks for any help.

I assume that you're doing something like this:
start
stop
The quickest fix is to return false from the onclick event handlers, like this:
start
stop
The idea is to stop the browser from doing the default action of the event (in this case, going to #, which scrolls to the top of the page). Nowadays, the more modern way is to bind an event handler function, then use e.preventDefault() in it, but return false; still works for old-style event attributes.

Related

Javascript stop scrolling on touchmove after scrolling has already started

I have a simple example where a user starts to scroll on a touch screen, and then after one second, I want to disable scrolling. I thought event.preventDefault() would stop the scrolling but it doesn't seem to work after scrolling has already started
Here is an example: https://jsfiddle.net/7s5m8c6L/30/
let allowScroll=true;
function TS(e){//touchstart handler
setTimeout(function(){
allowScroll=false;
},1000)
}
function TM(e){//touchmove handler
if(!allowScroll){
e.preventDefault();
}
}
In this example, you can start scrolling, and after a second, I want the scrolling to stop, but it does not. I know there are ways that I can get this to work with CSS (adding overflow:hidden), but I would particularly like to know why preventDefault doesn't work.
If you are using chrome, there is a hint in the console:
[Intervention] Ignored attempt to cancel a touchmove event with cancelable=false, for example because scrolling is in progress and cannot be interrupted.
The problem is exactly that Event.cancelable. Unfortunately for you this property is read-only and it is not safe to call preventDefault for a not cancelable event. If you print e.cancelable in the TM function you can observe that throughout the scrolling e.cancelable is false.

javascript how to execute one method after another

I have some animation in my code and I have faced a problem: When the user clicks the button more than once my animation will become faster and faster. To deal with this I have included the refresh page function (location.reload()) inside the function below.
Now I have a major problem: when I execute the button supposed the reload page function will be executed first then follow by day2 function then day1 function... the problem is now only the refresh page function is been executed.
How do I overcome this problem?
Javascript:
function day()
{
location.reload().then(day2).then(day1);
}
HTML:
<input type="button" id="buttonThree" value="Day" onclick="day()"/>
What you're doing doesn't work
Now I have a major problem: when I execute the button supposed the reload page function will be executed first then follow by day2 function then day1 function... the problem is now only the refresh page function is been executed.
Well, yeah. You refreshed the page. That involves leaving the page then re-entering it. Leaving the page means your JavaScript ends everything it's doing, and re-entering it means your JavaScript starts anew. JavaScript does not transcend page loads.
If you want your JavaScript to communicate with JavaScript on other pages, do so via other means: an #anchor in the URI, a query string in the URI, form data, sessionStorage, localStorage, or cookies - those are arranged in order of permanence and appropriateness, with cookies completely overdoing it, and #anchors and query strings being completely appropriate.
But that's completely unnecessary and inappropriate here. You shouldn't be doing what you're doing in the first place.
Let's address the actual problem of multiple button presses
I have some animation in my code and I have faced a problem: When the user clicks the button more than once my animation will become faster and faster.
Simply put, you shouldn't be doing what you're doing and this problem has a much simpler solution: disable the button, or set a boolean flag, in order to prevent the animation from running multiple times. Simply, don't allow the animation to run multiple times.
Option 1: Disabling the button
Disabling the button prevents it from sending onclick events, and signals to your user the button won't do anything for now. I recommend doing this if your button should not do anything longer whilst the animation is running, or whilst something else is happening.
The approach is to disable the button as soon as it's clicked. Later, once the tasks that button fired off (such as the animation) are finished, and it's OK to click the button again, you re-enable the button.
<input type="button" id="animateButton" value="Animate" onclick="animate()"/>
function animate() {
// 'this' refers to the button, when the button's click event
// calls this function
this.disabled = true;
startAnimation();
}
function startAnimation() {
// run the animation
// ...
// once the animation is completed, via whatever means you want
// (such as by jQuery's animate.complete callback),
// re-enable the button like this:
document.getElementById("animateButton").disabled = false;
// or address the button some other appropriate way.
}
Option 2: Boolean flag, leaving the button enabled but doing nothing
This approach involves using a boolean flag to ignore clicks when the animation is running, instead of disabling the button outright.
This lets the user click the button still. It's useful if you want the button enabled for whatever reason, such as if you want the button doing other things on click - just without starting the animation every time.
If it's not going to do anything except start the animation, however, you probably should use option 1 instead to disable it, signalling the button won't do anything for now.
If you want this button to do other things, I suggest you have it call a different function - for example, doStuff() - and have that function call the animate() function below.
<input type="button" id="animateButton" value="Animate" onclick="animate()"/>
var canAnimate = true;
function animate() {
if (!canAnimate) return; // do nothing if we're not allowed to animate yet
canAnimate = false;
startAnimation();
}
function startAnimation() {
// run the animation
// ...
// once the animation is completed, via whatever means you want
// (such as by jQuery's animate.complete callback),
// set the flag to say we can animate again, like this:
canAnimate = true;
}

Triggering Jquery at certain length of page

I'm trying to figure how to trigger an jquery animation when the user scrolls to the middle of the page. Is there a way to set a listener to see if the person scrolls halfway down the page it activates the jquery code?
Using jQuery, you can attach an event handler to the scroll event, which will let you listen to whenever the window is scrolled and determine whether the user has scrolled the appropriate amount.
$(window).scroll(function () {
if (($(window).scrollTop()) > ($(document).height() / 2)) {
// Run animation here
}
});
http://jsfiddle.net/ult_combo/XdqPJ/1/
Think so.. you can look at checking parts of the page using;
setInterval(name_Of_Function,1000);
runs every second, then run a check on there is;
window.pageYOffset // Gives you current horizontal window scroll position for the page.
Firebug is helpful to get more information on these functions. Remember to check in all major browsers as the implementation or values returned may be slightly different between different browsers.
Good reference page I found;
http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
Is there a way to set a listener to see if the person scrolls halfway
down the page it activates the jquery code?
You can get the amount that the user has scrolled with the following:
$("html,body").scrollTop();
so, to trigger an event halfway down the page:
if (($("html,body").scrollTop()) > ($("html,body").height() / 2))
{
// Code that will be triggered
}
You would need a timer to constantly be checking this. You can use setInterval() in Javascript to repeatedly execute a function to check this.
http://api.jquery.com/scrollTop/

Cross-browser method to capture scroll events (or an easier way to temporarily disable scrolling)

I'm trying to execute a Javascript function whenever a user scrolls a page.
I've tried:
<body onscroll="myScrollFunction()">
and this works fine in Firefox but not IE.
I also tried:
window.onscroll = "myScrollFunction()";
but this seems to only perform the function once, similar to an onload event, but further scrolls do not fire the event. My doctype is set to strict; not sure if this makes a difference or not.
How can I get this to work across all browsers?
What I'm trying to accomplish is a way to prevent users from scrolling once a modal is displayed. I'd rather not use
overflow:hidden
because the document shifts slightly when the modal is displayed (to compensate for the scrollbar), so I figured I could capture the scroll function and lock it to the top of the page whenever the modal is displayed. If there is an easier way to do this, please let me know.
Instead of
window.onscroll = myScrollFunction();
which assigns the result of the myScrollFunction() to the onscroll handler, you want
window.onscroll = myScrollFunction;
which assigns the function itself, and will therefore be called on each scroll.
I suggest that instead of doing that, you just give your modal dialog position: fixed; which will fix it to the viewport instead of the page.
Set the <body>'s overflow to hidden while your lightbox is open.
$('body').css('overflow','hidden');
...then return to normal when it closes:
$('body').css('overflow','auto');

How do I prevent auto-scrolling to the top in jQuery?

This works in all other browsers and I have no idea what the problem is. I'm kind of in a hurry so I thought I'd ask you guys in case I missed anything obvious. I have a link you click on which initiate a popup, and in Firefox (and possibly opera) the page auto scrolls back to the top.
$('[class*=popup-link]').click(function(e) {
/* Prevent default actions */
e.preventDefault();
e.stopPropagation();
/* Get the id (the number appended to the end of the classes) */
var name = $(this).attr('class');
var id = name[name.length - 1];
/* Show the correct popup box, show the blackout and disable scrolling */
$('#popup-box-'+id).show();
$('#blackout').show();
$("html,body").css("overflow","hidden");
});
I need both preventDefault and stopPropagation to stop some other stuff happening. Can you see any errors or a way to stop this auto scrolling to the top? Thanks!
Quick Edit:
I'm also running a function which centers the box using
$(window).scroll(centerBox);
I'm unsure if this would affect scrolling in some odd way in firefox. The contents of this function are just adding CSS, so I doubt they would have any effect on it.
Another Edit:
A link to try it out. Not working in Firefox for me.
http://inserthtml.com/demo/internal-popup/
first, i see nothing wrong in the script. it should be preventing the "top jump" even only with e.preventDefault(). try stripping it down to this. it should tell if this handler is causing it or not
$('[class*=popup-link]').click(function(e) {
e.preventDefault(); //prevent the click from jumping esp on hashes
e.stopPropagation(); //prevent from any parent click handlers that didn't prevent the jump
//no code here for now
return false; //the natural way to prevent the jump
});
if this code prevents the jump, then there is something in the rest of your code that causes it especially broken scripts. check the console for errors also
e.preventDefault();
e.stopPropagation();
is equivalent to
return false;
Change them, and you will be fine

Categories

Resources