Web Development with jQuery®

(Elliott) #1

(^276) ❘ CHAPTER 10 SCROLLBARS
Next, you added a click event handler for the new buttons to scroll the scrollable container to the
referenced elements within the scrollable container.
$('button.block-button')
.click(
function()
{
$('div#container')
.scrollTop($('div#' + $(this).data().block).offset().top



  • $('div#container').offset().top



  • $('div#container').scrollTop())
    .scrollLeft($('div#' + $(this).data().block).offset().left



  • $('div#container').offset().left



  • $('div#container').scrollLeft());


}
);

Within this event handler, you set the scrollTop() value for the <div> element with id name
container using calculated values. You began with the value of the top edge of the block element
specifi ed by the button’s data-block attribute (relative to the top of the document).

$('div#' + $(this).data().block).offset().top

From that value, you subtracted the value of the top edge of the scrollable container.


$('div#container').offset().top

Finally, you added back in the current scroll position of the scrollable container, which has an
impact on the fi rst value in this calculation.

$('div#container').scrollTop()

You followed the same pattern to set the horizontal scrollbar position using scrollLeft().


Scrolling to the Top


The preceding example demonstrated the functionality of setting the scrollbar positions using
calculated values. Scrolling to the top of a scrollable container is a specialized case in which the
value to be set is zero. To scroll the container to its top leftmost content, you need only one line of
jQuery code:

$('div#aScrollableElement').scrollTop(0).scrollLeft(0);

jQuery’s scrollTop() and scrollLeft() are fairly tolerant of values outside the logical bounds. This
tolerance can be useful when the values are calculated. For instance, fractional values are truncated;
most values greater than the maximum possible scrollbar position result in the maximum valid
value; and negative or otherwise invalid values result in zero. As a result, the following line also
scrolls the container to its top leftmost content:

$('div#aScrollableElement').scrollTop('red').scrollLeft('blue');

http://www.it-ebooks.info

Free download pdf