Scroll to view using jQuery

Jb
3 min readApr 23, 2021

Recently I have come across wanting to add a function to help navigate through my website better. I’ve always said that if you can think it and picture in development you can make it possible to implement it. The functionality I wanted to introduce to my website should work as follows, on click scroll too desired topic. I implemented a navigation bar with three subjects “Projects”, “About”, and “Misc”. All the subjects have their own section already implemented now so now it’s time to set up our function.

So first things first we have to make sure in our application we have a separate js file that will then “import” using a script tag in our html file. I put the script tag at the bottom of the html file but keeping it inside of the body tag. In this example I have called my js folder scripts with a file inside named app.js. Also we need to “import” our jQuery cdn using a script tag. This lets us use the jQuery library. In this example I am using v. 3.1.1.

Let’s make sure our app.js is connected to our html file. I simply do this by writing a console.log(“Connected”) in the app.js and once we run our index.html file in the browser we should see in the console of the development tools “Connect”. This lets us know we are properly connected and ready to add our jQuery functions.

Now time to write our scroll to function! With a combination of using call attributes and the jQuery library we should be able to achieve this functionality. On my “Project” button in the html file, I have given the button a id of “#projButton”. This way will be able to target our button by using its id attribute. In the example below I have targeted the id “#projButton” and have given it a click function. Just make sure this is set properly I have written a console.log(“CLICKED BUTTON”). So when this project button is clicked we should see in our development tools console “CLICKED BUTTON”, this lets us know we are ready to add our logic to our function.

Once we click project button we want the whole page to scroll. That means we have to target the body and html of the our index.html. We target the body and html and use the animate method provided by the jQuery library. Now we have to tell the animate method where to scroll to and how fast using params that define the css properties we will be animating.

The method animate is now going to scroll to the top of the projects div with a speed of 2000 milliseconds. I hope this helps in any project you find yourself coding with jQuery. You can find my website at jeffreybolling.com and checkout my latest repos here on Github. Happy coding!

--

--