Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

128 CHAPTER 3 Getting started with JavaScript



  1. Press F5 to run the test, and all 10 tests will fail. Look closely at each test to understand
    why each test failed.
    You must add code to subscribe to the click event of the number buttons.

  2. Fix the failing tests by adding looping code to the initialize function that subscribes to
    the click event of all ten number buttons.
    Your code should look like the following:
    for (var i = 0; i < 10; i++) {
    document.getElementById('btn'+i).addEventListener('click',
    numberClick, false);
    }

  3. Press F5 to run the test, which should pass.
    When btnPlus is clicked, the value in txtInput will be added to the value in txtResult.

  4. In the tests.js file, add a new test to check btnPlus when it’s clicked.
    Your test code should look like the following:
    test("Add Test", function () {
    expect(1);
    txtInput.value = '10';
    txtResult.value = '20';
    var btnPlus = document.getElementById('btnPlus');
    QUnit.triggerEvent(btnPlus, "click");
    var expected = '30';
    equal(txtResult.value, expected, 'Expected value: ' + expected +
    ' Actual value: ' + txtResult.value);
    });

  5. Press F5 to run the test and verify that the test fails because you haven’t subscribed to
    the click event of btnPlus.

  6. In the initialize function, add code to obtain a reference to the txtResult text box and
    assign it to a new global txtResult variable. Add code in the initialize function to sub-
    scribe to btnPlus and call the plusClick function. Add the plusClick function with code
    to add txtInput to txtResult.
    Your code should look like the following:
    var txtInput;
    var txtResult;


function initialize() {
for (var i = 0; i < 10; i++) {
document.getElementById('btn'+i).addEventListener('click',
numberClick, false);
}
txtInput = document.getElementById('txtInput');
txtResult = document.getElementById('txtResult');

document.getElementById('btnPlus')
.addEventListener('click', plusClick, false);
}
Free download pdf