I have a hidden div with specific error messages throughout my form. Before form submit I run a validate routine to check if all the required fields are filled with some text. If not, a div with the class 'redAlert' gets visible right above the text field. I also want the dialog window to scroll right to this position when the error messages are displayed. I know there are quite a few plugins available for doing this but I want to do it using simple Jquery. I am trying to A) Find the first visible div with the class redAlert, b) Find its position by calling the .offset() on this div and then c) calling .scroll() on the window object but I am not getting this to work. Let me know if I am missing something altogether or my syntax is not valid (I've often found myself struggling with syntax error with Jquery). Below is my code. Also - this only find the visible div (assuming there is only one error div at a time) , can you please provide me the selector for finding first visible div with a particular class.
var errorDiv = $('.redAlert:visible').attr("id");
var scrollPos = $("#"+errorDiv ).offset();
//alert(scrollPosition); // This alert always says 'null', why ?
$(window).scroll(scrollPos);
//Also tried scrollTo();
Thanks much in advance.
The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. Example: Using scrollTo() to scroll to an element.
click(function() { $('html, body'). animate({ scrollTop: $("#myDiv"). offset(). top }, 2000); });
To scroll to an element on click in React:Set a ref prop on the element you want to scroll to. Set the onClick prop on the other element. Every time the element is clicked, call the scrollIntoView() method on the ref object.
var errorDiv = $('.redAlert:visible').first();
var scrollPos = errorDiv.offset().top;
$(window).scrollTop(scrollPos);
Demo: http://jsfiddle.net/Cjuve/2/
I don't think its gonna work out.
Look at the code I left behind
$('html, body').animate({
scrollTop: ($('.error').first().offset().top)
},500);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With