31

I currently use jTemplates to create a rather large table on the client, each row has a button that will open a jQuery UI dialog. However, when I scroll down the page and click on one of those buttons, jQuery dialog will open, but the scroll position get lost and the page jumps back to the top (with the blocking and the actual dialog showing off the screen). Has anyone seen or know what might cause this problem?

Thanks.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
Kiwik
  • 355
  • 1
  • 3
  • 6
  • Seen this before but then I've used the following plugin to ensure scroll position isn't lost http://plugins.jquery.com/project/ScrollTo – S Philp Jul 20 '09 at 21:08

4 Answers4

73

Are you using an anchor tag to implement the "button" that pops the dialog? If so, you'll want the click handler that opens the dialog to return false so that the default action of the anchor tag isn't invoked. If you are using a button, you'd also need to make sure that it doesn't submit (by returning false from the handler) and completely refresh the page.

For example,

$('a.closeButton').click( function() {
     $('#dialog').dialog('open');
     return false;
});


<a class='closeButton'>Close</a>
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • 1
    I had the same problem when using angularjs and after wasting a few hours found that href attribute should be avoided when using [ng-click](http://docs.angularjs.org/api/ng.directive:ngClick). – Ritesh Sep 19 '13 at 21:36
  • @Ritesh there's really no need for it here anyway. I've removed. – tvanfosson Sep 20 '13 at 13:22
  • 1
    ok. If you remove href attribute then the mouse cursor wouldn't show up and you may need to do some styling. It is not a problem in case of angularjs, which handles it automatically. – Ritesh Sep 20 '13 at 22:02
  • @Ritesh well, it's a "button" so I assumed you'd be doing some styling, including changing the mouse pointer, anyway. – tvanfosson Sep 21 '13 at 02:40
13

If your buttons work with an html anchor tag with href="#" replace the href for example by href="javascript:;" or any other method that you use to disable the href. The reason why the scrolling happens is because of href="#" scrolls to the top of your page.

7

change your code like this

$('a.closeButton').click( function(e) {
    e.preventDefault();
     $('#dialog').dialog('open');
});
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • I use them to load content via ajax and was having the same issue. When I was scrolled down a page and opened a dialog, then closed it the page would 'jump' back to the top. The scrollTo plugin was more involved than I needed, the above worked perfectly. – Dirty Bird Design Feb 14 '11 at 14:38
  • Very good answer. Just make sure dialog has $.post() or $.ajax() if you plan to carry out an action. – DMadden51 Apr 16 '18 at 14:46
-2

You can try :

scrollTo(0, jQuery("body"));
Mehdi Chaouch
  • 425
  • 4
  • 7