Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 6. Dimensions > Determining Whether an Element Is Within the Viewport - Pg. 143

In both of these examples, the scrolling happens instantaneously--efficient, but not necessarily attractive. The animate method will animate an element's scrollTop prop- erty, so animating the transition is trivial. Here's how we would do it for the scrolling container: var $foo = jQuery('#foo'); $('#bam').click(function() { var lastParagraphPosition = jQuery('#foo p:last').position(); var scrollPosition = $foo.scrollTop() + lastParagraphPosition.top; jQuery('#foo').animate({scrollTop: scrollPosition}, 300); }); jQuery also includes a scrollLeft method, with behavior analogous to scrollTop . 6.5 Determining Whether an Element Is Within the Viewport Problem You want to determine whether an element is visible within the viewport; further, you want to determine the percentage of the element that is visible and scroll to it if it is less than 50 percent visible.