Take Off Labs | Ruby on Rails and iOS for web and mobile apps
x
11224742 10207744386832061 1134591581572583218 n

Smooth scrolling in long pages

about 7 years ago by Alex

Popup

The long page effect is becoming more and more popular, as web developers all around the world are starting to see its benefits. One of the most important features of a long page is the smooth scrolling, as it allows the user to get a better view of the website and adds a bit of dynamism.

In my post, I am going to show you how to implement this and avoid the problems I encountered. Let’s assume we have a contact section at the bottom of the page and you want to scroll down to it when you click on the “Contact Us” button in the header menu.

Step 1: Identifying the involved components

On a long page, identifying different sections of the page is very important when it comes to scrolling. For our contact section, we will add a div right above it, with the “contact” ID.


%div.section{id: "clients"}

The “Contact Us” button also needs an ID (let’s say “contact-button”) , which we will use in the jQuery function.


%td

%p{id: "contact-button"}

Contact Us

Step 2: Writing the function

Now that we can identify the contact section and the button we’ll use, all we need to do is write the function.


jQuery ->

$("#contact-button").click ->

$("html, body").animate

scrollTop: $("#contact").offset().top

, 600

As you can see, when we click on the “Contact Us” button, the body of the page is animated, and is scrolls down to the element with the “contact” ID. The speed of the scrolling can be adjusted. Here, one scroll lasts 600 ms.

Step 3: Playing around with the design

Once you have your page sections working and a functional scroll, it is time to experiment a bit, in order to achieve a beautiful design. A very useful element is the “Back Up” button. When you have very long pages, users might want to go back to the header without having to scroll manually. This can be implemented in the way I explained above.

Step 4: Testing your application and trying different browsers

When it comes to web apps, testing is crucial. You might encounter problems with your code that you didn’t even take in the consideration during the process. In my experience with scrolling, I had a few issues with Chrome. Even though in Firefox everything went well, the scrolling wasn’t exactly smooth in Chrome. I managed to fix this by manually resizing the images on the page instead of waiting for the browser to do it. In Chrome, loading resized images took quite a long time, therefore jamming the scroll.

That’s it! Now you know how to implement smooth scrolling. :)

Did you like this post? Share it with your friends!