2

! Latest I've tried. I put it in my head.php which I just include. I'll send over my files if you'd want to see them personally. Directory of my folder

Main_Folder
-Main_files
-- JS_Folder
---- Js Files
-- Includes_Folder
---- Head.php is here


<script type="text/javascript">
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
//alert($('ul a').length);
$('ul a').each(function() { 
    if (this.href === path) {
        $(this).addClass('sub-menu active');
    }
    //alert(this.href);
});
}); 
</script>

Whole sidebar:

 <div class="sidebar-scroll">
<div id="sidebar" class="nav-collapse collapse">
 <!-- BEGIN SIDEBAR MENU -->
  <ul class="sidebar-menu">
          <li class="sub-menu">
              <a class="" href="panel-admin.php">
                  <i class="icon-dashboard"></i>
                  <span>Dashboard</span>
              </a>
          </li>
          <li class="sub-menu">
              <a href="javascript:;" class="">
                  <i class="icon-briefcase"></i>
                  <span>Employees</span>
              </a>
          </li>
          <li class="sub-menu">
              <a href="javascript:;" class="">
                  <i class="icon-book"></i>
                  <span>Students</span>
              </a>
          </li>
          <li class="sub-menu">
             <a href="javascript:;" class="">
                  <i class="icon-calendar"></i>
                  <span>Scheduling</span>
                  <span class="arrow"></span>
              </a>
              <ul class="sub">
                  <li><a class="" href="admin-foreign.php">Foreign Languages</a></li>
                  <li><a class="" href="admin-esl.php">ESL Local</a></li>
                  <li><a class="" href="admin-workshop.php">Summer Workshops</a></li>
              </ul>
          </li>
          <li class="sub-menu">
              <a href="javascript:;" class="">
                  <i class="icon-pencil"></i>
                  <span>Enroll</span>
                  <span class="arrow"></span>
              </a>
              <ul class="sub">
                  <li><a class="" href="general.html">Foreign Languages</a></li>
                  <li><a class="" href="button.html">ESL Local</a></li>
                  <li><a class="" href="slider.html">Summer Workshops</a></li>
              </ul>
          </li>

      </ul>
 <!-- END SIDEBAR MENU -->

class="sub-menu" is needed to make it dropdown menus drop. So the active version is class="sub-menu active". In case of a 2 level dropdown menu, both the main bar and sub bar are to be set to active.



This is my side bar.

<div class="collapse navbar-collapse navbar-ex1-collapse">
        <ul class="nav navbar-nav side-nav">                    
            <li>
                <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a>
            </li>
            <li>
                <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a>
            </li>
        </ul>
    </div>

I've tried the following below but none works on my case:

Update class attribute based on page URL

https://css-tricks.com/snippets/jquery/add-active-navigation-class-based-on-url/


First sample code

$('.menu li a').each(function(){ //check thru all <a> elements inside <li> inside .menu

  var pagename= location.pathname.split('/').pop(); // get current pages filename (just filename)

    if($(this).prop("href") == pagename){
        $('.menu li').removeClass("active"); // remove all active class    
        $(this).parent("li").addClass("active"); //put active in parent of <a> which is <li>
   }
});

In the first one, I've changed the menu to collapse navbar-collapse navbar-ex1-collapse and collapse only but neither works.


In the second sample code, I've tried doing the following:

$(function() {
  $('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active');
});

I put [2] since I'm currently in the localhost. So it would be localhost/folder_name/index.php.

I also tried putting "/index.php"/ but when I click that it directs me to localhost/index.php instead of localhost/folder_here/index.php.


Third sample code

jQuery(function($) {
 var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
 $('ul a').each(function() {
  if (this.href === path) {
   $(this).addClass('active');
  }
 });
});

Still doesn't work. I've change $('ul a) to $('div ul a) and $('div li ul a).


EDIT: Just to be sure, the script created is just included by include('js/js_file.js');. This line should be before or after the html is loaded?

As suggested by David Thomas I've tried the following below. But it doesn't work.

var url = 'window.location.pathname';
$('.nav a').each(function() {
  // get the absolute URL from the <a> element:
  var href = this.href,
    // get the current page and file-type:
    pageAndFile = href.split('/').pop();
  // if the location ends with the pageAndFile found in
  // the current <a> element (using String.prototype.endsWith())
  // we add the 'active' class-name:
  if (url.endsWith(pageAndFile)) {
    $(this).closest('li').addClass('sub-menu active');
  }
});
Community
  • 1
  • 1
Dev
  • 1,592
  • 2
  • 22
  • 45
  • I feel like `location.pathname.split("/")[2]` should be `location.pathname.split("/")[1]` as your href appears to be pointing to the root "/". – KJ Price Apr 29 '15 at 16:10
  • Ohh yeah. I misunderstood the example code. But still doesnt work. – Dev Apr 29 '15 at 16:13

3 Answers3

1

One approach:

// obviously, use 'document.location'/'window.location' in the real thing:
var fakeLocation = 'http://www.example.com/index.php';

$('.nav a').each(function() {
  // get the absolute URL from the <a> element:
  var href = this.href,
    // get the current page and file-type:
    pageAndFile = href.split('/').pop();
  // if the location ends with the pageAndFile found in
  // the current <a> element (using String.prototype.endsWith())
  // we add the 'active' class-name:
  if (fakeLocation.endsWith(pageAndFile)) {
    $(this).closest('li').addClass('active');
  }
});
.active {
  border: 1px solid red;
}
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
  <ul class="nav navbar-nav side-nav">
    <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a>

    </li>
    <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a>

    </li>
  </ul>
</div>

JS Fiddle demo.

For those browsers that don't implement String.prototype.endsWith():

// simple shim for String.prototype.endsWith(), for browsers that
// don't yet implement the same:
String.prototype.endsWith = String.prototype.endsWith || function(testString) {
  // creates a regular expression from the passed-in string, followed by the '$'
  // character which signifies that the passed-in string must be followed by the
  // end-of-string:
  var reg = new RegExp(testString + '$');

  // using RegExp.prototype.test() to test that the String we're testing,
  // the 'this,' is matched by the created regular expression:
  return reg.test(this);
};

var fakeLocation = 'http://www.example.com/index.php';

$('.nav a').each(function() {
  // get the absolute URL from the <a> element:
  var href = this.href,
    // get the current page and file-type:
    pageAndFile = href.split('/').pop();
  // if the location ends with the pageAndFile found in
  // the current <a> element (using String.prototype.endsWith())
  // we add the 'active' class-name:
  if (fakeLocation.endsWith(pageAndFile)) {
    $(this).closest('li').addClass('active');
  }
});
.active {
  border: 1px solid red;
}
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
  <ul class="nav navbar-nav side-nav">
    <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a>

    </li>
    <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a>

    </li>
  </ul>
</div>

JS Fiddle demo.

And, without jQuery, you could do much the same:

// simple shim for String.prototype.endsWith(), for browsers that
// don't yet implement the same:
String.prototype.endsWith = String.prototype.endsWith || function(testString) {
  var reg = new RegExp(testString + '$');
  return reg.test(this);
};

// again, in real-world non-demo use you should use 'document.location':
var fakeLocation = 'http://www.example.com/index.php',
  // finding the last portion of the fakeLocation variable:
  currentPage = fakeLocation.split('/').pop(),
  // getting all the a elements with an href attribute that ends
  // with the currentPage string (after escaping the special
  // characters with the (ugly) regular expression) and the
  // attribute-ends-with ('attribute$=value') selector:
  activeAElements = document.querySelectorAll('.nav a[href$=' + currentPage.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + ']');

// using Array.prototype.forEach to iterate over the array-like
// activeAElements NodeList:
Array.prototype.forEach.call(activeAElements, function(a) {
  // the first argument of the function is the array-element,
  // here an <a> element node;
  // we're adding the 'active' class-name to the parentNode of any <a>
  // element that was found by the above selector:
  a.parentNode.classList.add('active');
});
.active {
  border: 1px solid red;
}
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
  <ul class="nav navbar-nav side-nav">
    <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a>

    </li>
    <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a>

    </li>
  </ul>
</div>

JS Fiddle demo.

As to why your own attempts failed:

$('.menu li a').each(function(){

  var pagename= location.pathname.split('/').pop();

    // the HTMLAnchorElement.href is the absolute URL formed
    // by the href attribute; to find the actual string from
    // an <a> element, you'd need to use either JavaScript:
    //  - this.getAttribute('href');
    // or jQuery's:
    //  - $(this).attr('href'); 
    if($(this).prop("href") == pagename){
        $('.menu li').removeClass("active");
        $(this).parent("li").addClass("active");
   }
});

Your second attempt:

$(function() {
  // this won't work because your JavaScript will return 'index.php',
  // and pass that into the attribute selector; unfortunately this
  // includes the period ('.'), which is a special character in CSS
  // and has to be double escaped, first for the JavaScript and then
  // the CSS
  $('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active');
  // with that in mind, you'd need to do (something like) the following,
  // which - as in my own code - replaces all special characters with
  // a double-escaped version of that character (so '.' becomes '\\.'):
  $('nav a[href^="/' + location.pathname.split("/")[2].replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + '"]').addClass('active');
});

Your third attempt:

jQuery(function($) {
 var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
 $('ul a').each(function() {
  if (this.href === path) {
   $(this).addClass('active');
  }
 });
});

Looks like it should work, albeit you're adding (or should be adding) the 'active' class-name to the <a> element, rather than the ancestor <li> element.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

Assuming location.pathname.split("/")[2] returns the expected parameter, the problem is

$('nav a[href^="/'

should be

$('.nav a[href^="'

.nav is a class, not an element, in your example

Ted
  • 14,757
  • 2
  • 41
  • 58
  • I've tried it. Having the `"/...php/"` and `".php"`. But doesn't work. – Dev Apr 29 '15 at 16:12
  • @iamDevlin remove the '/' as well, i assume `location.pathname.split("/")[2]` returns 'index' or 'employee' – Ted Apr 29 '15 at 16:13
  • I already change `[2]` to `[1]` as stated by KJ Price but still doesnt work. – Dev Apr 29 '15 at 16:16
  • @iamDevlin what does `console.log('.nav a[href^="' + location.pathname.split("/")[2] + '"]')` return? And what is the page url? – Ted Apr 29 '15 at 16:41
  • It seems to do nothing. Not quite sure what I am doing wrong or where to put it. – Dev Apr 29 '15 at 16:45
  • @iamDevlin than change `console.log` to `alert`. The console is in the developer tools in most browsers. F12 in most. – Ted Apr 29 '15 at 16:48
  • console.log('.nav a[href^="' + location.pathname.split("/")[2] + '"]') .nav a[href^="employee.php"] undefined – Dev Apr 29 '15 at 16:52
  • Well, that looks like it is returning the correct selector. Can you verify that the element doesn't have the class added? (in Chrome, F12, click the magnifying glass and then the link on screen that should have the `active` class) – Ted Apr 29 '15 at 16:59
  • Nothing added. I also tried putting `class=""` just in case. – Dev Apr 29 '15 at 17:02
  • No javascript errors in the console? At this point, I'd have to see it in action to figure out whats wrong with it. – Ted Apr 29 '15 at 17:07
  • I created a fiddle and it seems to work fine...[see it here](http://jsfiddle.net/p53byaxj/12/) – Ted Apr 29 '15 at 17:19
0

problem in your script......

$(function() {
    $('.nav a[href^="' + location.pathname.split("/")[2] + '"]').addClass('active');t
});
blurfus
  • 13,485
  • 8
  • 55
  • 61
Sagar Naliyapara
  • 3,971
  • 5
  • 41
  • 61