5 Simple but useful JavaScript snippits

Originally posted on 26th March 2009 by Ian Harris

« Back to articles

JavaScript can be employed on your website to perform an whole multitude of simple, but quite effective, tasks that make your job as a web developer that little bit easier. Over time, we have compiled a library of these little JavaScript snippets and we have listed a few of our favourites here.

1. ‘Previous Page’ link

This snippet will take the user back to the previous page that they have viewed. Pretty much like the standard browser back button really:

1
<a href="javascript:history.back(1)">Previous Page</a>

2. ‘Print this page’ links

I’ve read quite a few mixed opinions about adding a link that allows users to print the current page. Some developers think that their users will already know how to print the page using the browsers toolbar and don’t need us cluttering our pages with unnecessary links. Others believe that we should make it easy for the user and remind them that they can print this content if they so wish. I am with the latter, but whatever your opinion, here it how you add a print link:

1
<a href="#" onclick="window.print();return false;">Print</a>

3. Close the current browser window

On occasions, you might need want to give the user the option to easily close the current browser window. For example, you have created a CMS that uses pop-up top display information. This snippit will close the current browser window (or tab):

1
<a href="javascript:window.close();">Click to Close</a>

4. Confirm prompt

If you are asking the user to perform a certain action, like deleting something, you can prompt them to confirm that they definitely want to go ahead. This snippit intercepts by prompting with a Yes/No box and a message of your choice. If the user selects Yes, it will carry on to the URL in the link. Selecting No will just cancel the action.

1
<a href="delete.php" onclick="return confirm('Are you sure you want to delete this?')">Delete</a>

5. Replace broken images

Sometimes you may link to images that are hosted on other domains, such as photos in your Flickr account. As this is external, you cannot guarantee that this content will always be available and if the site hosting the image was to go offline, you would be left with that nasty red cross that gives the impression that you don’t look after your site. The snippet below will display a default image if the external image is unavailable (obviously, you should only link to images where you have permission to do so, nobody likes a bandwidth thief).

1
<img src="http://www.mydomain.com/image.jpg" onerror='this.src="/images/unavailable.png"' />

I hope these are useful to you, they have certainly helped us. Thanks.