I have a lot text boxes in a form that get a class added to them when submitted
then that class gets a :first
selector along with .focus()
to focus on the text box that didn't receive any input but it cutoffs the message above the text box.
So how do I move the scr开发者_StackOverflow社区oll bar in conjunction with the .focus()
on text box?
Something like this is what you're after right?
$(function() {
$('input, textarea').each(function() {
var os = $(this).offset().top;
$(this).bind('focus', function() {
$('html,body').animate({scrollTop: os}, 300);
});
});
});
When you focus either an input or a textarea it will scroll to it.
Here's a fiddle of it in action: http://jsfiddle.net/fExhw/
EDIT
$(function() {
$('#submit').click(function(e) {
e.preventDefault();
$('input').each(function() {
if($(this).hasClass('error')) {
var firstError = $('.error:first');
$('html,body').animate({scrollTop: firstError.offset().top}, 300);
firstError.focus();
}
});
});
});
http://jsfiddle.net/fExhw/1/ (hit the submit button at the bottom)
Ok updated it to what I think you're after.
Have you used jQuery.scrollTo? I've had great luck with it solving similar tasks.
In the textbox's focus
eventhandler, get the textbox's coords and use jQUery scrollLeft/scrollTop
to scroll the page accordingly.
Example (starting point, may need refinement):
function scrollToTextbox(id) {
var coords = $('#' + id).offset();
$(document).scrollLeft(coords.left);
$(document).scrollTop(coords.top);
}
Note: You may have to adjust the scroll a bit (either by adding few pixels or by subtracting) based on how markup and styling is used in your page.
精彩评论