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:

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.

The original post was in the categories: django web_design javascript jquery but I'm still in the process of migrating categories over.

The original post had 7 comments I'm in the process of migrating over.