When I apply this script, it goes to the link but I want it to go 120px above the content it is linked to.
Here is the code:
<script>
$(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 !== 0) {
// 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
});
});
</script>
EDIT #02
Here is my HTML, CSS and Java for those who are wondering:
https://codepen.io/crosso_7/pen/WYegpY
Simply subtract the amount of pixels from your calculation.
$(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 !== 0) {
// 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 -120
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
the problem is window.location.hash = hash; after animate it do second action which is same with default action. Replace it with history.pushState(null, null, hash); to rewrite the url history and add hash
$('html, body').animate({
scrollTop: $(hash).offset().top - 120
}, 800, function() {
// Add hash (#) to URL when done scrolling (default click behavior)
//window.location.hash = hash;
history.pushState(null, null, hash);
});
Related
I have a website where sections have # and menu items should scroll to them. Due to setup of website it's required that my URL have / (slash) at the end.
For example website.com/about/
So anchor would be website.com/about/#team/
When there's / at the end of URL, scroll to anchor doesn't work. I don't have any jQuery on website so simple jump to section doesn't work either. When I remove / it works.
Is there jQuery which I can use for that purpose? I tried bunch of jQuery but without success.
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
});
});
});
As you said you cant change hash pattern then you have to do reverse process: remove dash from this.hash before putting $(hash).offset() method
$(document).ready(function(){
$('a').click(function(event) {
// Store hash
event.preventDefault();
var hashWithoutDash = this.hash.replace("/",""); // remove dash from hash to make $(hashWithoutDash).offset() worked
$('html, body').animate({
scrollTop: $(hashWithoutDash).offset().top
}, 1000, function() {
window.location.hash = this.hash; // keep actual hash with dash
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<p id="team">This is a paragraph.</p>
<div style ="height:1000px"> please scroll down to see href link </div>
team
<button>Return the offset coordinates of the p element</button>
I am trying to add a smooth scroll down functionality to my website so when a user click an anchor tag from another page it links/sends the user to another page and scroll down to a specify div. The code performs correctly however /#NaN appears at the end of the url.
My jQuery:
jQuery(document).ready(function () {
// run on DOM ready
// grab target from URL hash (i.e. www.example.com/page-a.html#target-name)
var target = window.location.hash;
// only try to scroll to offset if target has been set in location hash
if (target != '') {
$('.introsection').hide(0);
$('#swipe-down').hide(0);
$('body').css('overflowY', 'scroll');
$('#home-mobile-nav').css('position', 'fixed');
$('#home').css('margin-top', '0');
var $target = jQuery(target);
jQuery('html, body').stop().animate({
'scrollTop': $target.offset().top - 150
}, // set offset value here i.e. 50
2000,
'swing',
function () {
window.location.hash = target - 40;
});
}
});
In the console this error appears but I have no idea how to fix this.
I have this JS which works but then it starts to scroll before the page completes loading. Is there a way to check page loading and then load for that smooth effect?
jQuery(document).ready(function(){
var href = window.location.href+'#team';
var splitit = (href.split('#'))[1];
if(splitit !== "" || splitit !== "undefined"){
jQuery('html, body').animate({
scrollTop: jQuery('#'+splitit).offset().top - 50
}, 2000);
}
});
Also, what does splitit do? Can we remove it?
The split() method is used to split a string into an array of substrings, and returns the new array.
var str = "How are you doing today?";
var res = str.split(" ");
//result is array [How,are,you,doing,today?]
Remove for what?
Splitit needed for checking is in url '#'-symbol or not empty url after '#'.
Try load event that runs when the page is fully loaded including graphics.
jQuery( window ).load(function() {
// Run code
});
For this functionality, you can utilize modern browsers css:
html {
scroll-behavior: smooth;
}
but I recommend this approach: call smoothScroll() in document.ready
function smoothScroll(){
// this part will add ID's to the named anchor tags
// please name tags names not to interfere with other elements id's but
// also will look good in addressbar, as : #ListOfFeaturedProductsSection
$("a").each(function(){
var t=this;
if (t.name!=="" && t.id==""){
t.id=t.name;
}
});
// 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
var hash = this.hash;
if (hash) {
event.preventDefault();
// 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;
});
}
}
});
}
splitit is the id attribute of the target to what the page should be scrolled.
Actually it is not so obviously how to check that all resources are loaded, but you can put this jquery code in the end of your page before , i think, it helps you partly.
I have a link and trying to make it smooth scroll, it works but it makes all links active I just want it for this specific link no others
<div id="shelf">content</div>
$(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
}, 800, function () {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
Then be more specific in your jQuery selectors
Change:
And
$("a").on('click', function (event) {
For:
And
$("a#myspecificlink").on('click', function (event) {
Change
$("a").on("click", function(){ ... });
To
$("a#toshelf").on("click", function(){ ... });
And make this your HTML:
Click me!
Instead of using tag selector, use id selector as below:
<a id="a1" href="#shelf"></a>
<div id="shelf">content</div>
$(document).ready(function ()
{
$("#a1").on('click', function (event)
{
//Your code here
});
});
I am using this code to a wordpress paid theme (Gavick - Creativity) and it uses the code below:
jQuery(document).ready(function () {
// SmoothScroll jQUery substitue
jQuery('a[href^="#"]').click(function (e) {
e.preventDefault();
var target = this.hash,
$target = jQuery(target);
if ($target.length) {
jQuery('html, body').stop().animate({
'scrollTop': $target.offset().top + 150
//'scrollTop': $target.offset().top ORIGINAL
}, 1000, 'swing', function () {
window.location.hash = target+150;
//window.location.hash = target; ORIGINAL
});
} else {
window.location.hash = target;
// window.location.hash = target; ORIGINAL
}
});
The thing is that it smooth scrolls only from internal links and not from external.
When I am at the same page and click on an anchor link it scrolls perfectly.
Visiting the page anchor from another page doesn't scroll at all.
All I need is to visit http://domain.com/#anchortag and scroll to it from the start of the page.
I also need to be able to have different offsets if I am in the same page or in an external one.
Any help?
Well first thing
Visiting the page anchor from another page doesn't scroll at all.
You can make a jQuery function to check for that case:
function checkForAnchor() {
var pathname = jQuery(location).attr('href');
pathname = pathname.split("#");
for(var i = 0; i < pathname.length; i++){
if(pathname[i] == 'YOUR ANCHOR'){
jQuery('html, body').animate({ scrollTop: (jQuery('.YOUR CONTAINER TO SCROLL TO').offset().top)}, 'slow');
}
}
}
I also need to be able to have different offsets if I am in the same page or in an external one.
Therefore you may use a cookie. When the user visits your page first and there is no cookie you can use another offset to scroll to. After that set a cookie and use a different offset.