set links in sidebar to be active

« Go back

Display Content on Certain Page & Set Link Active

PHP
<?php
// Checks to see if the URL contains the text string 
// and if it does, it writes the HTML code to the page
if( stristr($_SERVER['PHP_SELF'], ‘/foo/bar/1/’) == TRUE )
<?php { ?>

<ul class="nav">
<li><a href="/foo/bar/1/">Link to Page 1</a></li>
<li><a href="/foo/bar/2/">Link to Page 2</a></li>
</ul>
<?php } ?>
JavaScript
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>	
	<script type="text/javascript">
		// Searches the secondary nav and matches the site URL to the link HREF to make the link active
		// For this example, the link to Page 1 will be set active
		$(".nav a").each(function() {
			if(this.href == window.location) $(this).addClass("active");
		});
	</script>

Let’s say you have a sidebar included on every page. The php code above displays the sidebar nav only if your browser is pointed to that page. The JavaScript underneath will then set the current page active by adding a class name to it, which you can then apply your styling in CSS.

Share and Enjoy:
  • Facebook
  • Twitter
  • Reddit
  • StumbleUpon
  • Digg

Tags: ,

About the author

Author

I started my career as a print designer and wanted nothing to do with "code". Then slowly I began to learn by reading tutorials online. My learning process has been challenging, yet very rewarding. My goal is to document the lessons I have learned and to encourage other beginners in the field of web design / front-end programming. - Jacob Lett