Dom Weldon
Dom Weldon

Reputation: 31

Changing URL hash with javascript - reverts to blank once set

I've written a class to produce a set of tabs from content in a series of nested DIVs (the site I'm working on at the moment are very reluctant to install JQuery so I can't use JQuery UI). I'm trying to incorporate a neat little feature so that when ever a user refreshes a page, the same tab stays open (this would also allow me to send a user to the relevant tab on a page from another page etc.)

My code works fine, except for when I try to change the URL's hash when a new tab is opened. At the moment, the hash changes briefly, then seemingly reverts back to blank (''). I'm having to work with Prototype and Scriptaculous, so was wondering if anyone knows whether these libraries have an automatic hash change event that I have to over-ride or something similar? Does anyone know what might be causing the problem? I'm really stumped on this one! The relevant parts of my code are below...

ff_Tabs.prototype.getSelectedTabFromHash    =   function () {
        // is there a has set?
        if (this.Selected < 0) {
            for (iTab in this.Tabs) {
                if (typeof this.Tabs [iTab] != 'function') {    
                    if ('#' + this.HashNamespace + '-' + iTab == window.location.hash) {
                        // hash refers to tab
                        return iTab;    
                    }   
                }   
            }   
        }

        // no, return to default
        if (this.Selected >= 0) {
            return this.Selected;   
        }
        else {
            return 0;       
        }
    }

ff_Tabs.prototype.changeSelectedHash    =   function (iTabId) {
    // change the has to something selected
    window.location.hash                =   '#' + this.HashNamespace + '-' + iTabId;
}

Upvotes: 3

Views: 297

Answers (2)

Dom Weldon
Dom Weldon

Reputation: 1738

This is Dom (the question poster) again - I used the wrong email address when first signing up. I've found the problem, the answer just came to me and was obvious.

I made the daft mistake of not specifying the HREF of the Anchors when I specified their onClick events. Thus, my JavaScript object changed the URL, then, once the script had finished, the browser changed it again to the HREF of the link (which was, by default, set to "#"

My apologies, this would have been impossible to spot from the first post since I did not specify the method which applies the onClick events to the anchors. The answer only came to me as I was setting up another set of tabs just now!

Needless to say the code works fine now, and if anyone would like a quick, clean little Tabs script, do get in touch!

Upvotes: 1

Shivan Dragon
Shivan Dragon

Reputation: 15219

How about instead of keeping the current opened tab in an url hash you keep it inside a cookie? This way the currently opened tab will be known nomatter what you do with the url...

Upvotes: 0

Related Questions