Tuesday, November 26, 2013

jQuery: The Basic Smooth Scrolling

animate()
Perform a custom animation of a set of CSS properties.
scrollTop()
Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.

For instance, if you click the left cursor-floating navigation (desktop view) of this blog, you'll see the "Top" button. That button triggers the animate() transition of the scrollTop() method.

This is the snippet of that button:

The script will trigger the transition of the vertical scroll bar to 0px top position. You need to change [duration] with an integer that represents the transition's timing length (in milliseconds), such as 500, 1000, 3000, 1234, etc. The bigger the number the longer the transition will be.

Anyway, we can call another function after the first transition is completed.

The structure looks like this:

someEvent there can be replaced by click, mouseover, mouseout, focus, blur, etc etc, or even bind multiple events at once.


Scroll to the bottom of page demo
Let's see another example, this basic button. Click it, and you'll be scrolling down to the bottom of this post.


This is the CSS, HTML element, and the script snippet of it:


Scroll to certain position

You need to change $("reference_element_selector") with the element on your page you want to scroll to on button click.


Only scrollTop(), without animate() method

That button click will trigger the "back to top" of HTML page without any transition/animation.


Links

No comments:

Post a Comment

Tell me what you think...