Reputation: 1159
So far I have this working properly for the error message only. However, I would like this to work for success message as well. This should happen when the submit button is pressed in the contact form. Click contact at the top right of the page to scroll to it.
You can test it here.
Here is the jQuery I'm using for the error message:
$(document).ready(function() {
$(".error:first").attr("id","errors");
$("#errors").each(function (){
$("html,body").animate({scrollTop:$('#errors').offset().top-175}, 1000);
});
});
Any way to modify it to work with scrolling to #success and #errors with the same offset().top-175 ?
Thanks in advance!
Upvotes: 2
Views: 6901
Reputation: 76
This solution will do the same job for Contact Form 7 (a popular form plugin for WordPress). I found this page while searching for my problem using Google, so I've added the solution below to help others who ended up on this page as well.
jQuery(function ($) {
$(document).ready(function ()
{
var wpcf7Elm = document.querySelector( '.wpcf7' );
wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
setTimeout(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $(".wpcf7-response-output").offset().top - 100
}, 500);
}, 500);
//console.log("Submited");
}, false );
});
});
Upvotes: 3
Reputation: 14025
You could do :
$(document).ready(function() {
var pos = null;
if($("#contact-form #errors.visible").length > 0)
pos = $('#errors').offset().top;
if($("#contact-form #success.visible").length > 0)
pos = $('#success').offset().top;
if(pos != null)
$("html,body").animate({scrollTop:pos-175}, 1000);
});
And fix the fact that your script "js/contact_script.js" must be declared after JQuery lib
Upvotes: 6
Reputation: 4761
$(document).ready(function () {
var $elementToScrollTo;
var $firstError = $(".error:first");
if ($firstError.length > 0) {
$firstError.attr("id", "errors");
$elementToScrollTo = $firstError;
}
else {
$elementToScrollTo = $("#success");
}
$("html,body").animate({
scrollTop: $elementToScrollTo.offset().top - 175
}, 1000);
});
Upvotes: 0