PhpRiot
Download Article
Download this article or the entire “Eight Weeks of Prototype” series with all listings and files.




More information
Related Books
JavaScript: The Good Parts

JavaScript: The Good Parts

Most programming languages contain good and bad parts, but JavaScript has more than its share...

jQuery: Novice to Ninja

jQuery: Novice to Ninja

jQuery: Novice to Ninja is a compilation of best-practice jQuery solutions to meet the most...
PhpRiot Newsletter
Your Email Address:

More information

Eight Weeks of Prototype: Week 3, Prototype Data Types

The Number Data Type

Prototype extends the native JavaScript number type with a range of new methods, each of which can be applied similarly to string methods. These methods are documented at http://prototypejs.org/api/number.

For the most part, these methods are just wrappers to the normal Math object methods. For example, the abs() method corresponds to the Math.abs() method. Similarly, the ceil(), floor() and round() methods also correspond to the respective Math method.

Aside from these methods, the only other methods of any great use are the toColorPart() and toPaddedString() methods.

The toColorPart() method is used to convert a number (assumed to be in the range of 0 to 255) to a 2 character hexadecimal number. This allows you to easily create a CSS colour string.

Listing 3 shows how toColorPart can be used. Later in this article we'll look at another way of using this method by making use of the array methods Prototype provides.

Listing 3 Creating hex colour codes with toColorPart() (listing-3.html)
<html>
    <head>
        <title>Creating hex colour codes with toColorPart()</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div id="foo">
            This div will change colour!
        </div>
 
        <script type="text/javascript">
            var r = 255;
            var g = 100;
            var b = 0;
 
            var hex = '#' + r.toColorPart()
                          + g.toColorPart()
                          + b.toColorPart();
 
            // hex will have the value #ff6400
 
            $('foo').setStyle({ backgroundColor : hex });
        </script>
    </body>
</html>

The toPaddedString() method is useful for created a zero-padded string based on the target number. For example, calling (25).toPaddString(5) will result in a string 5 characters in length. That is, 00025.

In This Article