January 31, 2010

JavaScript Snippets for Dynamic Web Pages

There are a ton of unnecessarily complicated JavaScript examples strewn about the Internet.  In an attempt to counter that, here are a few simplified examples of using JavaScript to accomplish common tasks.

Catalog of JavaScript Snippets:
To try out a snippet, click the link for the example listed below the snippet.

Code here is Public Domain Software — free to use as you like.


Show/Hide Toggle
JavaScript can be used to show and hide an object on a web page with each click by the user.  This JavaScript snippet finds the display status of the element and flips the status from "none" (hidden) to "block" (visible) or from "block" to "none".

JavaScript
function toggle(elemName) {
   var s = document.getElementById(elemName).style;
   s.display = s.display == 'none' ? 'block' : 'none';
   }



Read URL Parameters
JavaScript can be used to read URL parameters.  This JavaScript snippet reads the name/value pairs appended to a URL and stores the values in an array named params.

JavaScript
var params = new Array();
var keyvals = location.search.substring(1).split('&');
for (count in keyvals) {
   keyval = keyvals[count].split('=');
   params[keyval[0]] = keyval[1];
   }



Set and Get Cookie Value
JavaScript can be used to set and get browser cookies.  This JavaScript snippet contains two functions — one to save the cookie value and the second to read the value back.

JavaScript
function setCookie(key, value) {
   var expires = new Date();
   expires.setTime(expires.getTime() + 31536000000); //1 year
   document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
   }

function getCookie(key) {
   var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
   return keyValue ? keyValue[2] : null;
   }



Further Reading

Elsewhere:

0 comments: