Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to the top of a modal window in javascript

My requirement is that I need to show a modal window as a form to be filled by user. But the height of that modal should be not more then window size.

So if the entries in form are too much then the modal becomes scrollable. The problem is that while validating the entries in the form the error message is shown at the top of the modal above the first entry. If user is at last property then he will not be knowing that some validation error had occurred unless the modal is scrolled to top on the error event.

I have tried :

$(window).scrollTop(); // and $('#modalId').scrollTop(); 

this is the modal code:

<div class="modal hide" id="groupModal" tabindex="-1" role="dialog" aria-hidden="true" >     <div class="modal-header">     </div>     <div class="modal-body" style="max-height: 300px;">         <div class="grpForm">             <div class="alert alert-error hide">                  <span class="errMsg"></span>             </div>             <div class="alert alert-success hide">                  <span class="successMsg"></span>             </div>             <form class = "formFieldHolder" id="groupInfoForm"></form>           </div>     </div>     <div class="modal-footer">         <button class="btn cancelFormBtn" data-dismiss="modal" aria-hidden="true" msgkey="common.cancel.label"></button>         <button class="btn btn-primary submitGroupFormBtn" type="submit" msgkey="common.submit.label"></button>          </div> </div> 
like image 963
kavinder Avatar asked Jun 04 '13 05:06

kavinder


People also ask

How do you go to top in JavaScript?

The scrollTo() method of the window Interface can be used to scroll to a specified location on the page. It accepts 2 parameters the x and y coordinate of the page to scroll to. Passing both the parameters as 0 will scroll the page to the topmost and leftmost point.

How do I scroll modal pop up?

Bootstrap 4.3 added new built-in scroll feature to modals. This makes only the modal-body content scroll if the size of the content would otherwise make the page scroll. To use it, just add the class modal-dialog-scrollable to the same div that has the modal-dialog class.


2 Answers

$('#modalId').scrollTop(0);

scrollTop() only returns the value; scrollTop(0) sets the value to 0 (all the way to the top)

like image 104
Tom Avatar answered Oct 05 '22 19:10

Tom


To scroll the page to the modal, select html, body and scroll to the offset top of the modal

$("html, body").scrollTop($("#modalId").offset().top); 

If you want to scroll the modal div to the top use

$("#modalId").scrollTop(0); 

Example on jsFiddle

You can combine both to scroll the page and the modal to a visible area for the user if needed.

References

  • jQuery scrollTop
  • jQuery offset
like image 21
BrunoLM Avatar answered Oct 05 '22 19:10

BrunoLM