Sunday 20 February 2011 07:29pm
  • Share with Reddit
  • Share with Facebook
  • Bookmark with Delicious
Following the launch of my new website yesterday, I thought I'd be nice and publish a couple of JavaScript functions which I have written and found most useful.

Feel free to make use of these snippets as you wish, and let me know if they can be improved upon. I'm using them on this site so if they can be made better then that's only a good thing.

Load Content using AJAX

This function loads an external file into a HTML <DIV> element meaning that content can be changed without having to reload the entire site. It's parameters are the full path to the file being loaded and the ID of the element to contain it.

You could enhance this function to include error messages (e.g., 404 not found) but this is not something I've considered necessary. Whilst loading the content, the message "Please wait..." is displayed.

function ajaxLoadDoc(file,element)
	{	
	xmlhttp=new XMLHttpRequest();
	xmlhttp.onreadystatechange=function()
		{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
			document.getElementById(element).innerHTML=xmlhttp.responseText;
			}
		else if (xmlhttp.readyState <4)
			{
			document.getElementById(element).innerHTML="Please wait...";
			}
		}	
	xmlhttp.open("GET",file,true);
	xmlhttp.send();	
	}


Toggle Element Visibility

Here we have a function that alters the style property 'display' for the given element, effectively toggling it between the property 'block' or 'none' i.e., making it visible or invisible. Of course, the element is always loaded. This is just a toggle of whether it can be seen or not.

The function requires the ID of the element being toggled and optionally what it is being toggled to (type; can be 'block' or 'none'). If type isn't provided then the opposite of the current state is used.

function toggle(id,type)
	{
	//Toggle element display on (block) or off (none)
	if (!type) type = 'block';
       	var e = document.getElementById(id);
       	if(e.style.display == type) e.style.display = 'none';
       	else {e.style.display = type;}
	}


Key Press Action

A function that is called by the OnKeyDown property in the HTML <body> tag, this permits a degree of keyboard control to a website.

The following function recognises a press of the ESCAPE key but this can be expanded to detect any key press simply by using the appropriate KeyCode value.

I've used an IF statement to evaluate the keyCode, but if numerous codes are evaluated then a SWITCH...CASE block would be a better choice.

function keyPressAction(e)
	{
	if (e == 27)	//Key = ESCAPE
		{
                //Code to execute goes here
		}
	}



There we are. Nothing major or ground-breaking, but a few functions which I think are useful and thought I'd share. I'm nice like that :)
Close