Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Adam Menczykowski
Adam Menczykowski
2,319 Points

jQuery URL check to change Nav behaviour

Hi,

I have a sub-menu which I only want to reveal when in the /gallery/ part of my website.

I have found the PURL utility which is for parsing URLs and extracting information out of them. https://github.com/allmarkedup/purl

I have written some jQuery code which is what I want to use to reveal the sub-menu but it does not work. Any tips?

var subfolder = $.url().segment(1);
function() {
  if (subfolder.contains('gallery')) {
    $('.gallery-categories').slideDown();
  }
} 

4 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Adam

You really don't need the Purl library to do this:

var subfolder = window.location.pathname.split('/')[1];
if (subfolder === 'gallery') {
    $('.gallery-categories').slideDown();
}

window.location.pathname provides everything after the protocol and domain. For example, if you're at http://domain.com/folder/subfolder/index.html window.location.pathname will return /folder/subfolder/index.html. You can use the string's split() method to split on the / character. This then produces an array like this: ['','folder','subfolder','index.html']. The item at index 1 is the name of the first level -- 'folder' You can then test to see if that element matches 'gallery'

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Adam Menczykowski

I'm not sure if this is the problem, but she string contains() method is not well supported: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/contains

Why not just try an equality operator like this:

var subfolder = $.url().segment(1);
function() {
  if (subfolder === 'gallery') {
    $('.gallery-categories').slideDown();
  }
} 
Adam Menczykowski
Adam Menczykowski
2,319 Points

Thanks for the response Dave, but that code is not working. I use mixture for preprocessing and it is saying please check your script.

I don't know if it could be the PURL at fault on the first line, not your code below?

It seems when I inspect the page in the console with just line 1 in my javascript code, subfolder is empty: subfolder: ""

This is the issue here. I need to look into why PURL is not getting the subfolder

Adam Menczykowski
Adam Menczykowski
2,319 Points

Fantastic. Thanks so much. I'll keep this one for years to come!