0

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?

3
  • 1
    I'd suggest you add the class from the backend using PHP and then having the CSS for it. Commented Apr 16, 2015 at 13:33
  • In addition to what @MrVentzi said, you can make a menu.php file which you can include on all your pages, so you don't have to copy it everywhere. There you can check what page have been visited and output the "active" class. Commented Apr 16, 2015 at 13:36
  • The reason why i'm doing this with jquery is because i want to make it more dynamic, so even the navigation trought the pages doesn't need to be with php. I know ajax can do this, but i just didn't found anything to show me how. I just need to replace the content on the page, not the header, menu and footer. Commented Apr 16, 2015 at 13:42

2 Answers 2

1

Since you are using jQuery, take a look at jQuery's load function. Using load you can specify an html element(usually div) in which you will load pages, like this:

$("#myDiv").load("/my/page/folder/page.html");

To handle the menu you will need this piece of code:

// Select all menu links and attack event handler on them
$(".navbar li a").on("click", function(event){
  // This stop the link from loading into the browser tab(we want it to load in a div)
  event.preventDefault();
  // Remove any previous highlight
  $(".active").removeClass("active");
  // Add highlight to the menu we clicked
  $(this).addClass("active");
  // Load the link into "myDiv"
  $("#myDiv").load(this.href);
});

You may need to tweak around with this code, i haven't tested it, but this is how it works in general.

Note: in the pages you load, using jQuery's load function, you need only the content and not the whole HTML structure.

If you want to load only part of the page you can do so like this:

$("#myDiv").load("/my/page/folder/page.html #container");
Sign up to request clarification or add additional context in comments.

2 Comments

This is working just fine! Just what i was looking for. I was trying to find something like this and i ended with another 'problem' to change the URL based on the link i click, in case the user want to share the page, etc.. I read something about pushState() to do that. Do you know how to fit this with my navigation in order to keep the webpage url updated with the proper link?
Have in mind that not every browser supports push state. There is a trick you might use to always have the correct link in your URL. You can use anchors. For example example.com/index.html#/my/page/folder/page.html . Then you can load pages using $("#myDiv").load(document.location.hash.slice(1)); What this code does is take the anchor(hashtag) and remove the hash from it, to receive the URL we want. Then it loads the url in our container. When you have this, just make your links href="#/my/page/folder.page.html" and it should work. P.S. Please mark an answer as accepted if it works.
1

Your method of page's inclusion is extremely dangerous as I can basically access any php file on your server.

I would recommend to use an array that contains all the allowed pages, like:

$pages = array('home', 'about', 'contact');
$current_page = '';

//Default page
if(!isset($_GET['p']) || empty($_GET['p'])){
$current_page = 'home';
}

Now, when you print the menu, you can do something like this:

foreach($pages as $page){
echo '<li><a href=""';
if($page == $current_page) echo ' class="active"';
echo '></a></li>';
}

You can expand your array of pages to contain also title, meta tags, etc. For instance:

$pages = array(
'home' => array('title' => 'Home', 'meta_description' => 'Bla Bla Bla'),
'about' => array('title' => 'About Us', 'meta_description' => 'Bla Bla Bla')
);

1 Comment

I update my question. I understand what you said, but i think for this project it would be better to keep with jquery because it's a simple website with just some info and news from a company.

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.