Setting jQuery Scroll Bar Movement

Greg Crane

jquery_scroll_bar.pngThere are many ways to navigate the user around the web page to designated areas using some very basic HTML, CSS, and jQuery. The first movement I will address is vertical.

Vertical Scroll

I am always a fan of real world examples, and recently I worked on a project that had a brands list. On top of the brands list was an alphabetical key container. The desired functionality was to position the scroll bar to move to the letter of the section that was clicked. The list was quite large (200+ brands) so this code was necessary for ease of use.

Now, technically jQuery is not even needed for this; one can use just html attributes by simply adding an element id name as an href to an anchor element. When clicked, the screen will position itself directly on top of the element. Here is a simple example:

By selecting any of the top list links, which have an href attribute that corresponds to one of the paragraphs below, the scroll bar will move so that the targeted element is at the top of the browser window. Also, each paragraph has an anchor tag that contains an href that targets the id, on top which is the main h1 dom element. See, incredibly easy stuff. As a side note I also want to point out there are tons of different ways to achieve these movements, but I am trying to keep it relatively simple in this article.

Now that’s all well and good, but say we want to add a little style to the mix. I am not a fan of the way the screen snaps to the element; sure it gets the job done, but I would like a smoother movement. This can be done by adding a class to the anchor elements and adding a jQuery listener that will fire off a function when the anchor is selected. Here is the updated example:

If you don’t have a large amount of knowledge on jQuery I will break the function apart and explain how it works, otherwise feel free to skip ahead.  

$('').click(function(event) {
This sets a jQuery listener and binds it to all anchor elements with the class page-scroll. This will listen for when any of these elements are clicked.

This will stop the browser from displaying the target id in the url.

var target = $(this).attr('href');
This sets a variable called “target” to be the clicked element’s href attribute (which would be the id of the target element).

if (target.length) {
This will make sure that the element has an href, otherwise the rest of the code will not run.

$('html,body').animate( {scrollTop: $(target).offset().top }, 'slow'); }});
This will target the html and body dom elements. It will then call a jQuery function called animate. This is a rather in-depth function that can do many things. For our purposes we are supplying the properties and the duration arguments (for a more in-depth look at the functions, use jQuery’s great api documentation).

Now, instead of giving a normal property for the first argument like color or height, we use scrollTop with the function offset being called on the target element. Offset grabs the coordinates of the element relative to the document. This little bit of code basically grabs the element’s position relative to the top of the page. Lastly, we then supply the duration argument, which can be in milliseconds or a string value. After all this code has been run, the screen will move smoothly to the desired position.

Horizontal Scroll 

Now let’s talk about horizontally positioning a scroll bar. Say we have a list of products inside a container with a horizontal scroll bar. This container is displayed inside a div that has a width that is less than the inner container, but has the CSS attribute of overflow-x set to scroll. This is depicted in the example below.

Now I will walk you through how to target and move the scroll bar to access different elements inside the scrollable list. Don’t worry as much about the CSS/html and let’s focus on the jQuery. This is a little bit harder than what we did previously, but it is not too complex. I will try to split the code up and use the same variables in all the functions to make this a little easier to follow for the readers that are newer to front end development.

Now, as you can see in the example we have four buttons, each with a function attached to them. I will step through each of the functions in the following example:

Function 1:

$('#btn-center').click(function(event) {

Again, this line just sets up an event listener on the selected item, in this case our button ids.

var outerContent = $('.cat-container');
var innerContent = $('.cat-container > ul');

These will be used to reference our two containers.

outerContent.animate({scrollLeft:(innerContent.width() - outerContent.width())/2}, 500);

This runs a little like what we have done above. The red argument is one item: the minimum value for scrollLeft is zero, and the maximum is innerContent.width() - outerContent.width(). So to get halfway between we simply divide the result by 2.

As a side note, scrollLeft actually can scroll right; scrollLeft: with a 0 parameter will return to the far left, and any positive value will move the bar to the right x amount of pixels.

Function 2:

var middleElement = Math.round($('.cat-container ul li').length / 2);

This will grab the number of li elements that the selector returns, divide them by two, and then round up. This will grab the middle item, or the closest possible.

var targetElement = innerContent.children('li').eq(middleElement -1);

This will grab the actual middle element using the variables that we have set up. It will get all the li children of the inner content ul element, then grab the child with the index of the middleElement variable we got previously minus 1 (this is done because the index starts at 0).

targetElement.css('border', 'solid 2px red');
outerContent.animate({scrollLeft:  (getTotalWidth(middleElement -1) - 20) }, 500);

The first line will change the targetElement’s border color styling. The second line you should be used to seeing by now. This time we do something a little different; we call a custom function getTotalWidth, with the middle number argument passed in. This function will return the summation of all the widths of each element in the list up to that middle number. This way we will basically move the scroll bar right x amount with a -20 offset. This will be nice if you have items with variable widths inside the element. Again, that 500 is simply the milliseconds the animate function will take to complete to give it a nice, smooth appearance.

Function 3:

if(input && input > 0 && input <= catCount) {
    var targetElement = innerContent.children('li').eq(input -1);
    targetElement.css('border', 'solid 2px red');
    outerContent.animate({scrollLeft: (getTotalWidth(input -1) - 20)}, 500);
else {
alert('Please enter a valid number in')}

So, here the input is the value from the textbox. We do a quick check to make sure it exists, it is greater than 0, and it is less than or equal to the catCount variable, which is just the number of li items in our list. Inside the if statement we grab the target element, similar to what we did previously, we set its border color, and use that function to get the widths of all of the li elements leading up to and including that (again with that -20 offset). Lastly, we have a fallback with an alert telling the user to enter in a valid number.

Function 4:

$.each(liElements, function() {
     $(this).css('border', 'solid 2px orange');
outerContent.animate({scrollLeft: 0}, 500);

Here we are resetting all of the values. We remove any red outlines from the li elements by cycling through them all and setting the border back to orange. Then we scrollLeft to 0 which moves the scroll bar to the far left beginning.

Function 5:

var liElements = $('.cat-container > ul li').slice(0,number);
 var total = 0;
$.each(liElements, function() {
    total += $(this).width();
return total;

Here we grab all the li elements of the container, then we slice the array so we only have the numbers 1 through/including x where x is the passed-in number. We then proceed to add up all of the widths and then return the total.

So there you have it! With a little bit of jQuery, HTML, and CSS you can move the user to any position you would like on the screen. This functionality is not always completely necessary, but under the right circumstances and when done correctly, it can positively impact the customer experience.

Read more about the key benefits of partnering with a company that uses  certified developers. Click to Download

A Great Offer, Just a Click Away

Lorem ipsum dolor sit amet, consectetur adipiscing elit

Subscribe by Email

No Comments Yet

Let us know what you think