Smooth Scrolling with only vanilla JavaScript - javascript

I have always used this jQuery script for smooth scrolling:
var root = $('html, body');
$('a[href^="#"]').click(function() {
root.animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 1000);
return false;
});
How can I do this with vanilla JavaScript? I have tried this:
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
But it doesn't work with Safari, which is a deal breaker for me.

As you can read on the docs safari doesn't support options parameters on scrollIntoView so you'll need to find another method. I suggest taking a look at this alternative.

Related

Converting conventional jQuery link smooth scrolling method to vanilla javascript

I'm converting this jQuery code:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html,body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 1000);
});
It's very popular, and I'm sure everyone understand what it does, when clicking an anchor link with an id it smooth scrolls to it. I have used this code for many projects but I am no longer using jQuery, as it is being deprecated. Converting this to vanilla JavaScript has proven a challenge. This is what I have so far, that works:
document.addEventListener('click', function(event) {
if (event.target.matches('a[href^="#"')) {
event.preventDefault();
console.log('works fine')
}
}, false);
I am having trouble finding resources to convert .animate() and the line with scrollTop. It's a pretty tall order for someone with only beginner/intermediate JS experience. I was wondering if anyone knew how to convert this code to JavaScript, or where I could find resources about converting this. A popular solution to smooth scrolling I have found is the following code:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
Using scroll-behavior: smooth, but I do not wish to use this as it is unsupported by many browsers (to my knowledge), and it does not let me customize how long it takes to smooth scroll.
Any help would be much appreciated.
Looking through the jQuery code, it uses another library (Tweening) to create the smooth scrolling effect. It wouldn't be worthwhile trying to create it in vanilla JS.
While a lot of browsers might not support scroll-behaviour, pretty much all major browsers do. A lot of older browsers are now being discontinued (especially IE).
Your best option is to continue using the code you provided yourself (or just continue using jQuery):
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});

Compatibility with latest Jquery

I got this code off the internet some years back. But whenever I update my wordpress to the latest Jquery version using Jquery updater plugin, it breaks. As soon as I revert back to the old version, it works again. By breaks, I mean that instead of scrolling to the top of the page, it moves the page up by about 10 pixels.
Is there anything in this code which is now incompatible with latest version of Jquery?
The script is for a button to scroll the page back to the top.
<script>
jQuery(document).ready(function($) {
$(window).scroll(function() {
if ($(this).scrollTop() < 500) {
$('#scrolltotop') .fadeOut();
}
else {
$('#scrolltotop') .fadeIn();
}
});
$('#scrolltotop').on('click', function() {
$('html, body').animate({scrollTop:0}, 'slow');
return false;
});
});
</script>
Thank you so much for your help everyone.
Try the code below, hope it'll help
$('#scrolltotop').on('click', function() {
$('html, body').animate({
scrollTop: $("body").offset().top
}, 500);
return false;
});

Jquery scroll to offset target div on page load

I'm trying to scroll to the div that is in the URL. It could be one of 21 IDs like:
url.com/test#lite1
url.com/test#lite2
url.com/test#lite3
I need this to happen on page load (user is coming from an ebook and should see the exact item they clicked on).
Here is the code I currently have:
$(document).ready(function(){
$('a[href^="#"]').load(function() {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top -150
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
</script>
It doesn't work and I think it's because of this part (I have no idea what I'm doing here):
$('a[href^="#"]').load(function() {
I also want it to be in the center of the page (not at the top cut off like browsers do when scrolling to divs). Please let me know if this is correct:
$target.offset().top -150
Thanks so much in advance!
window.location.hash contains the current hash in the URL so use that. As the hash is already in the URL(as you said that they come to page by clicking on link with hash) so you don't need to add it manually.
Try using this :
$(document).ready(function(){
$('html,body').animate({
scrollTop: $(window.location.hash).offset().top-150
}, 900, 'swing');
});
Using wordpress, it seems the $ needs to be replaced by jQuery so it comes out to:
jQuery(document).ready(function(){
jQuery('html,body').animate({
scrollTop: jQuery(window.location.hash).offset().top-150
}, 900, 'swing');
});
As an alternative, you could try using the following jQuery plugins. I've used them on multiple projects. They're customizable and provide nice, smooth animation:
scrollTo (download, documentation) allows you to scroll to a specific element on the page. Basic usage: $(element).scrollTo(target);
localScroll (download, documentation) requires scrollTo as a dependency, and handles anchors for you. You can apply it to specific set of links by selecting their container: $('#link-container').localScroll();, or you can activate it globally: $.localScroll();

jQuery scroll to anchor with variable speed

I have a very basic HTML site with a few anchor tags. On click each anchor leads to the other, using a little bit of smooth scroll with this function:
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault(); var target = this.hash; var $target = $(target);
$('html, body').stop().animate(
{
'scrollTop': $target.offset().top - 300
},
900,
'swing',
function () {
window.location.hash = target - 300 ;
}
);
});
});
The gaps between the anchors will be quite big and I am trying to figure out a way to get the speed to vary - when clicked on an anchor, to start slower, than speed up, when close to the next anchor to slow down again before it stops.
Could not find any JQuery docs on it, does someone has a suggestion?
FIDDLE: https://jsfiddle.net/koteva/ovf9ywb3/
I believe you would want to use an easing function to handle this. By default, jQuery only handles swing easing, which you have already passed into your animate function. However, you can include additional easing functions with a plugin.
George Smith has a lightweight js plugin for download that may help you, called jquery.easing.1.3.js. I think easeInOutQuart sounds like the closest thing to what you are looking for
Here is a demo fiddle
By including jQuery UI (after jQuery) you will be able to use the easings listed here
Your code should look like:
$('html, body').stop().animate(
{
'scrollTop': $target.offset().top - 300
},
900,
'easeInOutCubic',
function () {
window.location.hash = target - 300 ;
}
);

Best method for Auto scrolling to previous place without jquery (PHP and Javascript)

I have done my homework and seen allot of different methods of accomplishing this. But what is the most effective way that is cross-browser error "proof".
Some things I have tried...
body.onload = function(){
window.scrollTo(0,<?php echo $_POST['scrolltext'];?>);
};
With scrolltext coming from a hidden input filled by a document.getElementById('scrolltext').value = window.pageYOffset || docElem.scrollTop || body.scrollTop
Also...
$(document).ready(function() {
$('#<?php echo $_POST['site']; ?>').scrollIntoView(true);
});
with many otherr forms of this, where the posted site being a ID linked by php on the page based on the button pushed. But I found Jquery's methods very unreliable and Ipad's especially seem to hate everything to do with jquery(especially panels)...
So i figured the best way to do it would be javascript? some PHP methods I cant really think of?
Thanks in advance.
Scroll to the top of a document
$("html, body").animate({ scrollTop: $(document).height() }, 300);
Scroll to the top of an element
$('html, body').animate({ scrollTop: $("#itemid").offset().top }, 800);
Scroll to the top of a specified element
var itemid = $("#daitemid2").val(); //method 1
var itemid = $(this).attr("itemid"); //method 2
$('html, body').animate({ scrollTop: $("#itemid"+itemid+").offset().top }, 800);

Categories

Resources