So, im building a website and i want to give a "active" class to my menu depending on the page the user access. I'm new to Jquery, so i don't know if this is the best way to do it, or if there is a better code to achieve what i want.
Currently my main structure is:
- Header
- Navbar
where is the menu i'm giving the active class - Content
called with the php code - Footer
The only thing i need to change when loading another page, is the content it doesn't really matter if it's php or ajax. Actually, i know ajax can do it more dynamic, but i just don't know how to do it yet.
So this is the code i made to give a active class to my li a element correspondent to the webpage:
php to load page:
<?php
if(!empty($_GET['p'])){
if (file_exists ($_GET['p'].".php")){
include($_GET['p'].".php");
} else include ("erro.php");
} else include("content/home.php");
?>
Jquery to give it a class:
$(document).ready(function() {
var home = $('a[href$="home"]'),
servicos = $('a[href$="servicos"]'),
advogados = $('a[href$="advogados"]'),
escritorio = $('a[href$="escritorio"]'),
noticias = $('a[href$="noticias"]'),
contato = $('a[href$="contato"]');
$(function() {
var loc = window.location.href;
if(/home/.test(loc)) {
$('.navbar li').find(home).addClass('active');
} else if(/servicos/.test(loc)) {
$('.navbar li').find(servicos).addClass('active');
} else if(/advogados/.test(loc)) {
$('.navbar li').find(advogados).addClass('active');
} else if(/escritorio/.test(loc)) {
$('.navbar li').find(escritorio).addClass('active');
} else if(/noticias/.test(loc)) {
$('.navbar li').find(noticias).addClass('active');
} else if(/contato/.test(loc)) {
$('.navbar li').find(contato).addClass('active');
};
});
});
Is there another way or a best/easy way to do it?