Showing posts with label active. Show all posts
Showing posts with label active. Show all posts

Wednesday 23 March 2016

Dynamically make items active in Twitter Bootstrap navigation using jQuery

Here, I have created a jQuery plugin. It takes as its parameter the elements containing navigation items from a Twitter Bootstrap page. The plugin then matches the page URL with a navigation item and makes it active.
Find the code here.

Friday 20 February 2015

Match the current URL with the responding navigation items of a Twitter Bootstrap site

So, you've got a Twitter Bootstrap website and you want the navigation items to become active when you're in the corresponding page. Below I wrote the jQuery plugin to do just that.
First the HTML
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <title>jQuery navigation plugin for bootstrap</title>
    <link href="bootstrap-3.3.2-dist/css/bootstrap.min.css" rel="stylesheet">      
  </head>
  <body>
    <nav class="navbar navbar-default">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1">
            Menu          
          </button>
          <a class="navbar-brand" href="#"><span class="glyphicon glyphicon-education" aria-hidden="true"></span></a>
      </div><!-- .navbar-header -->
      <div class="collapse navbar-collapse" id="navbar-collapse-1">
        <ul class="nav navbar-nav">
          <li><a href="index.html">Home</a></li>
          <li><a href="irrigation.html">Irrigation</a></li>
          <li><a href="pump.html">Pump</a></li>
        </ul>
      </div><!-- #navbar-collapse-1 -->
    </div><!-- /.container -->
  </nav>
    <script src="jquery/1.11.2/jquery.min.js"></script>  
    <script src="bootstrap-3.3.2-dist/js/bootstrap.min.js"></script>  
    <script src="js/matchactive.plugin.js"></script>
    <script>
    (function()
    {
       $('ul.nav > li > a').matchactive();
    }();
    </script>
  </body>
</html>

And now the matchactive.plugin.js
(function($)
{
    $.fn.extend(
    {
        matchactive:function(getvar)
        {
            var pathArray = window.location.pathname.split( '/' );
            var sn = pathArray[pathArray.length - 1];
            var setOfAnchors = $(this);
            $(setOfAnchors).each(function()
            {
            if($(this).attr('href') == sn)
            {
            $(this).parent().addClass('active');
            }
            });
        }
    });
})(jQuery);