Forums
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Detect on what page are you with jQuery
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?
Thanks.
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.
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
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?
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?
Thank you @JohnMotylJr it help me understand a bit how it could be achieved but still I didn’t make it work. :(
you just want to add a class to the link that matches the page?
yup.
@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!
Or as a one-liner (well, after `pathname` that is…): `$(‘[href*=”‘+pathname+'”]’).addClass(‘selected’);` ;)
@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!
Any time :)
@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:
Lol indeed! Almost the same solution as well ;D