views:

178

answers:

2

I need to be able to open an ID'd jQuery UI Modal on a page when that modal's ID is passed in the page's URL. For example:

http://mysite.com/visit.html#directions

#directions is an ID'd DIV at the very bottom of the page, right before the closing BODY element. It's instantiated as a jQuery UI dialog on page load, then I'm running a function to check the current URL for the modal's ID. If the URL contains the modal's ID, the modal is opened.

Here's what my auto-open function looks like:

function autoOpenModal() {
    if ( document.location.href.indexOf('#') ) {
        var uriParts = document.location.href.split('#');
        var hashID = '#' + uriParts[1];
        if ( $(hashID) && $(hashID).hasClass('dialog')) {
            $(hashID).dialog('open');
        }
    }
}

The problem I'm having is that the browser is automatically scrolling down to the ID at the very bottom of the page before the modal is opened. So when the user closes the modal they're at the bottom of the page (which seems "broken" to me).

Can anyone tell me how I stop the browser from auto-scrolling down to the ID please? I've had a look at event.preventDefault() but without success; I'm not sure where or how to use it in the event chain.

A: 

Try returning false from within your autoOpenModal() function:

function autoOpenModal() {
    if ( document.location.href.indexOf('#') ) {
        var uriParts = document.location.href.split('#');
        var hashID = '#' + uriParts[1];
        if ( $(hashID) && $(hashID).hasClass('dialog')) {
            $(hashID).dialog('open');
        }
    }
    return false;
}
karim79
Thanks for the suggestion, karim. But I tried that already and it doesn't seem to work. I think it's because the browser "jumps" down through the markup before it executes the document.ready() event.
markedup
A: 

If this is your URL "http://mysite.com/visit.html#directions" the web browser should always jump to "directions" as that is what is being asked of it. Instead of using "#" maybe you could use a query string.

http://en.wikipedia.org/wiki/Query_string