Web Development with jQuery®

(Elliott) #1

(^272) ❘ CHAPTER 10 SCROLLBARS
Inside the scroll event, you write some logic for updating the status bars by getting the scrollbar
positions. First, you get the scrollTop() value from the scrolled element and use its value to set the
innerText of the span#vertical-scroll-value element. Then you similarly get the scrollLeft() value
from the scrolled element and use that value to set the innerText of the span#horizontal-scroll-
value element.
function()
{
$('span#vertical-scroll-value')
.text($(this).scrollTop());
$('span#horizontal-scroll-value')
.text($(this).scrollLeft());
}
With this minimal amount of jQuery, you have retrieved the scrollbar position values of a DOM
element while it is being scrolled and updated additional DOM elements to display those values. The
remaining examples in this chapter build upon this structure that you created.
SCROLLING TO A PARTICULAR ELEMENT
WITHIN A SCROLLING


As discussed in the introduction to this chapter, and as is typical with jQuery, the same method used
to get the value can also be used to set the value. Therefore, setting the scrollbar positions of a scrol-
lable element is as easy as
$('div#aScrollableElement').scrollTop(100);
$('div#aScrollableElement').scrollLeft(100);
Again, the values should be specifi ed in pixels when setting the scrollbar positions; as a result, you
must calculate the pixel values if you want to scroll directly to an element within a scrollable con-
tainer. Example 10-2 shows multiple elements within a scrolling
element and the code needed
to scroll directly to each:
<!DOCTYPE HTML>




content='application/xhtml+xml; charset=utf-8' />

Scrollbar Position







Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[http://www.it-ebooks.info](http://www.it-ebooks.info)