Vanilla Javascript Smooth Scroll Tutorial

Sdílet
Vložit
  • čas přidán 26. 05. 2018
  • Check out my courses and become more creative!
    developedbyed.com
    Here is a quick tutorial on how to do the smooth scroll effect in vanilla javascript. Browser support is really good for the request animation animation so I wouldn't worry about it too much. Hope you guys enjoy this Javascript tutorial.
    Links:
    Ease functions : www.gizma.com/easing/
    Request time frame : developer.mozilla.org/en-US/d...
    ~-~~-~~~-~~-~
    Follow my Twitter:
    / deved94
    Please watch: "Should You Become A Software Engineer?"
    • Video
    ~-~~-~~~-~~-~
  • Jak na to + styl

Komentáře • 195

  • @michaelwagner1560
    @michaelwagner1560 Před 6 lety +115

    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.

    • @trentgrunewald1978
      @trentgrunewald1978 Před 5 lety +2

      Huge help, thanks!

    • @danielsousa5611
      @danielsousa5611 Před 5 lety +1

      Thank, help a lot!

    • @lexsemenenko
      @lexsemenenko Před 5 lety +1

      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

    • @meijboomm
      @meijboomm Před 4 lety +1

      Thanks man, helped me a lot!

    • @kasmr6860
      @kasmr6860 Před 4 lety +1

      thx man, gj

  • @BoisNation
    @BoisNation Před 4 lety +34

    The start of a legend.

  • @PS-le4mf
    @PS-le4mf Před 5 lety +12

    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!

  • @RondellKB
    @RondellKB Před 4 lety +1

    Thanks so much! You have no idea how long I've been searching for an easy to understand and working animation like this

  • @rahxephon76
    @rahxephon76 Před 5 lety +1

    I salute you brother for your easy to follow and understanding instructions. You just got yourself a new subscriber. 👍🏾

  • @RockStar-oi6cw
    @RockStar-oi6cw Před 5 lety +1

    Very helpful and informative! I really understand how each line works! Thank you for this!

  • @marvelbox
    @marvelbox Před 5 lety +4

    I've just implemented this into the react project I'm working on and it works like a charm. Thanks for the tutorial.

  • @fdc_8507
    @fdc_8507 Před 5 lety +1

    nice playlist I'm big fan of Vanilla Javascript Thanks for sharing all of this tutorials It's easy to understand

  • @monkkokkalis1354
    @monkkokkalis1354 Před 4 lety +1

    This is very helpful, Ed. I'll be integrating this into a website I'm currently creating. Thanks a lot.

  • @milanmalicevic4627
    @milanmalicevic4627 Před 4 lety +9

    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!

  • @fuad7us1
    @fuad7us1 Před 5 lety +8

    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?

  • @quidproquo786
    @quidproquo786 Před 5 lety +5

    Well explained - excellent tutorial. Goes line by line and explains every element

  • @kyleh1448
    @kyleh1448 Před 6 lety +1

    This was awesome man, thanks!

  • @programmergaptech9849
    @programmergaptech9849 Před 5 lety

    hi Dev Ed it's a cool tutorial i hope you can add more videos about vanilla javascript. i love your videos so much.

  • @fixesdev
    @fixesdev Před rokem

    Excellent video mate!

  • @marcoscabrinirianidosreis6655

    Thank you for this tutorial, it really helped me out.

  • @jeckatz
    @jeckatz Před 4 lety +1

    i thank you alot for making me fix/add anything i needed in my website right now. :D :D

  • @ManontheBroadcast
    @ManontheBroadcast Před 5 lety +3

    Could you please explain the first line of the ease function? ...
    Thanks in advance...

  • @AshfaqAhmed05
    @AshfaqAhmed05 Před 4 lety

    You're Amaazinngggg DEV ED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Keep coming up with more videos on JS

  • @MarijanRaicevic
    @MarijanRaicevic Před 5 lety

    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!

  • @sukhmandeepsingh5986
    @sukhmandeepsingh5986 Před 2 lety

    God Bless Brotha! Highly appreciate your work and your explanation for everything!

  • @phabiojullioln2332
    @phabiojullioln2332 Před 5 lety +1

    you are great teacher Thanks Ed!

  • @Kronibaloni
    @Kronibaloni Před 5 lety +1

    This is fantastic! Thank

  • @RunningReis
    @RunningReis Před 5 lety

    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?

  • @russelqp
    @russelqp Před 4 lety

    Thanks a lot for the code and the tutorial!

  • @emmanuel4699
    @emmanuel4699 Před 6 lety +1

    Bro, you're the best.

  • @moisescastillo3447
    @moisescastillo3447 Před 5 lety

    so cool, more videos with javascript like this.

  • @radekprovaznik9432
    @radekprovaznik9432 Před 5 lety

    first video tutorials that i can actually understand from start to end. Thank you!

  • @tibinsunny
    @tibinsunny Před 4 lety

    Where is " Hello My gorgeous Friends in the Internet " :-) ;-) One of the best guy in CZcams

  • @kenkvt707
    @kenkvt707 Před 5 lety

    Is it possible to do 5 different Nav links to scroll different areas using this method? How can I do it?

  • @akhwanstudio
    @akhwanstudio Před 4 lety

    what about for navigation position fixed on top? it's not work properly. i must scroll up first then click the other links

  • @ashishparkinson2
    @ashishparkinson2 Před 3 lety

    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!

  • @jeremijaredramos1228
    @jeremijaredramos1228 Před 3 lety

    what if I have a sticky navbar? top part contents of my sections going under the navbar. what should i do?

  • @moldovandorin6187
    @moldovandorin6187 Před 5 lety +1

    Can please anymore tell me where the value of currentTime is taken from?

  • @the_ks18
    @the_ks18 Před 3 lety

    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.

  • @assermriad6218
    @assermriad6218 Před rokem

    oh man you are a genius it work correcly

  • @peepwebdev575
    @peepwebdev575 Před 4 lety +1

    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.

  • @AnujSharma-cl6tr
    @AnujSharma-cl6tr Před 5 lety

    thanks bro!!! Keep it up!

  • @troymokoagow5435
    @troymokoagow5435 Před 3 lety

    what is used your theme and font ed? i like that

  • @mitri-dvp
    @mitri-dvp Před 4 lety +1

    Thank you!

  • @vxruzdanz
    @vxruzdanz Před 8 měsíci

    can i make this work for a href links?

  • @shahjalalrafi4732
    @shahjalalrafi4732 Před 3 lety

    where i can find your source code..could you please tell me?

  • @othmangueddana1462
    @othmangueddana1462 Před 3 lety

    thank you so much for the tutorials Ed , but could you do some about Angular 10 please :) keep it up man

  • @dimitritsikaridze6220
    @dimitritsikaridze6220 Před 2 lety +1

    what about scroll-behavior: smooth; ?

  • @Kronic19cdg
    @Kronic19cdg Před 4 lety

    Great Video Thank You

  • @mohammedimran3622
    @mohammedimran3622 Před 4 lety

    Something wrong with the display: flex; property.
    The elements are not centered.

  • @RameenFallschirmjager
    @RameenFallschirmjager Před 5 lety

    how do you know these functions?! I mean how did you know there are such functions in the first place?

  • @timchelsky
    @timchelsky Před 5 lety

    Thanks man!!!

  • @chima9727
    @chima9727 Před 4 lety

    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

    • @msdhaliwal
      @msdhaliwal Před 3 lety

      you still need help with that ? let me know I can help

  • @AmitMondal-hp6sz
    @AmitMondal-hp6sz Před 5 lety +2

    Uncaught TypeError: Cannot read property 'getBoundingClientRect' of null
    at smoothScroll (app.js:3)
    at app.js:10

  • @nvrenuff
    @nvrenuff Před 5 lety +1

    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?

    • @developedbyed
      @developedbyed  Před 5 lety +1

      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.

    • @cjdungca6298
      @cjdungca6298 Před 4 lety

      Please share that code pen! I've been trying to solve the same issue.

  • @erisakimura551
    @erisakimura551 Před 4 lety +1

    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?

    • @aliguliyev2122
      @aliguliyev2122 Před 4 lety

      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

  • @yitingli3545
    @yitingli3545 Před 4 lety

    veri good! thx !

  • @tallitvak5325
    @tallitvak5325 Před 5 lety +2

    THANK YOU! you really helped me!
    if you want to make infinite scroll - up and down
    setInterval(function(){
    smoothScroll('.section2', 2500);
    }, 2500);

    • @parisafro4668
      @parisafro4668 Před 3 lety

      this Function means that if I scroll my mouse one time, it goes to section two, right? instead of clicking the specific button??

  • @strxangxl
    @strxangxl Před 4 lety

    Can anyone explain me why ease functions are used??

  • @khemirimonem6001
    @khemirimonem6001 Před 5 lety +8

    why the variable input "currentTime" is not initiated?

    • @iammakimadog
      @iammakimadog Před 4 lety

      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).

  • @samishafi6535
    @samishafi6535 Před 4 lety +21

    you can use HTML and CSS for this. just put href="section2" on the link and scroll-behaviour: smooth in css

    • @fkma13552
      @fkma13552 Před 4 lety +7

      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.

    • @mahmoudk528
      @mahmoudk528 Před 4 lety

      @@fkma13552 it doesnt work in chrome too!!

    • @RondellKB
      @RondellKB Před 4 lety

      It didn't work for me in Firefox either.

    • @nivellen1168
      @nivellen1168 Před 4 lety

      I wouldn't recommend that.

  • @blu8762
    @blu8762 Před 5 lety

    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

    • @tallitvak5325
      @tallitvak5325 Před 5 lety

      you gotta to try build things, only that way you'll face challenges that beyond innerhtml and getelementbyid

  • @jakem9519
    @jakem9519 Před 5 lety

    idk why but that pause for the a lot of math comment has my dying lol

  • @ThomazMartinez
    @ThomazMartinez Před 5 lety

    What theme you using?

  • @baudysdev
    @baudysdev Před 3 lety

    Why I have to doubleclick the text to scroll ?

  • @mrwicccked
    @mrwicccked Před 6 lety +4

    Could you post a link to the code please?

  • @_ademmeral
    @_ademmeral Před 2 měsíci

    awesome

  • @bartek4033
    @bartek4033 Před 4 lety

    why it doesnt work using const, or let while declaring "target" ?

    • @msdhaliwal
      @msdhaliwal Před 3 lety

      read these
      developer.mozilla.org/en-US/docs/Glossary/Scope
      developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

  • @benedettooddo9461
    @benedettooddo9461 Před 3 lety +1

    only for curiosity how much you earned with this video from CZcams? I wanted to start a developer channel only for Italy. Regards

  • @Mach1-9538
    @Mach1-9538 Před 3 lety

    can you update this video to ES6 thank you

  • @MichaFal
    @MichaFal Před 5 lety

    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.

    • @fuad7us1
      @fuad7us1 Před 5 lety

      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.

  • @sakshamawasthi9951
    @sakshamawasthi9951 Před 3 lety

    Legend's previous days

  • @a1103345
    @a1103345 Před 5 lety

    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.

    • @developedbyed
      @developedbyed  Před 5 lety

      Thank you! It should be the same, so don't worry :)

  • @petarscepanovic2506
    @petarscepanovic2506 Před 5 lety

    works!

  • @nielsvansteen9087
    @nielsvansteen9087 Před 5 lety +9

    the bring me down smooth scrolling can also be done with just css: '* { scroll-behaviour: smooth; }' just saying

    • @nemanjastepanovic6317
      @nemanjastepanovic6317 Před 5 lety +1

      Enormous thank you 😄

    • @ic0mad
      @ic0mad Před 5 lety +15

      Mind that the css solution only works in Chrome, Firefox and Opera. Compatibility issue with Safari, Edge and IE

    • @nabilabdulkader142
      @nabilabdulkader142 Před 4 lety +1

      @@ic0mad who the hell uses Ie

    • @vishallondhe7298
      @vishallondhe7298 Před 4 lety

      @@nabilabdulkader142 stone age people's..

  • @nebojsastojakovic4919
    @nebojsastojakovic4919 Před 4 lety

    can we just use
    **CSS**
    html {scroll-behavior: smooth;} ?

    • @matthiascotting3236
      @matthiascotting3236 Před 4 lety

      unfortunately, scroll-behavior is not implemented on some Browsers, namely Safari. On top of that, you cannot change the animation speed nor the easing...

  • @vatsalaykhobragade
    @vatsalaykhobragade Před 4 lety

    Hey Ed please make a video on one page web app design.

  • @GabrielVasile
    @GabrielVasile Před 4 lety

    Why not use
    window.scrollTo({
    top: 100,
    left: 0,
    behavior: 'smooth'
    });

  • @dubailee7781
    @dubailee7781 Před 3 lety

    it works but i wanna make 3rd pages too. it's not working well over 3pages :(. but thanks for tutorials!

  • @abidali5131
    @abidali5131 Před 4 lety

    where is the source code?

  • @kumailkhan7148
    @kumailkhan7148 Před měsícem

    everything goes above my head 😮‍💨😮‍💨

  • @PS-le4mf
    @PS-le4mf Před 5 lety

    I'd rather learn some math from you. Going to watch all your videos!

  • @AndriiMartsun
    @AndriiMartsun Před 5 lety

    You are THE BEST. Really! Thank you a lot😀
    😎 - no more

  • @Philafxs
    @Philafxs Před 4 lety

    The distance is simply the targetPosition, not minus startPosition.

  • @jet2204
    @jet2204 Před 3 lety

    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;)

  • @BorNation
    @BorNation Před 5 lety +2

    For Me I Use Pure CSS to do it

  • @randomactivities5367
    @randomactivities5367 Před 3 lety

    I was your first subscriber

  • @biLLie_wiLLie
    @biLLie_wiLLie Před 5 lety

    gizma.com is closed(

  • @diptochokroborty2107
    @diptochokroborty2107 Před 4 lety +2

    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);
    });

    • @brianm5775
      @brianm5775 Před 2 lety

      got lost on same section, null error

  • @__prod1gy__793
    @__prod1gy__793 Před 5 lety +35

    html {
    scroll-behavior: smooth;
    }

    • @carlosrodriguezorellana5467
      @carlosrodriguezorellana5467 Před 5 lety +7

      True, but not 100% supported by all browsers.

    • @neirox439
      @neirox439 Před 5 lety +7

      Your proflie img suits your comment

    • @Me-og5iy
      @Me-og5iy Před 3 lety

      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.

  • @jackrosenhauerii7866
    @jackrosenhauerii7866 Před 6 lety

    GOD DAMN IT PARENS AND SINGLE QUOTES!

  • @randomorgan5891
    @randomorgan5891 Před 4 lety

    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.

    • @NoOne-ev3jn
      @NoOne-ev3jn Před 4 lety

      it isn't supported by a lot of browsers including safari and some versions of others browsers, that's why.

  • @NphiniT
    @NphiniT Před 5 lety +2

    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
      @cube.9816 Před 5 lety

      wow! thanks man!! can we add any custom smooth effects to this?

    • @NphiniT
      @NphiniT Před 5 lety

      @@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

  • @JahidHasan-zl7om
    @JahidHasan-zl7om Před 5 lety

    not working even the same code

  • @dawnbugay7094
    @dawnbugay7094 Před 4 lety +1

    this is not working in multiple sections :(

    • @Philafxs
      @Philafxs Před 4 lety +1

      Change distance to targetPosition (without - startPosition)

    • @alissonpratesperes6077
      @alissonpratesperes6077 Před 3 lety +1

      @@Philafxs Yeah! I had the same issue and your tip worked like a charm for me! Thanks ! :)

  • @alond5271
    @alond5271 Před 4 lety

    Wtf is the ease function?

  • @gregtegreg
    @gregtegreg Před 4 lety +1

    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 :)

    • @joelrizkyw
      @joelrizkyw Před 4 lety

      yeah me too ! I already watch the basics of JS but after watching JS Projects from CZcams, i feel like i don't know anything at all :(

  • @ThefutureofhistoryCoUkTV
    @ThefutureofhistoryCoUkTV Před 6 lety +1

    Unfortunatlely this kinda fails if you add more than 2 full height sections

    • @developedbyed
      @developedbyed  Před 6 lety

      haven't had an issue...what problem are you having?

    • @Philafxs
      @Philafxs Před 4 lety

      @@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.

  • @marwanemezzane4090
    @marwanemezzane4090 Před 3 lety

    you are the best, but this can do it easy with jquery or css

  • @simonfernandez-prada7647
    @simonfernandez-prada7647 Před 4 lety +1

    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!!

    • @diptochokroborty2107
      @diptochokroborty2107 Před 4 lety +1

      Hey, you found any solution to that? It looks like I'm facing the same.

    • @Monkeys996
      @Monkeys996 Před 3 lety +1

      I know this is very late but I had missed the .top from var targetPos = target.getBoundingClientRect().top; That sorted mine out.

  • @sulaimandev
    @sulaimandev Před 3 lety +1

    Who is here after 500k subs special video?

  • @cheekycheekyjen9780
    @cheekycheekyjen9780 Před 2 lety

    volume is too low

  • @sebafurfaro2482
    @sebafurfaro2482 Před 4 lety

    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

  • @yugajain5489
    @yugajain5489 Před 3 lety

    I can do this in just html