user3027875
user3027875

Reputation: 101

jQuery dialog close scrolls browser to top

I'm creating a jQuery dialog that can be opened and closed from many different buttons, everything is working fine, except when I close the dialog, the browser scrolls to the top. I've tried many of the suggestions online, but none seem to keep the functionality working while preventing the scroll.

I'm creating the dialog like so:

function create_hint_widget(hint_text) {
  if ($("#hint_dialog").hasClass("ui-dialog-content")) 
  {
    $("#hint_dialog").dialog("open");
    $("#hint_dialog").html(hint_text);
  }
  else
  {
    return $("<div id='hint_dialog' title='Help'>" + hint_text + "</div>")
      .dialog({
        resizable: true,
        height: 200,
        width: 300,
        modal: false,
        position: ['right', 180],
        close: function(ev, ui)
        {
          $("#hint_dialog").dialog("close");
        },
      });
  }
}

This is the Rails code to create the link calling the dialog:

 <%= link_to image_tag("hint_link.jpeg", :size=>"13x13"),
 'javascript:;', :onclick => 'create_hint_widget("Enter a name for your template. Each template must have a unique name.");
 return false;' %>

I'm using the open/close for the dialog because I want it to retain its position. event.stopPropagation(); doesn't stop the scroll and event.preventDefault(); breaks the open/close functionality. Probably most important, when I remove my close: function, it no longer scrolls on close, but some of the open/close functionality stops performing.

Upvotes: 2

Views: 1117

Answers (2)

Gergő Gyula
Gergő Gyula

Reputation: 31

Check whether you have focus on any other element than the body (e.g. an input field or button etc.) before opening the dialog. If yes, then try to get the focus back from any element before showing the dialog, something like this:

if (document.activeElement) {
    document.activeElement.blur();
}

As I presume, it jumps back to the focused item after closing.

Or, get the page scroll values before opening the dialog, just like this: JavaScript get window X/Y position for scroll and then catch the close event, and set back the scroll to the previously saved values after hiding the dialog.

Upvotes: 2

user3027875
user3027875

Reputation: 101

So the problem lies within

$("#hint_dialog").dialog("close");

I kept playing and eventually tried

$("#hint_dialog").hide();

And it no longer scrolls to the top.

Upvotes: 0

Related Questions