3

I've browsed a few other questions on here with getting current page url with jQuery and/or plain javascript but I have been having no luck.

My goal is this: depending on what page the user is on, I want a border under that menu item. This is how I am attempting to do it:

var urlHome = 'http://example.com/'
var urlShop = 'http://example.com/shop/'
var urlTeam = 'http://example.com/team/'

if (document.url.is(urlHome)) {
    $('#home-link').css('border-bottom', '1px solid #000');
}
else if (document.url.is(urlShop)) {
    $('#shop-link').css('border-bottom', '1px solid #000');
}
else if (document.url.is(urlTeam)) {
    $('#team-link').css('border-bottom', '1px solid #000');
};

Unfortunately this code isn't working for me, I'm open to any and all suggestions, thank you in advance for your help.

4
  • 1
    try if (document.url == urlHome) etc.... .is is a jquery function Commented Feb 13, 2015 at 16:55
  • 1
    JavaScript is case sensitive, and doesn't have an is function. document.URL === urlHome should work. Commented Feb 13, 2015 at 16:56
  • I think you might need document.location.href Commented Feb 13, 2015 at 16:56
  • And if you store that in a variable you can pass it like this var _href = document.location.href; if (_href === 'example.com/shop/') {execute code etc. Commented Feb 13, 2015 at 16:58

2 Answers 2

3
var loc = window.location.href,id="";
     if (loc === urlHome) id = "home";
else if (loc === urlShop) id = "shop";
else if (loc === urlTeam) id = "team";
if (id) $('#'+id+'-link').css('border-bottom', '1px solid #000');

This works for me, with my own variables of course :)

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

5 Comments

Thank you, i thought .is was the same as ===
Please only load the href once and set css once
@mplungjan : I'm not 100% sure what that would change. Would copying the href value into a separate variable and checking that instead of the original be better? Feel free to edit the code.
Ok, changed it to a less verbose version
Thank you, it's nice to know there's always something one can learn :)
2

Just do

if(document.URL == urlHome)
{
// Whatever
}

2 Comments

Thank you! I didn't know there was a difference between == and .is
Anytime, Dont forget to mark it as correct answer... Cheers!

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.