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 (6)
James Tauber on April 29, 2008:
Aidas Bendoraitis on April 29, 2008:
if ($('.comment_error').length) {
$('form.add_comment').show();
scrollTo('.comment_error');
}
James Tauber on April 29, 2008:
Aidas Bendoraitis on May 6, 2008:
{{{
(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:
http://flesler.blogspot.com/2007/10/jqueryscrollto.html
Add a Comment
Last Modified: April 28, 2008
Author: jtauber
Simon Willison on April 28, 2008:
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();