JavaScript Calculator API

The JavaScript Calculator now includes a public API as of version 1.1a4. This allows much greater flexibility and control of the calculator through code. Note, however, that this is still an alpha version and the API may change in the future. With that in mind, the following offers some examples of how to use the new API.

Adding Calculators to a Page

There are now two ways to add calculators to a page. The first and simplest way is to add the class "calc" to any elements on the page that should contain a calculator and then call JSCALC.init():

<div class="calc"></div>
<script src="calc-1.1a4-min.js"></script>
<script>JSCALC.init();</script>

In versions prior to 1.1a4, the calculator script would automatically create calculators. Now, you must call JSCALC.init() to create them. This has the advantage of more control as to when a calculator is inserted in the page. For example, you may want to have a button on the page that displays a calculator when pressed. This way, a calculator is never created unless it's needed.

<input id="calcBtn" type="button" value="Display Calculator" />
<div class="calc"></div>
<script src="calc-1.1a4-min.js"></script>
<script>
document.getElementById('calcBtn').onclick = function () {
    JSCALC.init();
};
</script>

The second way to create a calculator involves passing an argument to JSCALC.init(). Let's say you have no control over the HTML or do not wish to modify it. In this case, you can create a calculator inside an existing element simply by specifying the element's id.

<div id="tools"></div>
<script src="calc-1.1a4-min.js"></script>
<script>JSCALC.init('tools');</script>

Alternatively, an element object can be passed to the init() method. Here is an example using nothing but JavaScript:

(function () { // do not pollute the global scope
    var button = document.createElement('input');
    button.type = 'button';
    button.value = 'Display Calculator';
    
    button.onclick = function () {
        var container = document.createElement('div');
        document.body.replaceChild(container, this);
        JSCALC.init(container);
        button = null;
    };
    
    document.body.appendChild(button);
}());

Calculator Objects

The JSCALC.init() method returns one or more Calculator objects that can be used to control the calculators displayed on the page. When called with no arguments (or invalid arguments), the init() method will return an array of objects - one for each calculator that was created. If an element id or element object is passed, however, it will return the single Calculator object or false if one could not be created. Other methods of the JSCALC object also return Calculator objects.

Calculator objects have a remove() method which removes the calculator from the page. Using this method, the previous example can be modified to allow removing the calculator as well as creating it.

(function () { // do not pollute the global scope
    var button = document.createElement('input'),
        container = document.createElement('div'),
        calc;
     
    button.type = 'button';
    button.value = 'Display Calculator';
     
    button.onclick = function () {
        if (this.value === 'Display Calculator') {
            calc = JSCALC.init(container);
            this.value = 'Remove Calculator';
        } else {
            calc.remove();
            this.value = 'Display Calculator';
        }
    };
     
    document.body.appendChild(button);
    document.body.appendChild(container);
}());

A similar result can be achieved more easily and efficiently by toggling the CSS display property of the containing element. If you don't have a reference to the calculator's parent/containing element, one can be obtained from the container property of the Calculator object.

<input id="calcBtn" type="button" value="Display Calculator" />
<div class="calc"></div>
<script src="calc-1.1a4-min.js"></script>
(function () { // do not pollute the global scope
    var calc;
    document.getElementById('calcBtn').onclick = function () {
        if (!calc) {
            calc = JSCALC.init()[0];
        }
        
        if (this.value === 'Display Calculator') {
            calc.container.style.display = 'block';
            this.value = 'Remove Calculator';
        } else {
            calc.container.style.display = 'none';
            this.value = 'Display Calculator';
        }
    };
}());

Calculator objects also have a press() method which simulates pressing buttons on the calculator. Using the press() method, you can pre-populate the calculator display and memory for the user.

var CHECKOUT = {
    getTotal: function () {
        // there are 8 items at $4.50 each with 6% tax
        // round to 2 decimal places
        return Math.round(8 * 4.5 * 1.06 * 100) / 100;
    }
};

JSCALC.init('myCalc').press(CHECKOUT.getTotal());

The press method returns the Calculator object on which it was called, so calls to it can be chained together. It also accepts non-numeric button values as strings.

JSCALC.init('myCalc')
    .press(22.5).press('+').press(2.5).press('=').press('r');

Please see the API documentation for a complete listing of the available properties and methods. A live example and download links are on the JavaScript Calculator project page.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>