A Javascript Shared Function Library

Productivity (and saving my fingers from some valuable keystrokes) is always high on my list of priorities in any project I'm working on. In this tutorial I'll show you how to start a basic javascript function library.

Recently, I was struck dumb with how silly I was being about JavaScript when I knew from my other languages just how easy it would be to save myself a great deal of time in development.

A function library

This isn't a new concept, people have been doing it for years. If you're consistently using a bit of code in the same way, why not encapsulate it into a reusable function and reap benefits across the board.

A simple line of code is required to include the library in each page on your web site:

<script type="text/javascript" href="sharedLibrary.js"></script>

get(id)

function get(id) {
	return document.getElementById(id);
}

One of the things I'm always typing in JavaScript is var [name] = document.getElementById("[id here]"). I've saved myself quite a bit of typing by creating a simple routine named get(id). It's a very simple function... nothing much to learn here, but it makes me happy every time I use it, and functions that make me happy are good to have around.

hide(id)

function hide(id) {
    get(id).style.display = "none";
}

We tap into the DOM here and change part of the CSS style. This may yield unexpected results if you use this method on elements on which you've specified a custom "display" attribute.

show(id)

function show(id) {
    get(id).style.display = "";
}

The exact opposite of hide. We change the "display" attribute to an empty string to indicate that it should use the default value for that element.

Only the beginning

This is but a very simple example of a function library. Add your own or collect some from around the web, but don't miss out on the benefits of reusing code!

Trackback URL: http://elijahtaylor.com/trackback/e9b569b7-8d83-40a9-91b6-cc07fa7d92a1/A-Javascript-Shared-Function-Library.aspx

Comments
santhanavelu
Hi, Thank you very much for providing me this module. this has been really useful. please keep up the good work. thank you very much
3/24/2008 1:09:15 AM
Report abuse
slucas
Elijah, thank you for a really simple but effective way to implement input watermarking. I liked your getId, etc functions as well. Bookmarked you. THanks again.
9/10/2008 10:14:52 PM
Report abuse
Leave comment



 Security code

details


This web site uses Kentico CMS, the content management system for ASP.NET developers.