Category: JavaScript

Pad A String In JavaScript

24 September, 2008 | JavaScript | No comments

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.

alert(pad("1", 4, "0")); // 0001
alert(pad("9", 4, "7")); // 7779
alert(pad("0002", 7, "this is a string")); // this is a string 0002
alert(pad("12345", 4, "0")); // 12345

JavaScript Word Counter

23 September, 2008 | JavaScript | No comments

I found this neat tool on a site to do with search engine optimisation, which counts the number of words that are typed into a textarea. I have tried all sorts of patterns and characters and it seems very robust.

The tool uses a textarea of a form and outputs the number of words into an input box in the same form. Here is the HTML. The textarea calls a function called textCounter() every time a key is pressed.

<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 first step is to detect what browser the user is viewing the site in due to a discrepancy between how different browsers split a string apart by white space. The following snippet is used to detect browsers.

var sUserAgent = navigator.userAgent;
var isOpera = sUserAgent.indexOf("Opera")>-1;
var isIE = sUserAgent.indexOf("compatible")>1 && sUserAgent.indexOf("MSIE")>1 && !isOpera;

Here is the function that counts the number of characters in the textarea element.

function textCounter(){
 var area = document.getElementById('wordCountCalc');
 var formcontent;
 if(area.message1.value.length != 0){
  var reg;
  reg = /^\s/gi;
  formcontent = area.message1.value.replace(reg,''); // remove white space at start or string
  reg = /\t+/g;
  formcontent = formcontent.replace(reg,' '); // remove any tab characters
  reg = /\s+/g;
  formcontent = formcontent.split(reg); // split string by spaces
  if(isIE){
   area.len.value = formcontent.length;
  }else{
   if(area.message1.value.charAt(area.message1.value.length-1)==' ' ||     area.message1.value.charAt(area.message1.value.length-1)=='\n'){
    area.len.value = formcontent.length-1;
   }else{
    area.len.value = formcontent.length;
   };
  };
 }else{
  area.len.value = 0;
 };
};

Create A MooTools Slider With Spanning Element

10 September, 2008 | mootools | No comments

The MooTools slider is a good little application, and creates a reliable means of adding in a slider tool to a site. However, one thing that the MooTool slider is missing is a block that covers what is on the left hand side of the slider, before the handle.

Before we go into to how to create the tool, I have created an example of the slider. The colours are deliberately garish in order to show the different elements of the slider.

Create a page with the following HTML.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="./script/mootools.js"></script>
<link href="./style/slider.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="track1">
<span id="track1span"></span><div id="handle1"><img src="./style/slider/handle.png" id="handle1Image" alt="Drag Me" /></div>
</div>
<p id="test"></p>
<script type="text/javascript" src="./script/slider.js"></script>
</body>
</html>

The slider element has the following structure.

div <- container for the slider
---span <- the span element
---div <- handle
------img <- image to make the handle pretty

You will need to download the MooTools library to run this tool.

Create a style file (called slider.css in a directory called style) and add the following content.

#track1{
 width:500px;
 padding:0;
 margin:0;
 height:18px;
 background-color: #09f;
}
 
#handle1{
 padding:0;
 margin:-20px 0 0 0;
 width:18px;
 height:18px;
}
 
span#track1span{
 display:block;
 padding:0;
 margin:0;
 background-color: #222;
 height:18px;
 width:50%;
}

Now for the important part of the script. Create a file called slider.js in the script directory and add the following code in. I have put lots of comments in here to make it clear what each line is doing.

// set up track array
var handleArr = new Object();
handleArr["track1"]=250; // set initial value
 
// set up effects for the slider
var track1Span = new Fx.Style($('track1span'),'width',{duration:0});
 
var slider1 = new Slider($('track1'),$('handle1'),{
 steps:500, // there are 250 steps in the track
 offset:0, // offset of zero fits the handle into the track
 onChange: function(pos){
 track1Span.set(pos);
 handleArr['track1'] = parseInt(pos); // store position
 updateTestDiv(); // run function to do something
 }
}).set(handleArr["track1"]); // set initial position
 
// function to update test tag with handle position
function updateTestDiv(pos){
 $('test').innerHTML = handleArr['track1'];
}

All that this slider does is update a p tag with the id of test with the current position of the slider handle.

The ideal thing about this script is that it is fairly easy to add more tracks into it, you just need to duplicate the code slightly to create variables for slider2 and so on.

The Google Chrome User Agent

3 September, 2008 | JavaScript | No comments

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.

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13

So detecting it should only be a case of looking for the word “chrome”. Just like this:

var ischrome = navigator.userAgent.indexOf("Chrome")? true : false;

If you want to see what the user agent is on your machine then past this code into a web page and hit refresh. It is quite a basic bit of code and should work in most browsers.

<span id="useragent"></span>
<script type="text/javascript">
document.getElementById('useragent').innerHTML = navigator.userAgent;
</script>

Using The view-source Protocol

28 August, 2008 | JavaScript | No comments

If you are running FireFox then there is a handy little short cut you can use to view the source of a page you are looking at. If you add the text view-source on any web address then you will see the equivalent of viewing the source of a page (perhaps by pressing Ctrl+u). Although not entirely useful, it does have a couple of benefits, such as being able to view your code in another tab, rather than another window.

Unfortunately, this only works in FireFox up to the latest version (currently 3). I have tested this in IE 7, Opera and Safari and they all complain about invalid protocols. Apparently it used to work in IE 6 before SP2, but was removed with that patch. This leads me to believe that it is not really a protocol, but a command that the browser understands on a local level. Much in the same way as about:config works.

If you want to view the source of the page you are currently looking at quickly then add this bit of HTML and JavaScript into your page. It will just take the current URL, paste view-source in front of it and then redirect to that address.

<form><input type="button" value="View Source Code" onclick="javascript:location='view-source:'+location"></form>