Apply a class based on the page

I need to apply a class “.selected” to a navigation item when the user is on the corresponding page, so that when the user clicks on “Products”, it goes to the products page but the Products nav item remains selected. How can I accomplish this using jQuery? I suppose I would need to get the URL of the …

via Css Website development » Search Results » ajax:

Apply a class based on the page

I need to apply a class “.selected” to a navigation item when the user is on the corresponding page, so that when the user clicks on “Products”, it goes to the products page but the Products nav item remains selected. How can I accomplish this using jQuery? I suppose I would need to get the URL of the page an apply the style to the corresponding nav item, correct?
…………………………………

Here is a simple example, if you wish to match the entire URL (‘http://example.com/mydir/mypage.html’):
$(function()
var url = window.location;
$(‘a[href=”‘ + url + ‘”]‘).addClass(‘selected’);
);Or, to match the path (‘/mydir/mypage.html’):
$(function()
var url = window.location.path;
$(‘a[href=”‘ + url + ‘”]‘).addClass(‘selected’);
);
…………………………………

I assume that you’ll be doing some sort of AJAX system where you won’t be reloading the menu on every click, otherwise this should definitely be done server side. If not, you can use the following
HTML

  • menu
  • menu
  • menu

???Javascript:
$(‘ul#main > li’).click(function()
$(‘ul#main > li.selected’).removeClass(‘selected’);
this.setAttribute(‘class’,’selected’);
?????????);?Here’s a link to try it out: http://jsfiddle.net/6zpJX/
…………………………………

assuming the element you want styled .selected has an id same as the html file currently in the browser:
$(document).ready(function() {

var page = window.location.href.match(//(w+).htm/)[1];
$(‘#’ + page).addClass(‘selected’);

For more info: Apply a class based on the page

Css Website development » Search Results » ajax

Apply a class based on the page

Share this post:

Related Posts

Leave a Comment