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

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

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.

回答1:

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

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



回答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); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!