Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

300 CHAPTER 6 Essential JavaScript and jQuery


txtInput.value = '0';
txtResult.value = '0';
};

return Calculator;
}());

})();


  1. In the initialize function, create a calculator variable and assign a new Calculator object
    to it. Be sure to use the namespace when creating the new Calculator object.
    The state should look like the following.
    var calculator = new ns.Calculator();

  2. Convert the loop that adds event listeners to each of the number buttons to a single
    jQuery statement based on finding all button elements that have an id that starts with
    btnNumber.
    The statement should look like the following.
    $('button[id^="btnNumber"]').on('click', calculator.numberClick);


To make the code work in this step, change the ids on the number buttons.


  1. Open the default.html file and replace the number button ids with btnNumberX where
    X is the number on the button.

  2. Open the CalculatorTests.html file and replace the number button ids with btnNum-
    berX where X is the number on the button.

  3. In the CalculatorLibrary.js file, locate the initialize function and delete the statements
    that set txtInput and txtResult.

  4. Convert the code that adds event listeners to btnPlus, btnMinus, btnClearEntry, and
    btnClear to use jQuery.
    The completed initialize function should look like the following.
    function initialize() {
    var calculator = new ns.Calculator();
    $('button[id^="btnNumber"]').on('click', calculator.numberClick);
    $('#btnPlus').on('click', calculator.plusClick);
    $('#btnMinus').on('click', calculator.minusClick);
    $('#btnClearEntry').on('click', calculator.clearEntry);
    $('#btnClear').on('click', calculator.clear);
    clear();
    }

  5. Convert the numberClick method to use jQuery.
    You can use the jQuery text method to retrieve the inner text. The completed method
    should look like the following.
    Calculator.prototype.numberClick = function () {
    $('#txtInput').val($('#txtInput').val() == '0'?

Free download pdf