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.
Comments (7)
James Tauber on April 29, 2008:
Thanks Simon. Didn't know how to do that but now I do :-)
Aidas Bendoraitis on April 29, 2008:
I would rather change the Django-template-based condition to a Javascript-based condition. Then you could move all the Javascript code into a separate file:
if ($('.comment_error').length) {
$('form.add_comment').show();
scrollTo('.comment_error');
}
James Tauber on April 29, 2008:
Good point, Aidas.
Aidas Bendoraitis on May 6, 2008:
The way proposed by Simon Willison doesn't work at least with jQuery 1.2.2. The correct code for jQuery plugin is this:
{{{
(function($){
$.fn.autoscroll = function() {
jQuery('html,body').animate(
{
scrollLeft: this.offset().left,
scrollTop: this.offset().top
},
500
);
return this;
};
})(jQuery);
}}}
adam j. sontag on May 8, 2008:
ariel flesler's jQuery.scrollTo plugin...
halm on Sept. 10, 2008:
Great! perfect
Thanks :x
Last Modified: April 28, 2008
Author: James Tauber
Simon Willison on April 28, 2008:
You can neatly package your scrollTo function up as a jQuery plugin:
jQuery.fn.autoscroll = function(selector) {
$('html,body').animate(
{scrollTop: $(selector).offset().top},
500
);
}
Then to scroll to the comment error field do this:
$('.comment_error').autoscroll();