JavaScript

Contained on this page are a few JavaScript functions I have created. This work is licenced under a Creative Commons Licence (you can use it for any purpose if you give the author credit).

daysInMonth (Monday, July 31, 2006)

For more information, read the related blog post: Find out how many days are in a given month (JavaScript).

function daysInMonth(year, month)
{
	 // month is zero based, so take away 1
	 month = --month;
	 // first day of the following month
	 var nextDay;
	 // if last month of year, then use first day of following year
	 if(month == 11)
	 {
	  nextDay = new Date(++year, 0);
	 }
	 // otherwise use next day of current year
	 else
	 {
	  nextDay = new Date(year, ++month);
	 }
	 // take away a millisecond to get required date
	 var requiredDate = new Date(nextDay - 1);
	 // return the day
	 return requiredDate.getDate();
}

createCSSClass (Friday, June 30, 2006)

For more information, read the related blog post: Create CSS Class (JavaScript).

var createCSSClass = function(selector, style)
{
	// using information found at: http://www.quirksmode.org/dom/w3c_css.html
	// doesn't work in Opera due to lack of styleSheets support
	if(!document.styleSheets) return;
	if(document.getElementsByTagName("head").length == 0) return;
	var stylesheet;
	var mediaType;
	if(document.styleSheets.length > 0)
	{
		for(i = 0; i<document.styleSheets.length; i++)
		{
			if(document.styleSheets[i].disabled) continue;
			var media = document.styleSheets[i].media;
			mediaType = typeof media;
			// IE
			if(mediaType == "string")
			{
				if(media == "" || media.indexOf("screen") != -1)
				{
					styleSheet = document.styleSheets[i];
				}
			}
			else if(mediaType == "object")
			{
				if(media.mediaText == "" || media.mediaText.indexOf("screen") != -1)
				{
					styleSheet = document.styleSheets[i];
				}
			}
			// stylesheet found, so break out of loop
			if(typeof styleSheet != "undefined") break;
		}
	}
	// if no style sheet is found
	if(typeof styleSheet == "undefined")
	{
		// create a new style sheet
		var styleSheetElement = document.createElement("style");
		styleSheetElement.type = "text/css";
		// add to <head>
		document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
		// select it
		for(i = 0; i<document.styleSheets.length; i++)
		{
			if(document.styleSheets[i].disabled) continue;
			styleSheet = document.styleSheets[i];
		}
		// get media type
		var media = styleSheet.media;
		mediaType = typeof media;
	}
	// IE
	if(mediaType == "string")
	{
		for(i = 0;i<styleSheet.rules.length;i++)
		{
			// if there is an existing rule set up, replace it
			if(styleSheet.rules[i].selectorText.toLowerCase() == selector.toLowerCase())
			{
				styleSheet.rules[i].style.cssText = style;
				return;
			}
		}
		// or add a new rule
		styleSheet.addRule(selector,style);
	}
	else if(mediaType == "object")
	{
	for(i = 0;i<styleSheet.cssRules.length;i++)
	{
		// if there is an existing rule set up, replace it
		if(styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase())
		{
			styleSheet.cssRules[i].style.cssText = style;
			return;
		}
	}
	// or insert new rule
	styleSheet.insertRule(selector + "{" + style + "}", styleSheet.cssRules.length);
	}
}

anchorWrap (Tuesday, January 03, 2006)

Wrap an element with an anchor. For more information, read the related blog post: anchorWrap (JavaScript).

// 'node' can be an existing node, or a string (id of node)
// 'anchor' can be a URL string, or a precreated anchor
// 'target' is the target frame to go to, and is optional
function anchorWrap(node,anchor,target)
{
	if(!document.createElement) return;
	var newanchor,parent,sibling;
	if(typeof(node) == "string")
	{
		node = document.getElementById(node);
	}
	if(!node || !node.parentNode) return;
	if(typeof(anchor) == "string")
	{
		newanchor = document.createElement("a");
		newanchor.href = anchor;
	}
	else
	{
		newanchor = anchor;
	}
	if(!newanchor) return;
	// if href is not set (which may be the case when it performs a javascript action), set it to #, so the link is seen
	if(!newanchor.href) newanchor.href = "#";
	// if target is defined, set it
	if(typeof(target) == "string")
	{
		newanchor.target = target;
	}
	// get the sibling and the parent node (so we can insert in the right place)
	sibling = node.nextSibling;
	parent = node.parentNode;
	// add the node to the new anchor
	newanchor.appendChild(node);
	// insert new anchor before sibling, or at the end if there is no sibling
	if(sibling)
	{
		parent.insertBefore(newanchor,sibling);
	}
	else
	{
		parent.appendChild(newanchor);
	}
}

getElementDimensions (Monday, December 05, 2005)

This gets the position (left, right,top, bottom), width and height for a given element. For more information, read the related blog post: getElementDimensions (JavaScript).

function getElementDimensions(el)
{
	if(typeof(el) == "string")
	{
		el = document.getElementById(el);
	}
	if(!el || !el.offsetParent) return false;
	var left = el.offsetLeft, top = el.offsetTop, width = el.offsetWidth, height = el.offsetHeight;
	do
	{
		el = el.offsetParent, left+= el.offsetLeft, top+= el.offsetTop;
	}
	while (el.offsetParent);
	return {"left" : left, "right" : left + width, "top" : top, "bottom" : top + height, "width" : width, "height" : height};
}

removeAllChildNodes, getImmediateChildren (Wednesday, November 30, 2005)

Removes all children of an element, or get child nodes (optionally filtered by tag name) that are directly underneath an element. For more information, read the related blog post: removeAllChildNodes, getImmediateChildren (JavaScript).

function removeAllChildNodes(node)
{
	if(!node || !node.childNodes) return;
	var nodeCount = node.childNodes.length;
	for(var i=nodeCount-1;i>=0;i--)
	{
		node.removeChild(node.childNodes[i]);
	}
}
function getImmediateChildren(node, tagName)
{
	if(!node || !node.childNodes) return;
	if(!tagName) tagName = "*";
	var elements = document.getElementsByTagName(tagName);
	var nodeCount = elements.length;
	var children = new Array();
	for(var i=0;i<nodeCount;i++)
	{
		if(elements[i].parentNode == node)
		{
			children[children.length] = elements[i];
		}
	}
	return children;
}

getInnerText (Monday, October 03, 2005)

This gets all the text contained within a given element. For more information, read the related blog post: getInnerText (JavaScript).

function getInnerText(node,ignorewhitespace)
{
	var text = "";
	// if the node has children, loop through them
	if(node.hasChildNodes())
	{
		var children = node.childNodes;
		for(var i=0; i<children.length; i++)
		{
			// if node is a text node append it
			if(children[i].nodeName == "#text")
			{
				if(ignorewhitespace)
				{
					if(!/^\s+$/.test(children[i].nodeValue))
					{
						text = text.concat(children[i].nodeValue);
					}
				}
				else
				{
					text = text.concat(children[i].nodeValue);
				}
			}
			// if node is a line break append \n
			else if(children[i].nodeName == "BR")
			{
				text = text.concat("\n");
			}
			// otherwise call this function again to get the text
			else
			{
				text = text.concat(getInnerText(children[i]));
			}
		}
	}
	// it has no children, so get the text
	else
	{
		// if node is a text node append it
		if(node.nodeName == "#text")
		{
			text = text.concat(node.nodeValue);
		}
		// if node is a line break append \n
		else if(node.nodeName == "BR")
		{
			text = text.concat("\n");
		}
	}
	return text;
}

Popup Window Countdown (Friday, August 13, 2004)

This is a demo of how to show a popup that closes itself after a certain time period. For more information, read the related blog post: Popup Window Countdown (JavaScript).

<html>
<head>
<title>Popup Timer</title>
<script language="JavaScript" type="text/JavaScript">

// popup window var
var popup;

// At what number shall the countdown counter start?
CounterStart = 10;
 
// This function CustomAction() can be modified to do 
// whatever you want done every second.
 
function CustomAction() {
	popup.document.timer.timeleft.value = CounterStart;
} // end of function CustomAction()

// end of JavaScript customization


function Decrement() {
	CounterStart--;
	CustomAction();
	if(CounterStart <= 0) { popup.close(); alert('Timer reached 0'); }
	else { setTimeout('Decrement()',1000); }
}
 
function StartTheCounter() {
	openPopup(120,100);
	setTimeout('Decrement()',1000);
}

function openPopup(w,h){
	// new window title
	var contents = '<html><head><title>Counter Window<\/title>';
	// resize window once image has loaded
	contents += '<script type="text\/javascript">window.onload = init;';
	// centre the popup window
	contents += 'function init() {window.moveTo((screen.width-'+w+')/2,(screen.height-'+h+')/2)}';
	contents += '<\/script>';
	contents += '<\/head><body>';
	contents += '<form name="timer">'
	contents += '<input name="timeleft" type="text" size="4" readonly="" value="'+CounterStart+'" /> seconds!';
	contents += '</form>';
	contents += '<\/body><\/html>';
	// open popup window
	popup = window.open('about:blank','popup','location=no,menubar=no,scrollbars=no,status=no,toolbar=no,width='+w+',height='+h);
	popup.document.open();
	popup.document.write(contents);
	popup.document.close();
}
// -->
</script>
</head>
<body onload="StartTheCounter();">
Popup Window Timer
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *