Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

126 CHAPTER 3 Getting started with JavaScript



  1. Press F5 to run the test, which should fail, as shown in Figure 3-20, because you don’t
    have any code yet. Notice that the failure states that “5” was expected but actual was
    “”.


FIGURE 3-20 he failed QUnit test because no code has been added yetT


  1. In the CalculatorLibrary.js file, add a numberClick function that reads the innerText
    (textual content of the element) property of the button that was clicked and appends
    the innerText property to the txtInput text box value.
    However, if txtInput has a value of zero, you should replace its value with the new value
    so you don’t end up with leading zeros in the text box. Your code should look like the
    following:
    function numberClick() {
    txtInput.value = txtInput.value =='0'?
    this.innerText : txtInput.value + this.innerText;
    }

  2. In the initialize function, add JavaScript code to subscribe to the click event of btn5,
    which will call the numberClick function when btn5 is clicked. The code should look like
    the following:
    document.getElementById('btn5').addEventListener('click', numberClick, false);

  3. Press F5 to run the test, which should pass. Click the test to expand it and see the
    green indicator, as shown in Figure 3-21.

Free download pdf