Showing posts with label dynamic. Show all posts
Showing posts with label dynamic. Show all posts

Monday 8 December 2014

Dynamically activate navigation items in Bootstrap using my jQuery plugin

My challenge was to write a piece of jQuery which:

  • Takes note of the page path.
  • Compares it with the Bootstrap navigation.
  • Makes the navigation element 'active' to remind the users where they are in relation to the site.

First the HTML. Notice, that I have not set any navigation item as active. The plugin will do this. The plugin call is in red.
<!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>Activate Navigation Entry</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <nav class="navbar navbar-default" role="navigation">
      <div class="container">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Brand</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav">
            <li><a href="index.php">Home</a></li>
            <li><a href="about.php">About</a></li>
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a>
              <ul class="dropdown-menu" role="menu">
                <li><a href="action.php">Action</a></li>
                <li><a href="anotheraction.php">Another action</a></li>              
              </ul>
            </li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container -->
    </nav>
    <div class="row">
      <div class="container">
        <div class="col-md-12">
          <h1>Home</h1>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
    <script src="activatenav.plugin.js"></script>
    <script>
    (function()
    {
      $(document).activatenav(
      {
        toplevel:'ul.nav.navbar-nav > li > a',
        dropdown:'ul.nav.navbar-nav > li.dropdown > ul.dropdown-menu > li > a'
      });
    })();
    </script>
  </body>
</html>
Next the jQuery plugin named 'activatenav.plugin.js'.
First calculate the end of the path. If there is no name, it must be the home page, so set that as active.
I also check if the current page is from the drop down menu. If so, set both the drop down heading and the corresponding navigation item as 'active'.
(function($)
{
    $.fn.extend(
    {
        activatenav:function(options)
        {
        var pname = window.location.pathname;
        var pArr = pname.split('/');        
            var defaults =
            {
                toplevel:'',
        dropdown:''
            };
            options = $.extend(defaults, options);
if(options.toplevel)
{
handled = $(this).handleTopLevel(options.toplevel, pArr[pArr.length-1]);
if(handled == false)
{
$(this).handleDropdown(options.dropdown, pArr[pArr.length-1]);
}
}
        }
    });

    $.fn.handleTopLevel = function(str, pth)
    {
    var hd = false;  
    if(!pth)
    {
    $(str).first().parent().addClass('active');
    }
    else
    {
    $(str).each(function()
    {
    if($(this).attr('href') == pth)
    {
    $(this).parent().addClass('active');
    hd = true;
    }    
    });
    }
    return hd;  
    };

    $.fn.handleDropdown = function(str, pth)
    {
        $(str).each(function()
    {
    if($(this).attr('href') == pth)
    {
    $(this).parent().addClass('active');
    $(this).closest('li.dropdown').addClass('active');
    }    
    });
    };
})(jQuery);

Friday 17 June 2011

Using PHP to create a dynamic page navigation based on filenames

Here is the problem. You create a bunch of pages. You want to highlight the current page within the navigation. You don't want to manually change the navigation elements to each page.

See demo.

In the example below I create an associative array which contains two elements:

  1. The name of the page which the navigation points to.
  2. The name which should appear in the navigation.

I then grab the filename of the of the current page in the browser.
I then traverse the associative array, each time comparing the filename against the current file shown in the browser, each time creating an anchor using the values.

If array filename and current page filename are the same, then I add a CSS ID to the anchor tag.

You will need to write a little CSS to highlight the current page anchor such as:

nav a#activeMenuItem
{
background:#EEEEEE;
}


But other than that, it works like a charm. Have fun!


<nav>
<?php
$navArray = array('index.php'=>'home', 'services.php'=>'services','portfolio.php'=>'portfolio','contact.php'=>'contact');
$fileName = substr(strrchr($_SERVER['SCRIPT_NAME'],47),1);
foreach($navArray as $fname => $linktitle)
{
echo '<a href="'.$fname.'"';
if($fname==$fileName)
{
echo ' id="activeMenuItem"';
}
echo '>'.$linktitle.'</a>';
}
?>
</nav>

Friday 10 June 2011

Fittext - Not bad

I came across a great new jQuery plugin today. Namely FitText. I've done dynamic text resizing myself before, but this seems like a better implementation. To test it, resize your browser.

See demo.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>FitText</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
h1
{
font-size:4em;
color:red;
line-height:1.5em;
}
h2
{
font-size:3em;
color:orange;
line-height:1em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script src="scripts/jquery.fittext.js"></script>
<script>
$(document).ready(function()
{
$('.fittext').fitText();
});
</script>
</head>
<body>
<header><h1 class="fittext">Header 1</h1></header>
<section id="mainContent">
<h2 class="fittext">It's all in the detail</h2>
<article>
<p class="fittext">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
</article>
</section>
<footer>Footer</footer>
</body>
</html>

Wednesday 23 March 2011

Resize chosen fonts dynamically

Again, I can't take much credit for this. The real credit goes to the author of this blog entry http://www.pukkared.com/2010/10/resizing-text-with-jquery-and-window-resize/. I have just made a few changes and calls for my own purposes. Namely, passing which fonts I would like to resize, what the original size should be and what size the page should be before resizing begins. Enjoy!

See demo.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic font resize</title>
<style>
body
{
font-family:Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
 google.load("jquery", "1");
 google.load("jqueryui", "1");
</script>
<script>
$.fn.resizeFonts = function(fontName, originalFontSize)
{
var originalWinWidth = $(window).width();
var ratioOfChange = 50;
$(fontName).css('font-size', originalFontSize);
$(window).resize(function()
{
var winWidth = $(window).width();
var widthDiff = winWidth - originalWinWidth;
if(widthDiff > 0)
{
var pixelsToIncrease = Math.round(widthDiff / ratioOfChange);
var newFontSize = originalFontSize + pixelsToIncrease;
$(fontName).css('font-size', newFontSize);
}
else
{
var pixelsToDecrease = Math.round(Math.abs(widthDiff) / ratioOfChange);
var newFontSize = originalFontSize - pixelsToDecrease;
$(fontName).css('font-size', newFontSize);
}
})
}
$(document).ready(function()
{
$(window).resize(function() {
if($(this).width() < 800)
{
$(this).resizeFonts('h1',20);
$(this).resizeFonts('p',10);
}
});
});
</script>
</head>
<body>
<h1>Big Mick's Recipe Book</h1>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
</body>
</html>