Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery scroll to specific div position in case of error and focus

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.

like image 934
user1006072 Avatar asked Jan 16 '12 19:01

user1006072


People also ask

How do I scroll to a specific div?

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.

How do I smooth a div scroll?

click(function() { $('html, body'). animate({ scrollTop: $("#myDiv"). offset(). top }, 2000); });

How do you auto scroll to a specific point on a page react?

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.


2 Answers

var errorDiv = $('.redAlert:visible').first();
var scrollPos = errorDiv.offset().top;
$(window).scrollTop(scrollPos);

Demo: http://jsfiddle.net/Cjuve/2/

like image 153
Vitalii Petrychuk Avatar answered Oct 08 '22 23:10

Vitalii Petrychuk


I don't think its gonna work out.

Look at the code I left behind

$('html, body').animate({
    scrollTop: ($('.error').first().offset().top)
},500);
like image 24
arc_shiva Avatar answered Oct 09 '22 00:10

arc_shiva