JavaScript

Typewriter Script

The following script can be used if you want to simulate a typewriter in an element on screen. I have put in a lot of comments to describe what is happening but the script works by taking each array element in turn and adding it character by character to the content of the selected element.

Preventing Accidental Moving Off Site With JavaScript

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.

Edit Any Web Page With JavaScript

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.

Edit

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.

Pad A String In JavaScript

Use the following function to pad a string with to a set length with a given string. The function takes three parameters. The string to be padded, the total number of characters that the string must be, and the string to be added. If the third parameter is not given then 0 is used as a default.

function pad(padMe, totalChars, padWith) {
  padMe = padMe + ""; // force num to be string
 padWith = (padWith) ? padWith :"0"; // set default pad
 if ( padMe.length < totalChars ) {
  while ( padMe.length < totalChars ) {
    padMe = padWith + padMe;
  }
 }
 return padMe;
}

Here are some examples of the function in action. If the string given is longer than the required pad length then the string is returned unchanged.

JavaScript Word Counter

Counting the number of words in a block of text can be tricky. Users tend to create sections of white space that can throw out most scripts that don't take this into consideration.

I have created a tool for #! code that looks at a textarea of a form, and prints the number of words into an input box in the same form. The textarea calls a function called textCounter() every time a key is pressed. Here is the HTML of the form.

<form onsubmit="return false;" action="" id="wordCountCalc">
<textarea name="message1" rows="10" cols="68" onkeydown="textCounter()" onkeyup="textCounter()"></textarea>
<input readonly="readonly" size="15" type="text" name="len" maxlength="10" value="0" />
</form>

The function works by removing any white space from the start of the text. It then removes any tab characters from the text before splitting the text by one or more white space characters.

The Google Chrome User Agent

As the new Google web browser was released last night (I'm writing this post using the new browser) I thought it would be good to update our readers on the user agent string that this web browser has.

The user agent of any browser can be found out by using the userAgent property of the navigator object. This is available in most modern browsers and is thankfully also present in Google Chrome.

navigator.userAgent

As an example the user agent for FireFox 3 on a Windows XP machine looks like this.

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1

Using the same code, and the same machine, the user agent produced by Google Chrome is as follows.

Highlight The Contents Of A Textarea With JavaScript

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.
</textarea>
</form>

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 Crazy Window Zoomer

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.moveTo(0,0);
 window.resizeTo(screen.availWidth, screen.availHeight);
}

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

Adding Numbers In JavaScript

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.

Randomise JavaScript Array

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
alert(numbers);
//randomise array
numbers.sort(randNumber);
//print random array
alert(numbers);

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.