2

I have a menu with multiple jQuery toggles in it and I wanted to have jQuery toggle open one if the page URL matched. I guessed that I would need an array to keep the code short, but I know I'm doing something wrong.

$(function() {
    var pathname = window.location.pathname;
var myWhoweare = new Array("history.asp","corporate_profile.asp");

if(jQuery.inArray(pathname, myWhoweare) !== -1) {
      $('div.accordian_whoweare> div').show();
    }
});

I'm pretty sure that my error is in how the array is created (there are two URLs in it for this test, there will be more later) and detected.

Any help would be appreciated.

1 Answer 1

3

location.pathname has a forward slash as first character. Add it to the URLs in your array (and use array literal notation):

$(function() {
    var pathname = window.location.pathname;
    var myWhoweare = ["/history.asp","/corporate_profile.asp"];

    if($.inArray(pathname, myWhoweare) !== -1) {
        $('div.accordian_whoweare> div').show();
    }
});

If you are going to add more URLs, more efficient would be to use a map (or hash table, however you want to call it), realised by a JavaScript object:

$(function() {
    var pathname = window.location.pathname;
    var myWhoweare = {
        "/history.asp": true,
        "/corporate_profile.asp": true
    };

    if(myWhoweare[pathname]) {
        $('div.accordian_whoweare> div').show();
    }
});

Testing whether the URL is contained in the map will be O(1) (whereas the runtime for finding a value in the array will obviously be higher).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks very much, that worked! I knew I was missing something.
You could also ditch the leading / and do substring(1) on the pathname. +1 because I think it is a good answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.