Give help. Get help.

  • # March 17, 2013 at 5:25 pm

    Hi folks,

    I need little help with detecting what page user is at so jQuery sets class to different element. This I wish to use for main navigation, so i don’t have to edit html – set/erase class from elements. Can anyone help?


    # March 17, 2013 at 5:27 pm

    What do you want to detect, actually? The page name? Page URL? Filename? The value of the H1 element? It really depends on your page structure how you want to do this, so we’ll need to see your site.

    # March 17, 2013 at 5:41 pm

    File name I think will be most appropriate like index.html, contact.html…? But URL, page title will be fine too.

    EDIT: and navigation is structured nav/ul/li/a

    # March 17, 2013 at 5:45 pm

    Is it possible that if a’s href value “index.html” matches file name of the page you are on – “index.html” class is added to a?

    # March 17, 2013 at 6:21 pm


    Hey, I didn’t have a lot of time cuz i gotta go make dinner lol… But i had to play with something..

    Maybe this will get you on track?

    # March 17, 2013 at 8:01 pm

    Thank you @JohnMotylJr it help me understand a bit how it could be achieved but still I didn’t make it work. :(

    # March 17, 2013 at 8:14 pm


    you just want to add a class to the link that matches the page?

    # March 17, 2013 at 8:17 pm


    # March 17, 2013 at 8:25 pm


    Updated CodePen

    # March 17, 2013 at 8:55 pm

    @JohnMotylJr Thank you man i owe you a drink. Still i had to change one line to make it work. Your code works in Codepen but don’t works in browsers with this line it’s vice versa.

    a = a.substring(a.lastIndexOf(‘/’));

    Thanks again! Cheers!

    # March 17, 2013 at 9:48 pm

    Or as a one-liner (well, after `pathname` that is…): `$(‘[href*=”‘+pathname+'”]’).addClass(‘selected’);` ;)

    # March 17, 2013 at 9:50 pm

    @VladimirKrstic of course man, that’s why these forums ROCK!

    @CrocoDillon FTW!! Good add man, i’ve never had to do that before so its nice to see your implementation. Thanks!

    # March 17, 2013 at 9:54 pm

    Any time :)

    # March 17, 2013 at 10:00 pm

    @VladimirKrstic, @CrocoDillon, So i was browsing the snippets section and just realized that Chris Coyier posted a snippet for this EXACT situation lol… Figured i would provide the link for future reference:

    Add Active Navigation Class Based on URL

    # March 17, 2013 at 10:09 pm

    Lol indeed! Almost the same solution as well ;D

Viewing 15 posts - 1 through 15 (of 16 total)

You must be logged in to reply to this topic.