Posts about the client side scripting language JavaScript.

JavaScript Logo

Preventing Accidental Moving Off Site With JavaScript

19th November 2008 - 4 minutes read time

There is nothing more irritating than when you are typing out a long message in a text box and you accidentally move backwards, or clicking on a link and moving off page, therefore losing data you may have entered. There is a solution to stop this happening and it involves the onbeforeunload event.

Although not technically a fully supported event, onbeforeunload is run just before the page is unloaded out of cache. The onunload event occurs right after this, and it is too late by that point.

To prevent a user from moving out of the current page without some form of warning you will need to return some text with the onbeforeunload event. In some browsers that text will be used as part of the message, some browsers will ignore the message but continue anyway.

Include the following body tag in the page you want to incorporate this feature into.

JavaScript Logo

Edit Any Web Page With JavaScript

11th November 2008 - 2 minutes read time

If you want to directly edit any page that you are looking at then copy and paste the following JavaScript into your address bar.

javascript:document.body.contentEditable='true' document.designMode='on' void 0

I have created a handy little bookmarklet that you can use to do the same thing.


This code has been tested in IE7, Firefox and Chrome and works well in all three.

Of course, it goes without saying that you don't actually edit the site, just the content that you see on the screen. Hitting refresh will remove any editing that you have done. This little tool is ideal if you want to see what different content would look like on the page without having to edit HTML. It can also be used to create spoof pages with false content.

JavaScript Logo

Highlight The Contents Of A Textarea With JavaScript

27th August 2008 - 2 minutes read time

If you want to give your users a little snippet of code it is nice to give them the option of selecting the entire block of code without having to highlight the text manually. This can be done with a simple JavaScript button.

Take the following form:

<form name="aForm">
<textarea name="aTextarea" cols="50" rows="20">
Copy this text onto your own website.

To enable the selection functionality you just need to add in an input button. The click event of this button will be to run a JavaScript bookmarklet that focuses on the textarea in question (in this case it is called aTextarea) and selects the text.

JavaScript Logo

JavaScript Crazy Window Zoomer

26th August 2008 - 3 minutes read time

I really don't know how this would be useful, but it might teach you a couple of things about how to use the browser window functions and properties.

The following function resizes the browser window to nothing and then gradually increases this to full screen in a series of steps, at each step the window is moved so that it is in the middle of the screen. This in effect makes it look like the browser window is zooming in.

function warpSpeedWindow(){
 for(i = 0;i < 50;i++){
  window.moveTo(screen.availWidth * -(i - 50) / 100, screen.availHeight * -(i - 50) / 100);
  window.resizeTo(screen.availWidth * i / 50, screen.availHeight * i / 50);
 window.resizeTo(screen.availWidth, screen.availHeight);

You can call this function on the page load by using the following:

JavaScript Logo

Format Numbers With Commas In JavaScript

31st July 2008 - 5 minutes read time

I found a good function that details how to format numbers with commas in JavaScript and thought I would reproduce it here. It basically takes any number and turns it into formatted string with the thousands separated by commas. The number_format() function is available in PHP and I have been relying on PHP to sort out the formatting before returning it via an AJAX call. I can now include this function into my JavaScript library and do this on the client side.

The function works by using regular expressions to first split the string into whole number and decimal, before splitting the number by groups of three digits.

The regular expression used is (\d+)(\d{3}), which looks for a sequence of three numbers preceded by any numbers. This is a little trick that causes the regular expression engine to work from right to left, instead of left to right.

JavaScript Logo

Adding Numbers In JavaScript

28th July 2008 - 3 minutes read time

You think I'm joking right? Well, due to a silly mistake (in my opinion) when creating the language the concatenation character is the same as the plus symbol. This means that sometimes JavaScript will add them together and sometimes it will concatenate them.

This occurs if JavaScript encounters any part of the calculation to be a string. If it is then it will concatenate the whole expression. For example.

alert("1"+2+3);// prints out "123" rather than 6

To stop this you need to add the parseInt() function to the part of the addition that might be mistaken as a string. Or the whole thing just to make sure. The following is a bit of an overkill but ensures that the values will be added, NOT concatenated.

JavaScript Logo

Randomise JavaScript Array

4th July 2008 - 3 minutes read time

Randomising a JavaScript array can be done in one or two ways. The easy way is to create a function that returns a random number and then use the sort() function of the Array object to sort the array by a random value.

// random number
function randNumber(){
 return (Math.round(Math.random())-0.5);
// create array
var numbers = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// print array
//randomise array
//print random array

The sort function works by taking the randNumber function as a parameter. For every item of the array it uses this function to compare one value to the next. If the function returns a random number then the array will be sorted randomly.

The second method is slightly more complex and involves using the Fisher Yates randomising algorithm. The following function takes in an array and returns a randomly sorted array.

JavaScript Logo

Merge Two JavaScript Arrays

3rd July 2008 - 2 minutes read time

Here is a simple bit of code that you can use to merge one or more arrays. The function you need is called contact().

Take the following two arrays, both of which contain numbers.

var array1 = new Array(1,2,3,4);
var array2 = new Array(5,6,7,8);

To join these two arrays together we use the concat() function like this.

array1 = array1.concat(array2);

The variable array1 now contains the contents of both arrays.

JavaScript Logo

Loading Page Styles And JavaScript With JavaScript

2nd July 2008 - 4 minutes read time

One good technique when using JavaScript is to load a single JavaScript file and get this file to load any other JavaScript or CSS documents that are needed. This means that you can simplify the instillation of a script on a page by including a single file, which then loads everything else it needs. Here is how to accomplish such a task.

The basic idea is that you add the references you need to the DOM structure of the document. Let's say that we want to load a CSS file called styles.css. To do this at run time we need to create a <link> element and give it some parameters before adding it onto the end of the <head> element of the page. Here is the code needed to do this.

JavaScript Logo

Enabling Tabbing In A Textarea

20th June 2008 - 4 minutes read time

When a user presses the tab key in a browser window the normal action is for the user to move the focus to a different control. To enable a word processor like tab effect in a text area you need to catch the keystroke and add in the tab character to where ever the cursor is. This is the main issue with creating this solution, it is easy to add a tab to the end of the text, but most users might want to add a tab half way through the text.

Take the following HTML text area.

<textarea name="content" class="textarea" id="content" rows="20" cols="65"  wrap="on" onKeyDown="return catchTab(this,event)"></textarea>

When a keystroke is detected it runs the catchTab() function. This function detects if the keystroke is 9 (which means it is a tab) and runs the function called replaceSelection() in order to find out where the cursor is and replace the text that exists there.