0

I'm using twitter bootstrap with a menu that I'm trying to set the active class when an item is clicked. I'm able to remove and set the active class with a click event but after the header.php file loads with every new page the active class is removed. Is there a way to maintain the active class after the header file loads?

header.php

<ul class="nav menu">
    <li><a href="test-page1.php">Test Page 1</a></li>
    <li><a href="test-page2.php">Test Page 2</a></li>
    <li><a href="test-page3.php">Test Page 3</a></li>
</ul>

footer.php

<script type="text/javascript">  

$(document).ready(function() {

    $('.menu li').click(function(e) {
      $('.menu li.active').removeClass('active');
      var $this = $(this);
      if (!$this.hasClass('active')) {
          $this.addClass('active');
      }
    });

});

</script>

test-page1.php

<?php 
  include_once dirname(__FILE__) . '/header.php';
?>

    Some sample test data

<?php
  include_once dirname(__FILE__) . '/footer.php';
?>
Paul
  • 11,671
  • 32
  • 91
  • 143

2 Answers2

1

I don't know if this is the most elegant solution, but this is how I've always done it; in the header before you call the navbar you have some sort of page identifier, such as:

$pageID = 'home';

And then in the HTML, you could have it like this:

<a href="home" <?php if($pageID == 'home'){ echo 'class="active"' }; ?>>home</a>
Waxi
  • 1,641
  • 2
  • 14
  • 20
0

Here's a purely Javascript solution.

var loc = location.pathname.substring(1);
$('.menu a[href="' + loc +'"]').parent().addClass('active');

This finds your current page name and searches for a link that matches. If you are modifying your url using .htaccess, this may not be possible, or may require some tweaks to get the correct info from your url. See this link for additional options for retrieving your page name from your url.

Community
  • 1
  • 1