James Tauber

journeyman of some

blog > 2008 > 04 >

James Tauber's Blog 2008/04/28

Auto-Scrolling in jQuery

I mentioned in my previous post New Site Look that, inspired by 37 Signals, I wanted to auto-scroll pages in my website in two circumstances:

  • when there is an error in an Add Comment form, scroll down to the error message
  • when the user expands the Add Comment form, scroll to put the form in view

Here's the fragment of my Django template that achieves both of these with jQuery:

<script type="text/javascript" src="/static/jquery.js"></script> <script type="text/javascript"> function scrollTo(selector) { var targetOffset = $(selector).offset().top; $('html,body').animate({scrollTop: targetOffset}, 500); } $(document).ready(function() { $('#add_comment_toggle').click(function() { $('form.add_comment').slideToggle(); scrollTo('form.add_comment'); return false; }); {% if comment_error %} $('form.add_comment').show(); scrollTo('.comment_error'); {% endif %} }); </script>

The only bit of Django, for those who don't know it, is the {% if ... %} which only includes that Javascript if a comment_error exists.

The scrollTo function scrolls to the element whose selector is given. Notice how, if a comment_error exists, I make sure the form is showing first, then call scrollTo.

Also, in my code for toggling the Add Comment form, I call the function to scroll to the form.

by James Tauber : Created on April 28, 2008 : Last modified April 28, 2008 : Categories django web_design javascript jquery : 7 comments (permalink)