Register now and start sharing your code snippets.
-->

Show and Hide (toggle) the Blueprint Grid with a JavaScript

JavaScript posted about 1 year ago by christian

This snippet-which could be improved on-allows you to easily display and hide the BlueprintCSS grid.

Put the following code inside the <head> element:

   1  <style title="grid" type="text/css">
   2  		.container { }
   3  </style>
   4  <script type="text/javascript">
   5  	function toggleGrid() {
   6  		if (!document.styleSheets) return;
   7  	
   8  		var cssTitle  	 = "grid"
   9  		var selectorName = ".container";
  10  		var cssText   	 = "background: url('images/grid.png');";
  11  		var css = new Array();
  12  	
  13  		// Find the stylesheet
  14  		for(i = 0; i < document.styleSheets.length; i++)
  15  		{
  16  			var styleSheet = document.styleSheets[i];
  17  			
  18  			if(styleSheet.title == cssTitle) {
  19  				if (document.styleSheets[i].cssRules)
  20  					css = document.styleSheets[i].cssRules;
  21  				else if (document.styleSheets[i].rules)
  22  					css = document.styleSheets[i].rules;
  23  				else return;
  24  				
  25  				break;
  26  			}
  27  		}
  28  
  29  		// Find the selector
  30  		for (i = 0; i < css.length; i++) {
  31  		
  32  			if ((css[i].selectorText.toLowerCase() == selectorName)) {
  33  				if(css[i].style.cssText == "") {
  34  					css[i].style.cssText = cssText;
  35  				}
  36  				else {
  37  					css[i].style.cssText = "";
  38  				}
  39  			}
  40  		}
  41  	}
  42  </script>

Change selectorName or cssText, if needed. Next add the following link, for example, to the footer:

   1  <a href="javascript:toggleGrid();" id="toggle-grid">Show grid</a>

Now when you click the link, the grid will be displayed. Click again to hide it.

Note that this is a simple example of how to change a CSS style sheet dynamically with JavaScript. You can use it to change any selector at runtime.

Tagged blueprint, css, blueprintcss, toggle, grid, javascript