Really nice tutorial, but I faced the following error: when I used the code with a navbar which contained the links as nav-items. the function wouldn't scroll properly. The error occured, because the .getBoundingClientRect().top function already returns the distance to the selector based on the window.y position. So when you click a nav-link twice the second time your targetPosition is equal 0 while your startPosition stays the same e.g 1200 => distance = targetPosition(0) - startPosition(1200) = -1200 which scrolls back your window to the very top which is of course not right. Basically we don't need the distance variable instead we should change the ease parameter distance to targetPosition => var run = ease(timeElapsed, startPosition, targetPosition, duration); If you want to use the code with a navbar I would also recommend to subtract your navbar-height from the targetPosition variable.
I had to draw the whole scroll system on paper to figure this out. I wish I read your comment earlier) And for this reason, the tutorial is not complete. It's more how to use animation frame and ease functions... Which was actually useful
This is actually really helpful. Your ideas for tutorials actually help. I feel like I get a different perspective than other programmers. Keep making videos!
One small addition to the code :) Beside what Michal Wagner said (I was also struggling and figured that I need to change distance to targetPosition), I wrote this to make all links with # in the href scroll to the desired target (with the same id as the href value) without the need to call the function for each individual element. So, after your code, write: //get all the links on the page containing # in the href (^= means starting with) const anchorLinks = document.querySelectorAll('a[href^="#"]'); anchorLinks.forEach((link) => { // get the target element by getting the href value from each link let scrollTarget = link.getAttribute('href'); // for clicking on any of the links link.addEventListener('click', (e) => { // we need to prevent default behaviour which would be just jumping to the element without scrolling e.preventDefault(); // call your fancy animated scroll function smoothScroll(scrollTarget,1000); }) }); Thanks for the video! Cheers!
It does not work properly in safari. I stucked with it few days ago. Safari don`t know what is "scroll-behavior". To do crossbrowser site you need to use js. No other solution.
Great video. There is an issue with this function though as Brian Cook has point out below. Please change the targetPosition variable to this: var targetPosition = target.getBoundingClientRect().top + window.pageYOffset; The problem is that the function doesn't take into account when you have already scrolled down the page. It calculates the scroll distance as if it were at pageYOffset = 0 every time. But this is still a great video and was super helpful! thank you for all your hard work Dev Ed.
Here is a super simple one: function scrollPage(divClass){ var target = document.querySelector(divClass); var targetLeftposition = target.getBoundingClientRect().left; var targetTopposition = target.getBoundingClientRect().top; window.scrollTo({ top: targetTopposition, left: targetLeftposition, behavior: 'smooth' }); } scrollPage(".section2");
@@cube.9816 I checked around! But it seems the behaviour key on the window.scrollTo() function does not accept custom effects. You will have to write an animation yourself or use a JS library! Here is a link to a a vanilla JS script that has a custom written easingOut animation: gist.github.com/andjosh/6764939
In my case, i have to use e.preventDefault() in the eventListener to prevent the anchor tags default behave otherwise it won't works. Anybody faced that?
Hello Dev, I've really enjoyed your tutorial. I'm a beginner in javascript. I followed your code but lost it at the end. I've coded exactly as you did. But upon clicking smooth scroll isn't working but without click event, it works fine when reloading the website every time. Here is my code (part I think is wrong). Your help will be much appreciated. var section1= document.querySelector('.first'); var section2= document.querySelector('.second'); section1.addEventListener('click',function(){ smoothScroll('.second',2000); });
In face I have the same question. This is what I found The callback method is passed a single argument, a DOMHighResTimeStamp, which indicates the current time (based on the number of milliseconds since time origin).
this is so useful the some day or the other this will be compatible with all browser, but IE. Just use it dgaf to IE! Cuz the more you make websites incompatible with IE, the more people will stop using it.
Hi great tutorial. I noticed that you don't need 'distance' variable 'getBoundingClientRect' returns distance between your current view and target. So it would work fine if you place 'targetPosition' in the ease function :) Plus that way you won't have problems after scrolling between sections.
Can you point me to how to implement this for a scroll inside an element, rather than the whole window. I have a div with horizontal scroll. I was able to set 'scroll-behavior': 'smooth' on the div and it works in Chrome, Firefox, but not Edge or Safari and i'd prefer not to depend on any library. What could be an alternative solution?
What I fail to understand, as a non dev, is this: my current mindset is set on the html&css simplicity - meaning I have an element and I make it look and stay where I want. Now JS being my first programming language, I don’t get the logic. I don’t understand where is the beginning and where is the end. I must find a book and study because learning a short script doesn’t help the big picture. Just my current situation :)
thank you Ed Im learning so much!! but I just made .section3 and wanted it to slide 1 to 2, 2 to 3, 3 to top and 2 to 3 part didnt work, does anybody know how to do that?
dude add into your delete all the stuff in javascript and just your into your css html {scroll-behavior: smooth;} AND THAT'S IT, YOU DON'T NEED TO YOUR ANY JS
I'm facing this issue ( Uncaught TypeError: Cannot read property 'addEventListener' of null for smooth scroll effect using JS). Kindly help me to fix it. I'm new to JS and trying to build projects. I need your help.
surprisingly in chrome console log is not working for me as there is no output in console but when added the code on codepen.io the online platform the console log of codepen io is working what should I do is there someway to link .js to HTML please reply quick!
@@developedbyed The issue is that the distance is not supposed to have the pageYOffset subtracted. getBoundingClientRect().top is already the distance in itself. So when you scroll a bit from the top anchor or have multiple sections, the subtraction of the pageYOffset messes things up.
Noice tutorial but there is an error for the distance: you should remove the '- startPos' else the distance take the wrong referencial (and if you got a nav bar, you just have to add: let margin = document.getElementById("nav-bar").getBoundingClientRect().height; And add to your distance: - margin (let distance = targetPos - margin;)
I found easier way to make your website responding in the same way html { scroll-behavior: smooth; } Does it have any relation in what've done? Btw, well done.
hi, how can i use one header for all my html pages? something in html( or css, js) equivalent of include in php? so i don't need to copy and paste in each page and when have some changes to do i just change one file? thanks for your tutorial
Hi Ed! I just found out your channel and enjoyed your content. Thank you :) I just wanted to ask what is the difference between having this effect through Vanilla JS vs using plain HTML tag and passing an id or class of a section to href. It seems like I can get the same effect.
unfortunately, scroll-behavior is not implemented on some Browsers, namely Safari. On top of that, you cannot change the animation speed nor the easing...
before adding the distance, do this var target = document.querySelector(target) var targetPosition = target.getBoundingClientRect().top var startPosition = window.pageYOffset targetPosition += startPosition var distance = targetPosition - startPosition
It's great but you can do the same effect without javascript. HTML Click to scroll // put content here // put another content here CSS html {scroll-behaivor:smooth;} And thats all
Really nice tutorial, but I faced the following error: when I used the code with a navbar which contained the links as nav-items. the function wouldn't scroll properly.
The error occured, because the .getBoundingClientRect().top function already returns the distance to the selector based on the window.y position.
So when you click a nav-link twice the second time your targetPosition is equal 0 while your startPosition stays the same e.g 1200
=> distance = targetPosition(0) - startPosition(1200) = -1200 which scrolls back your window to the very top which is of course not right.
Basically we don't need the distance variable instead we should change the ease parameter distance to targetPosition
=> var run = ease(timeElapsed, startPosition, targetPosition, duration);
If you want to use the code with a navbar I would also recommend to subtract your navbar-height from the targetPosition variable.
Huge help, thanks!
Thank, help a lot!
I had to draw the whole scroll system on paper to figure this out. I wish I read your comment earlier) And for this reason, the tutorial is not complete. It's more how to use animation frame and ease functions... Which was actually useful
Thanks man, helped me a lot!
thx man, gj
The start of a legend.
This is actually really helpful. Your ideas for tutorials actually help. I feel like I get a different perspective than other programmers. Keep making videos!
Thanks so much! You have no idea how long I've been searching for an easy to understand and working animation like this
One small addition to the code :)
Beside what Michal Wagner said (I was also struggling and figured that I need to change distance to targetPosition), I wrote this to make all links with # in the href scroll to the desired target (with the same id as the href value) without the need to call the function for each individual element.
So, after your code, write:
//get all the links on the page containing # in the href (^= means starting with)
const anchorLinks = document.querySelectorAll('a[href^="#"]');
anchorLinks.forEach((link) => {
// get the target element by getting the href value from each link
let scrollTarget = link.getAttribute('href');
// for clicking on any of the links
link.addEventListener('click', (e) => {
// we need to prevent default behaviour which would be just jumping to the element without scrolling
e.preventDefault();
// call your fancy animated scroll function
smoothScroll(scrollTarget,1000);
})
});
Thanks for the video!
Cheers!
Well explained - excellent tutorial. Goes line by line and explains every element
ey thanks for that!
I've just implemented this into the react project I'm working on and it works like a charm. Thanks for the tutorial.
I salute you brother for your easy to follow and understanding instructions. You just got yourself a new subscriber. 👍🏾
This is very helpful, Ed. I'll be integrating this into a website I'm currently creating. Thanks a lot.
nice playlist I'm big fan of Vanilla Javascript Thanks for sharing all of this tutorials It's easy to understand
Very helpful and informative! I really understand how each line works! Thank you for this!
You're Amaazinngggg DEV ED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Keep coming up with more videos on JS
you can use HTML and CSS for this. just put href="section2" on the link and scroll-behaviour: smooth in css
It does not work properly in safari. I stucked with it few days ago. Safari don`t know what is "scroll-behavior". To do crossbrowser site you need to use js. No other solution.
@@fkma13552 it doesnt work in chrome too!!
It didn't work for me in Firefox either.
I wouldn't recommend that.
God Bless Brotha! Highly appreciate your work and your explanation for everything!
Where is " Hello My gorgeous Friends in the Internet " :-) ;-) One of the best guy in TH-cam
i thank you alot for making me fix/add anything i needed in my website right now. :D :D
Great video. There is an issue with this function though as Brian Cook has point out below.
Please change the targetPosition variable to this:
var targetPosition = target.getBoundingClientRect().top + window.pageYOffset;
The problem is that the function doesn't take into account when you have already scrolled down the page. It calculates the scroll distance as if it were at pageYOffset = 0 every time.
But this is still a great video and was super helpful! thank you for all your hard work Dev Ed.
hi Dev Ed it's a cool tutorial i hope you can add more videos about vanilla javascript. i love your videos so much.
Thank you for this tutorial, it really helped me out.
Thanks a lot for the code and the tutorial!
you are great teacher Thanks Ed!
This was awesome man, thanks!
oh man you are a genius it work correcly
Thank you!
Could you please explain the first line of the ease function? ...
Thanks in advance...
Excellent video mate!
This is fantastic! Thank
so cool, more videos with javascript like this.
Here is a super simple one:
function scrollPage(divClass){
var target = document.querySelector(divClass);
var targetLeftposition = target.getBoundingClientRect().left;
var targetTopposition = target.getBoundingClientRect().top;
window.scrollTo({
top: targetTopposition,
left: targetLeftposition,
behavior: 'smooth'
});
}
scrollPage(".section2");
wow! thanks man!! can we add any custom smooth effects to this?
@@cube.9816 I checked around! But it seems the behaviour key on the window.scrollTo() function does not accept custom effects. You will have to write an animation yourself or use a JS library!
Here is a link to a a vanilla JS script that has a custom written easingOut animation:
gist.github.com/andjosh/6764939
In my case, i have to use e.preventDefault() in the eventListener to prevent the anchor tags default behave otherwise it won't works. Anybody faced that?
idk why but that pause for the a lot of math comment has my dying lol
first video tutorials that i can actually understand from start to end. Thank you!
Uncaught TypeError: Cannot read property 'getBoundingClientRect' of null
at smoothScroll (app.js:3)
at app.js:10
Same here . Could you find what could you improve to finish this project? Thanks!
Bro, you're the best.
Great Video Thank You
Legend's previous days
Can please anymore tell me where the value of currentTime is taken from?
thanks bro!!! Keep it up!
Hello Dev, I've really enjoyed your tutorial. I'm a beginner in javascript. I followed your code but lost it at the end. I've coded exactly as you did. But upon clicking smooth scroll isn't working but without click event, it works fine when reloading the website every time. Here is my code (part I think is wrong). Your help will be much appreciated.
var section1= document.querySelector('.first');
var section2= document.querySelector('.second');
section1.addEventListener('click',function(){
smoothScroll('.second',2000);
});
section2.addEventListener('click',function(){
smoothScroll('.first',2000);
});
got lost on same section, null error
thank you so much for the tutorials Ed , but could you do some about Angular 10 please :) keep it up man
Cool video. Can tell me what settings are you using in OBS. My OBS recording is chopping audio and video after a few seconds of recording. Thanks!
only for curiosity how much you earned with this video from TH-cam? I wanted to start a developer channel only for Italy. Regards
why the variable input "currentTime" is not initiated?
In face I have the same question. This is what I found
The callback method is passed a single argument, a DOMHighResTimeStamp, which indicates the current time (based on the number of milliseconds since time origin).
html {
scroll-behavior: smooth;
}
True, but not 100% supported by all browsers.
Your proflie img suits your comment
this is so useful the some day or the other this will be compatible with all browser, but IE. Just use it dgaf to IE! Cuz the more you make websites incompatible with IE, the more people will stop using it.
the bring me down smooth scrolling can also be done with just css: '* { scroll-behaviour: smooth; }' just saying
Enormous thank you 😄
Mind that the css solution only works in Chrome, Firefox and Opera. Compatibility issue with Safari, Edge and IE
@@ic0mad who the hell uses Ie
@@nabilabdulkader142 stone age people's..
Hi great tutorial. I noticed that you don't need 'distance' variable 'getBoundingClientRect' returns distance between your current view and target. So it would work fine if you place 'targetPosition' in the ease function :) Plus that way you won't have problems after scrolling between sections.
In that case, when you scroll back it's end just top of section1, not go all the way up. plz correct me if i'm wrong.
THANK YOU! you really helped me!
if you want to make infinite scroll - up and down
setInterval(function(){
smoothScroll('.section2', 2500);
}, 2500);
this Function means that if I scroll my mouse one time, it goes to section two, right? instead of clicking the specific button??
what is used your theme and font ed? i like that
what about scroll-behavior: smooth; ?
The distance is simply the targetPosition, not minus startPosition.
everything goes above my head 😮💨😮💨
this is not working in multiple sections :(
Change distance to targetPosition (without - startPosition)
@@Philafxs Yeah! I had the same issue and your tip worked like a charm for me! Thanks ! :)
Could you post a link to the code please?
github.com/DevEdwin/Smooth-Scroll
veri good! thx !
can i make this work for a href links?
Can you point me to how to implement this for a scroll inside an element, rather than the whole window. I have a div with horizontal scroll. I was able to set 'scroll-behavior': 'smooth' on the div and it works in Chrome, Firefox, but not Edge or Safari and i'd prefer not to depend on any library. What could be an alternative solution?
Browser support on scroll smooth is not that great..yeah. Throw up a codepen or something of your code and I will gladly take a look at it.
Please share that code pen! I've been trying to solve the same issue.
What I fail to understand, as a non dev, is this: my current mindset is set on the html&css simplicity - meaning I have an element and I make it look and stay where I want. Now JS being my first programming language, I don’t get the logic. I don’t understand where is the beginning and where is the end. I must find a book and study because learning a short script doesn’t help the big picture. Just my current situation :)
yeah me too ! I already watch the basics of JS but after watching JS Projects from TH-cam, i feel like i don't know anything at all :(
what if I have a sticky navbar? top part contents of my sections going under the navbar. what should i do?
Thanks man!!!
thank you Ed Im learning so much!! but I just made .section3 and wanted it to slide 1 to 2, 2 to 3, 3 to top and 2 to 3 part didnt work, does anybody know how to do that?
dude add into your delete all the stuff in javascript and just your into your css html {scroll-behavior: smooth;} AND THAT'S IT, YOU DON'T NEED TO YOUR ANY JS
I'm facing this issue ( Uncaught TypeError: Cannot read property 'addEventListener' of null for smooth scroll effect using JS). Kindly help me to fix it. I'm new to JS and trying to build projects. I need your help.
how do you know these functions?! I mean how did you know there are such functions in the first place?
thats amazing man can you plz tell me where did you learn all this stuff ? because all i know is getelementbyid and changing innerhtml lol
you gotta to try build things, only that way you'll face challenges that beyond innerhtml and getelementbyid
Is it possible to do 5 different Nav links to scroll different areas using this method? How can I do it?
where i can find your source code..could you please tell me?
what about for navigation position fixed on top? it's not work properly. i must scroll up first then click the other links
Is this the same as adding href="#contactme" or whatever the ID is of the place on the page you are trying to get to?
surprisingly in chrome console log is not working for me as there is no output in console but when added the code on codepen.io the online platform the console log of codepen io is working what should I do is there someway to link .js to HTML please reply quick!
Hey Ed please make a video on one page web app design.
Why I have to doubleclick the text to scroll ?
Something wrong with the display: flex; property.
The elements are not centered.
GOD DAMN IT PARENS AND SINGLE QUOTES!
For Me I Use Pure CSS to do it
Unfortunatlely this kinda fails if you add more than 2 full height sections
haven't had an issue...what problem are you having?
@@developedbyed The issue is that the distance is not supposed to have the pageYOffset subtracted. getBoundingClientRect().top is already the distance in itself. So when you scroll a bit from the top anchor or have multiple sections, the subtraction of the pageYOffset messes things up.
Noice tutorial but there is an error for the distance: you should remove the '- startPos' else the distance take the wrong referencial (and if you got a nav bar, you just have to add:
let margin = document.getElementById("nav-bar").getBoundingClientRect().height;
And add to your distance: - margin (let distance = targetPos - margin;)
can you update this video to ES6 thank you
I found easier way to make your website responding in the same way
html {
scroll-behavior: smooth;
}
Does it have any relation in what've done?
Btw, well done.
it isn't supported by a lot of browsers including safari and some versions of others browsers, that's why.
I'd rather learn some math from you. Going to watch all your videos!
why it doesnt work using const, or let while declaring "target" ?
read these
developer.mozilla.org/en-US/docs/Glossary/Scope
developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Who is here after 500k subs special video?
What theme you using?
Material Theme :)
You are THE BEST. Really! Thank you a lot😀
😎 - no more
Dev Ed:A lot of math
Me: *laughs in matlab*
it works but i wanna make 3rd pages too. it's not working well over 3pages :(. but thanks for tutorials!
hi, how can i use one header for all my html pages? something in html( or css, js) equivalent of include in php? so i don't need to copy and paste in each page and when have some changes to do i just change one file?
thanks for your tutorial
you still need help with that ? let me know I can help
Every time I clicked on "bring me down" nothing happened. I copied every code posted here. I'll try again later. Thanks for these projects!!
Hey, you found any solution to that? It looks like I'm facing the same.
I know this is very late but I had missed the .top from var targetPos = target.getBoundingClientRect().top; That sorted mine out.
where is the source code?
awesome
Why not use
window.scrollTo({
top: 100,
left: 0,
behavior: 'smooth'
});
works!
Hi Ed! I just found out your channel and enjoyed your content. Thank you :) I just wanted to ask what is the difference between having this effect through Vanilla JS vs using plain HTML tag and passing an id or class of a section to href. It seems like I can get the same effect.
Thank you! It should be the same, so don't worry :)
can we just use
**CSS**
html {scroll-behavior: smooth;} ?
unfortunately, scroll-behavior is not implemented on some Browsers, namely Safari. On top of that, you cannot change the animation speed nor the easing...
Wtf is the ease function?
not working even the same code
Early Ed looks like drugs addict who's coding for coke:D (No offence bro(:)
🖕
😃🔫
before adding the distance, do this
var target = document.querySelector(target)
var targetPosition = target.getBoundingClientRect().top
var startPosition = window.pageYOffset
targetPosition += startPosition
var distance = targetPosition - startPosition
gizma.com is closed(
It's great but you can do the same effect without javascript.
HTML
Click to scroll
// put content here
// put another content here
CSS
html {scroll-behaivor:smooth;}
And thats all
Hi Lorena 😂
Are you sure you’re in the correct user account?
volume is too low