jQuery auto scroll to ID from different page - javascript

I have seen this problem on stackoverflow but the code that was used in there was different and I didn't really understood it. So I want to make website scroll to div when website is coming from another page.
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top -70
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
This code works in homepage, scrolls smooth, but it does not work when it's clicked from another page.

This will scroll the body to the #someDiv top offset when page is loaded:
$(document).ready(function(){
$('html, body').animate({
scrollTop: $('#someDiv').offset().top - 70
}, 800);
});
and this if the referrer is not http://www.example.com:
$(document).ready(function(){
if (document.referrer !== "http://www.example.com") {
$('html, body').animate({
scrollTop: $('#someDiv').offset().top - 70
}, 800);
}
});
and this when comes from other page:
$(document).ready(function(){
if(document.referrer != '' && document.referrer != location.href ){
$('html, body').animate({
scrollTop: $('#someDiv').offset().top - 70
}, 800);
}
});

Related

smooth scrolling for all links and buttons on a page

The first 26 lines give me smooth scrolling for all links in my navbar and my logo, but I don't know how to combine it with the scroll up button that I've got from another tutorial. Is there a way to make all links scroll in the first piece of code and not only elements in the navbar?
$(document).ready(function(){
// Add scrollspy to <body>
$('body').scrollspy({target: ".navbar", offset: 50});
// Add smooth scrolling on all links inside the navbar
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
jQuery(window).scroll(function(){
if (jQuery(this).scrollTop() > 300) {
jQuery('.scrollToTop').fadeIn();
} else {
jQuery('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
jQuery('.scrollToTop').click(function(){
jQuery('html, body').animate({scrollTop : 0},800);
return false;
});
You need to separate click event for navigation bar link and your scrollToTop link, and register scrollToTop link to a click event as well. So your code will look like this (assuming you add a class 'nav-link' to links at the navbar):
$(document).ready(function(){
// Add scrollspy to <body>
$('body').scrollspy({target: ".navbar", offset: 50});
$('.scrollToTop').on('click',function(event){
event.preventDefault();
$('html, body').animate({scrollTop : 0}, 800);
});
// Add smooth scrolling on all links inside the navbar
$(".nav-link").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
jQuery(window).scroll(function(){
if (jQuery(this).scrollTop() > 300) {
jQuery('.scrollToTop').fadeIn();
} else {
jQuery('.scrollToTop').fadeOut();
}
});

Smooth scrolling function including page change

I'm trying to write a smooth scrolling function that can handle if the href needs to load a new page first then run the scroll.
I have seen a few options where adding /page-template.html#anchor to the href, but with a dynamic site where the homepage url would just be /#anchor.
So the below code isn't seeing the slash as a part of the target href.
const $anchor = $('a')
$anchor.on('click', function(event) {
if (this.hash !== "") {
event.preventDefault()
let hash = this.hash
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash
})
}
})
Kind of worked out a way to achieve this, but it's not tremendously pretty. Any advice on improving it would be appreciated.
// If loading a page with a hash in the URL, scroll to it
if (window.location.hash) {
setTimeout(function() {
$('html, body').scrollTop(0)
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top
}, 1000)
}, 0)
}
// Get the current url path
const currUrl = window.location.pathname
$anchor.on('click', function(e) {
// Get the href and a hash into variables
const href = $(this).attr('href')
const hash = this.hash
// If a hash is present
if (hash) {
// Check if there is a URl path before the hash
if (href.charAt(0) !== '#') {
// Check if this URL path matches the current page's href
if (currUrl == href.split('#')[0]) {
e.preventDefault()
// As they match, just run the scroll within the same page
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash
})
}
// There is no URL accompanying the hash, so it's got to be within the same page
} else {
e.preventDefault()
// Run smooth scrolling within the page
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash
})
}
}
})

Scrolling to ID issue in jquery

I am trying to create smooth scrolling to IDs. When I click on a link its ID should be scroll to top (at a certain point of top. Ex: 200px from top) of the page.
I tried it something like this:
var $root = $('html, body');
$('a[href*=#]').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: (($(href).offset().top >= 200 ) ? $(href).offset().top : 200)
}, 500, function () {
window.location.hash = href;
});
return false;
});
But it doesn't work and its always scrolling to top of the page.
Hope somebody may help me out.
I guess, the problem is your href, the target will presumably not be found. Maybe you'd be better off to store the element to scroll to in a data attribute, like so:
$('a[href*=#]').click(function(evt) {
evt.preventDefault();
var target = $(this).data('target');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 2000);
});
With an anchor tag like so:
Brilliant rainbow colors
Obviously, the element with the ID somewhere_over_the_rainbow must exist somewhere in your DOM.
This should do the job correctly :
$('a[href*=#]').click(function() {
var href = $.attr(this, 'href');
var top = $(href).offset().top;
$('body').animate(
{
scrollTop: top - 200
},
500
);
return false;
});
Obviously, the item with the id equal to the hash of the anchor must exist.

Stop scrolling at a certain point in jquery

I need to create smooth scroll to IDs using jQuery.
Here is my code:
var $root = $('html, body');
$('a[href*=#]').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
return false;
});
Its working fine for me. But one thing, I need to stop scrolling at a certain point of the top of the page. For example 200px from the top.
At this stage its always scrolling to top of the page.
Can anybody tell me how to modify this code?
Thank you.
by adding this:
(($(href).offset().top >= 200 ) ? $(href).offset().top : 200)
It checks how far the element is away from the top, if its more than 200px it will scroll to it else it will scroll to 200px from the top
here is the new code:
var $root = $('html, body');
$('a[href*=#]').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: (($(href).offset().top >= 200 ) ? $(href).offset().top : 200)
}, 500, function () {
window.location.hash = href;
});
return false;
});
If i understood you correctly, you have something like header with height for example 200px and position:fixed to top. And your current script is scrolling too high, hiding hash title under the header.
So if this correct you just need to subtract header height from $(href).offset().top (e.g. scrollTop: $(href).offset().top-200)
jsFiddle
Change this line scrollTop: $(href).offset().top to scrollTop: $("body").offset().top + 200
This will take the really top position (0) and then you can manipulate your scrolling for position you need

Change hash and animate scroll to element

I have a link and an element on the same page:
Click
<div id="#about-us"></div>
And the following javascript:
var scrollto = window.location.hash;
if (window.location.hash != null && window.location.hash != '') {
$('html, body').animate({
scrollTop: $(scrollto).offset().top
}, 500);
}
This should animate a scroll to #about-us element,but it doesn't , it goes straight to element without animation,probably because the hash condition is not met,though there is a hash in url,because the hash is changed after the function.
I need a way to auto scroll to that element with animation,when you click the link . As example,if this page is index.php , and you want to go from another-page.php to index.php , straight to that element, it should load the page,and then scroll to the element,same if you are on index.php but at the top of the page and you click on the link,it should scroll down to the element.
The only problem is when you are on the same page.It doesn't pass the condition,so the animation doesn't work.
UPDATE I've changed the code a little bit.Now the condition is meet,but the animation doesn't work..
$('#link').click(function(e) {
window.location.href='index.php#about-us';
var scrollto = window.location.hash;
if (window.location.hash != null && window.location.hash != '') {
alert(scrollto);
$('html, body').animate({
scrollTop: $(scrollto).offset().top
}, 500);
}
});
This is because window.location.hash is not defined by the time you click on the link and the event handler is called.
Try using:
jQuery(function($) {
$('#link').on('click', function(e) {
e.preventDefault();
var scrollTo = $(this).attr('href'); // retrieve the hash using .attr()
if (scrollTo != null && scrollTo != '') {
$('html, body').animate({
scrollTop: $(scrollTo).offset().top
}, 500);
}
});
});
Also, change your HTML code with:
<div id="about-us"></div> <!-- no need for prepending id value with # -->
See this working JSFiddle
If you want to bind the event on page load, use:
$(document).on('load', function(e) { /* the codez */ });
And retrieve the location hash with var scrollTo = window.location.hash; that will be defined when the page loads.
This code works for me
HTML for same page scroll
Click for About us
<div id="about-us"></div>
HTML for external page link
Click for product introduction
HTML for external page scroll
<div id="introduction"></div>
jQuery
if(window.location.hash){
var getUrlAfterHash = window.location.hash;
if($(getUrlAfterHash).length > 0){
$('html, body').animate({ scrollTop : 0 });
scrollToTop();
}
}
$('.link').on('click', function(e){
e.preventDefault();
var getUrlAfterHash = $(this).attr('href');
scrollToTop();
});
function scrollToTop(){
var idPositionHeight = $(getUrlAfterHash).offset();
$('html, body').animate({ scrollTop : idPositionHeight.top}, 800);
}

Categories