Skip to content

Instantly share code, notes, and snippets.

@0xgdr
Created November 16, 2019 12:38
Show Gist options
  • Select an option

  • Save 0xgdr/11eee91e6e990e0558ed233e30dbc8df to your computer and use it in GitHub Desktop.

Select an option

Save 0xgdr/11eee91e6e990e0558ed233e30dbc8df to your computer and use it in GitHub Desktop.
Using JavaScript To Access URL Segments :: 2012-06-19

Whilst working on a recent project, I wanted an accordion navigation to remain open depending on what the category segment in the url was displaying. To do this I found a simple bit of JavaScript published on CSS-Tricks which looks like this:

Get the full URL path:

var newURL = window.location.protocol + "://" + window.location.host + "/" + window.location.pathname;

Next split the segments of the URL using:

var pathArray = window.location.pathname.split( '/' );

Finally select the segment you require using:

var segment_1 = pathArray[1];

The above code would select segment_1 but you can see how you can easily select segment_2,segment_3 etc.

Once these segments are stored in variables it is really easy to set states for your navigation using jQuery.

if (segment_2 == "category") {
    $(nav).find('li ul:not(:first)').hide();
}

If you like this article and want to learn more about Javascript, I have started a series of posts on CodPen.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment