Instead of pasting $(‘html, body’).animate({ scrollTop: 0}, 2500); for every input, can I write it only once to work for all inputs?
Whats happening is my screen is scrolling to the top several for every event in the script and I can’t scroll down anymore.
Thanks.
$(function () {
$('#rbSubmit').formValidator({
scope: '#form_register',
onError: function () {
if ($('#input_2 input').hasClass('error-input')) {
$('#r2 div, #r2 input').css('background-color', '#C1272D').css('color', '#FFF');
$("#error-div").show();
$('html, body').animate({
scrollTop: 0
}, 2500);
} else {
$('#r2 div').css('background-color', '#2F2F2F');
$("#error-div").hide();
}
if ($('#input_3 input').hasClass('error-input')) {
$('#r3 div, #r3 input').css('background-color', '#C1272D').css('color', '#FFF');
$("#error-div").show();
$('html, body').animate({
scrollTop: 0
}, 2500);
} else {
$('#r3 div').css('background-color', '#2F2F2F');
$("#error-div").hide();
}
if ($('#input_7 input').hasClass('error-input')) {
$('#r7 div,#r7 input').css('background-color', '#C1272D').css('color', '#FFF');
$("#error-div").show();
$('html, body').animate({
scrollTop: 0
}, 2500);
} else {
$('#r7 div').css('background-color', '#2F2F2F');
$("#error-div").hide();
}
if ($('#input_10 textarea').hasClass('error-input')) {
$('#r10 div').css('background-color', '#C1272D').css('color', '#FFF');
$("#error-div").show();
$('html, body').animate({
scrollTop: 0
}, 2500);
} else {
$('#r10 div').css('background-color', '#2F2F2F');
$("#error-div").hide();
}
}
});
});
Theres no way for me to test this as I don’t have your markup or anything.. but I think you could really reduce the code your using by doing something like the following.
Basically it checks all the inputs and checks if they have the error class, if so grabs the number (since you are referencing numbers in your id’s not a good practice by the way). It then selects the related elements and does what it needs to do although I think this could be improved by selecting them based upon their position related to the errored input in the document. After all of that, if there was an error in any of them it sets a flag, and performs the animation.