Reputation: 17
I am developing a webpage where I use arrow button with two functions - to scroll to top and to attract attention of the visitors.
There are two states of the button:
↑ - Go to the top using onclick event $('html, body').animate({scrollTop: 0}, 'fast')
which is activated when user scrolled.
↓ - Attention attractor (default state on page load) - Does bouncing animation when $(window).scrollTop() == 0
and user didn't scroll yet.
But when I reload mid-page, all the behavior goes wrong and the arrow button reacts in weird way to all events. I have tried numerous approaches to the problem but didn't find any functional solution.
Simplified code I have: http://jsfiddle.net/rbusa/2m6RL/
Would you mind telling me what did I do wrong and eventually tell me how to fix this annoyance? Sorry for all the mess in the code, I am JS beginner.
Upvotes: 0
Views: 147
Reputation: 142
welcome to javascript. a few things.. as noted, the page is maintaining it's position when reloaded, so some functions are getting initialized. also, you should get into the habit of keeping your js and css in the proper files for easier maintenance and debugging. i've refactored your code a bit and think i have it working as you expect now. the main fixes were scrolling the page back to the top as mentioned above, and removing rotate classes on the arrow in the head like this:
$(window).scrollTop(0);
$('#arrow').removeClass('rotateup rotatedwn');
also, since it does the scrolltop function on load, i added the timeout for window.scroll to the bottom of the resetArrow function so that both wouldn't be called on init, which was causing confusion of states.
fiddle here - http://jsfiddle.net/ackerman/yqbVu/
Upvotes: 0
Reputation: 152
I think that the problem is when you reload the browser is stuck to old scroll position. Tray adding this
$(window).on('beforeunload', function(){
$(window).scrollTop(0);
});
Upvotes: 1