Force scroll to top updated - javascript

I am trying to force my page to load always on the top. I don't know if I have to define on-refresh or on-load but I've tried everything. I've searched all the previous questions and non of them seemed to work for me. I checked in Chrome and Mozilla. So do you have any suggestions? What should I do?
I tried the following:
1.
$(document).ready(function(){
$(window).scrollTop(0);
});
2.
jQuery('html,body').animate({scrollTop:0},0);
3.
$(window).on('beforeunload', function(){
$(window).scrollTop(0);
});
4.
$(document).ready(function() {
if (window.location.hash) {
//bind to scroll function
$(document).scroll( function() {
var hash = window.location.hash
var hashName = hash.substring(1, hash.length);
var element;
//if element has this id then scroll to it
if ($(hash).length != 0) {
element = $(hash);
}
//catch cases of links that use anchor name
else if ($('a[name="' + hashName + '"]').length != 0)
{
//just use the first one in case there are multiples
element = $('a[name="' + hashName + '"]:first');
}
//if we have a target then go to it
if (element != undefined) {
window.scrollTo(0, element.position().top);
}
//unbind the scroll event
$(document).unbind("scroll");
});
}
});
5.
$('a').on('click', function(e) {
e.preventDefault();
// do your js stuff
$(window).scrollTop(0);
});
6.
$("html, body").animate({
scrollTop: 0
}, 600);

use animate function
$("html, body").animate({
scrollTop: 0
}, 600);

Related

Calling the function only once in a time

I have such a function on my website:
$("#search-label").on("keypress", function(e) {
if(e.which == 13) {
$('html, body').animate({
scrollTop: $("#content").offset().top
}, 2000);
}
});
Its task is to scroll to the selected element after press enter and it works fine, but the problem is that it can be called repeatedly in a short time and then the page gets stuck.
How to limit the possibility of calling it up to once every 10 seconds?
Thanks
You can use a mix of a variable and a setTimeout to do this:
var scrollOK = true;
$("#search-label").on("keypress", function(e) {
if((e.which == 13) && scrollOK) {
$('html, body').animate({
scrollTop: $("#content").offset().top
}, 2000);
scrollOK = false;
setTimeout(function(){ scrollOK=true; }, 10000);
}
});
It uses scrollOK to make sure that scrolling is OK, and when it scrolls, then it sets it to false temporarily (temporarily because the setTimeout sets it back to true after 10 seconds, or 10000 milliseconds).
Edit: as #ChloeAnderson said, this may take up more resources than it should. This is a version that should be better:
var lastScrolled = 0;
$("#search-label").on("keypress", function(e) {
if((e.which == 13) && (Date.now() >= (lastScrolled + 10000))) {
$('html, body').animate({
scrollTop: $("#content").offset().top
}, 2000);
lastScrolled = Date.now();
}
});

WordPress Divi Theme - Anchor Link Opens Specific Tab Toggle

I am trying to get anchor links to open up tabs on a specific page.
Solutions like the one found on https://jonathanbossenger.com/using-anchor-links-to-open-accordions-and-tabs-in-divi/ only work when the anchor link is on the same page as the tabs.
I found a different thread on Stack that addressed this issue, but it had the finalized solution ironed out in a chat I don't have access to (Wordpress Divi Theme - Anchor link opens tab toggle).
I can see on their website that they were able to get it to work (https://www.elkodowntown.org/our-members/#member-tabs|3).
How can I access the site code of Elko Downtown to find the final version of the JavaScript below that got it to work?
jQuery(function($) {
$('.menu-item-179 a').on('click', function(event){
tabScroll('.et_pb_tab_0');
return false;
});
$('.menu-item-180 a').on('click', function(event){
tabScroll('.et_pb_tab_1');
return false;
});
$('.menu-item-181 a').on('click', function(event){
tabScroll('.et_pb_tab_2');
return false;
});
$('.menu-item-182 a').on('click', function(event){
tabScroll('.et_pb_tab_3');
return false;
});
$('.menu-item-183 a').on('click', function(event){
tabScroll('.et_pb_tab_4');
return false;
});
function tabscroll(target) {
$("html, body").animate({ scrollTop: $('#member-tabs').offset().top }, 1000);
setTimeout($('#member-tabs' + target + ' a').click(), 2000 );
}
$(function hash() {
var hash = window.location.hash.replace('#', "");
if (hash == '#shop') { tabscroll('.et_pb_tab_1'); }
if (hash == '#service') { tabscroll('.et_pb_tab_0'); }
if (hash == '#eat-drink') { tabscroll('.et_pb_tab_2'); }
if (hash == '#arts-entertainment') { tabscroll('.et_pb_tab_3'); }
if (hash == '#stay') { tabscroll('.et_pb_tab_4'); }
});
});
Every line of javascript transmitted over the web is visible by inspecting the browser. If all you're looking to do is see what they're finalized code is look below.
However, if you're using WP and trying to do things using JS/JQuery I strongly urge you to learn how to do the functions outside of WP first and understand what's going on, the code you take from will not always match your page structure/elements and you'll always wonder why things don't work.
Here's the code that's doing it for them:
function _setTab(){
// get current hash value
var curHash = window.location.hash.substr(1);
// only continue if hash provided and scoped to member tabs
if( !curHash || !curHash.match('member-tabs') ){ return false; }
// split and int val tab num
curHash = parseInt(curHash.split('|')[1]);
// ignore if tab is current state
if( curHash === window._tabSelected ){ return false; }
// set current tab to window
window._tabSelected = curHash;
// add click event to tab selected
switch(curHash){
case 0:
case 1:
case 2:
case 3:
case 4:
jQuery('#member-tabs .et_pb_tab_'+curHash+' a').click();
break;
default:
return false;
break;
}
// scroll to tabs container
_scrollToTabs();
}
// scroll to member tabs container with 50px offset
function _scrollToTabs(){
var oTabs = jQuery('#member-tabs');
if( oTabs.length > 0 ){
jQuery('html,body').animate({
scrollTop: (oTabs.offset().top - 50)
}, 1000);
}
return false;
}
// set falsey state for tab selected on load
window._tabSelected = false;
// we need to attach to window load because the tabs functions are initialized later in document
jQuery(window).on('load', function(){
// check for initial hash state
_setTab();
// add hash change window listener
jQuery(window).on('hashchange', function(){
_setTab()
});
// void submenu when we are in member section
var curPath = window.location.pathname;
if( curPath.match('our-members') ){
// only change hash and do not reload page
jQuery('#menu-item-98 ul li a').on('click', function(e){
e.stopImmediatePropagation();
window.location.hash = jQuery(this).prop('hash');
return false;
});
}
});

Jumpy scroll after scroll-animation with javascript

I have a problem with the scrolling animation. Jumpy scroll occurs when the page is scrolled after scroll-animation. I suspected the scroll-event repeats itself, but I'm not sure. Can you help me with it?
$(document).ready(function(){
var offset;
var anchor = $("#navigation").offset().top;
$(window).bind('mousewheel', function (e) {
offset = $(window).scrollTop();
if (e.originalEvent.wheelDelta < 0) {
//mouse scroll down
console.log('Down: ' + offset + " " + anchor);
if (offset >= anchor) {
// if anchor has been scrolled, user can scroll further
// the problem ocuurs in this block
return true;
} else {
// animate to anchor( nav menu)
$("body, html").animate({
scrollTop: anchor + 1
}, 200);
$("#navigation").addClass("nav-fixed");
return false;
}
} else {
//mouse scroll up
if (offset < anchor) {
$("#navigation").removeClass("nav-fixed");
return true;
}
}});
});
JSFiddle: http://jsfiddle.net/0noms3cs/
Thank you a lot!
Your issue is simple. The scroll event fires over and over again. Your line of thinking behind the cause of this issue is correct, you have a large number of animate events that get stacked up which causes this weird behavior.
You can resolve this issue by adding a boolean variable (such as scrollInitialized) that starts out as false and gets flipped to true once the scroll event has fired once.
Here's the altered JS code. Note: I only added the scrollInitialized variable and a check for it in the if statement.
Edit: I also removed the inner if-else case since it was not necessary using this design.
EDIT 2: I originally misunderstood what you wanted to do. What you need to do was add a scrollLock variable that would only be set to true for the duration of your animation. After thinking about this, I implemented it for you. Here is the Jsfiddle:
https://jsfiddle.net/04gaaapo/1/
Here is the new JS code:
$(document).ready(function () {
var scrollLock = false;
var offset;
var anchor = $("#navigation").offset().top;
$(window).bind('mousewheel', function (e) {
offset = $(window).scrollTop();
// if scroll is NOT locked and we are above the anchor
if (scrollLock === false && offset < anchor) {
if (e.originalEvent.wheelDelta < 0) {
// scrolling down
scrollLock = true;
// animate to anchor( nav menu)
$("body, html").animate({
scrollTop: anchor + 1
}, 200);
// unlock in 250ms
setTimeout(toggleLock, 250);
// add nav class
$("#navigation").addClass("nav-fixed");
} else if (e.originalEvent.wheelDelta > 0) {
// scrolling up
scrollLock = true;
// animate to top of page
$("body, html").animate({
scrollTop: 0
}, 200);
// unlock in 250ms
setTimeout(toggleLock, 250);
// remove nav class
$("#navigation").removeClass("nav-fixed");
}
}
});
function toggleLock() {
scrollLock = !scrollLock;
};
});

Conflicting "back to top" scripts - how to fix?

I'm using 2 scripts found on the internet, one for a smooth scroll to a DIV at the bottom of the page, and one for a smooth scroll "Back to top". The issue is that there's a conflict between both and therefore the "back to top" one doesn't work (no back to top on click). Used independently they both work perfectly.
How could I "merge" them both into one single script? (and keep the fade-in fade-out effect of the back to top script) See http://jsfiddle.net/GjsVq/1/
Many thanks
$(document).ready(function() {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
$(document).ready(function() {
var offset = 220;
var duration = 500;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > offset) {
jQuery('.back-to-top').fadeIn(duration);
} else {
jQuery('.back-to-top').fadeOut(duration);
}
});
jQuery('.back-to-top').click(function(event) {
event.preventDefault();
jQuery('html, body').animate({scrollTop: 0}, duration);
return false;
})
});
$('a[href^="#"]').on(... is selecting both <a> elements. One approach is to either rewrite this selector to match only the <a> elements that should force a scroll to the bottom (maybe use a CSS class for this?)
An alternative, quick-and-dirty fix would be to reset the event handlers on the "back-to-top" element before attaching its own click handler: jQuery('.back-to-top').off().click(...
I normally just use one smooth scroll function and then set my "go to top" button with a href="#idOfHighestElementOnPage". This is the smooth scroll function (which may include something helpful if you don't want to go the same route I went):
$(function () {
$('a[href*=#]:not([href=#])').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 100
}, 'normal');
return false;
}
}
});
})
window.onscroll = scrollFunction;
function scrollFunction() {
var doc = document.documentElement, body = document.body;
var top = (doc && doc.scrollTop || body && body.scrollTop || 0);
if (top > 200) {
$('.back-to-top').fadeIn();
}
else {
$('.back-to-top').fadeOut();
}
}

Sticky scroll with active class on navigation items

I currently have a sticky scroll navigation that changes the active class as it passes each section on the page. It is a little buggy though...
heres my jquery code:
var s = $("#page-nav"),
pos = s.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
if (windowpos >= pos.top) {
s.addClass("stick");
$('.main').css('margin-top', '60px');
} else {
s.removeClass("stick");
$('.main').removeAttr('style');
}
});
$(window).scroll(function() {
var y = $(this).scrollTop();
$('.linky').each(function (event) {
id = $(this).attr('href');
if (y >= $(id).offset().top) {
$('.linky').not(this).removeClass('active');
$(this).addClass('active');
}
});
});
//page nav
$("#page-nav li a").click(function(e) {
e.preventDefault();
$("#page-nav li a").removeClass('active');
$(this).addClass('active');
goToByScroll($(this).attr("href").replace("#", ""));
});
function goToByScroll(id){
$('html,body').animate({
scrollTop: $("#"+id).offset().top},
'slow');
}
And here is a working example over at codepen
How can I improve my javascript so that is performs a little smoother. As you can see when you click a link it still thinks it is within that section and the active class flickers.
Your problem was that you were setting the active class when you click an link and also when you move. What I did was to remove the class handling from the click event handler and let the scroll handler take care of everything. This way, there is no flicker. Here you have an updated CodePen.
$("#page-nav li a").click(function(e) {
e.preventDefault();
goToByScroll($(this).attr("href").replace("#", ""));
});
If this solution is not good enough for you, tell me and I'll think something more sophisticated.
New working solution here.
Basically, I created a variable that indicates whether you have clicked a link or not. If you have, then the scroll handler won't change CSS classes (avoiding the flicker). Then, in the complete handler of your animate function, I set it to false again (allowing for class changes as you scroll):
var s = $("#page-nav"),
pos = s.position(),
linkClicked = false;
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
if (windowpos >= pos.top) {
s.addClass("stick");
$('.main').css('margin-top', '60px');
} else {
s.removeClass("stick");
$('.main').removeAttr('style');
}
});
$(window).scroll(function() {
var y = $(this).scrollTop();
$('.linky').each(function (event) {
id = $(this).attr('href');
if (y >= $(id).offset().top) {
if (!linkClicked) {
$('.linky').not(this).removeClass('active');
$(this).addClass('active');
}
}
});
});
//page nav
$("#page-nav li a").click(function(e) {
e.preventDefault();
$("#page-nav li a").removeClass('active');
$(this).addClass('active');
linkClicked = true;
goToByScroll($(this).attr("href").replace("#", ""));
});
function goToByScroll(id){
$('html,body').animate({
scrollTop: $("#"+id).offset().top},
'slow', function() {
linkClicked = false;
});
}

Categories

Resources