Jump to content
Larry Ullman's Book Forums

Chapter 7 - Today.js


Recommended Posts

I have been working my way through the book and understood a lot of the concepts up until the Today.js file in Chapter 7.

 

I really cannot get my head around what is going on with the code.

 

I understand that the following occurs:

  • When the window has loaded the event listener will call the init function.
  • The init function will create a variable called today which will store the current date and time for the user. A variable called message will also be created which will generate a string to inform the user of the current time.
  • I am not too sure what setText('output', message); does. It looks the 'output' and message values are being passed to the setText function. What is the 'output' value being passed to the function and what is setText's purpose?
  • Once the setText function is called it has two parameters/arguments. These are elementId and message.
  • The function's parameters are validated to ensure that both values are strings. The message value will presumably be the message "Right now it is Date, Hours, Minutes". But what is the elementId string? I thought that 'output' and message were being passed to the function so am not sure why it is validating elementId.
  • A variable called output is created which should obtain an ID called elementId as an argument. I thought the getElementById method checks the HTML content for an id of elementId. The only reference to elementId I can find is within the JavaScript file.
  • An IF statement is then used to check whether to use textContent or innerText for displaying the message. How does it return the message to the HTML as there does not appear to be any reference to the paragraph element's id of ouput in the HTML file?

 

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Today</title>
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<body>
    <!-- today.html -->
    <p id="output"></p>
    <script src="js/today.js"></script>
</body>
</html>

 

 

/* The function will be called by the init function. The function takes two arguments assigned to the elementId and message variables.  */
function setText(elementId, message) {
    'use strict';
    
    if ( (typeof elementId == 'string')
    && (typeof message == 'string') ) {
    
        // Get a reference to the paragraph:
        var output = document.getElementById(elementId);
    
        // Update the innerText or textContent property of the paragraph:
        if (output.textContent !== undefined) {
            output.textContent = message;
        } else {
            output.innerText = message;
        }
    
    } // End of main IF.

} // End of setText() function.

// Call this function when the page has loaded:
function init() {
    'use strict';
    var today = new Date();
    var message = 'Right now it is ' + today.toLocaleDateString();
    message += ' at ' + today.getHours() + ':' + today.getMinutes();

    // Update the page:
    setText('output', message);
    
} // End of init() function.
window.onload = init;

 

Sorry for all the questions, however, I am really struggling with this chapter :(

 

Many thanks in advance.

Link to comment
Share on other sites

setText is a helper function created to set input on an element. It wraps the if statements for checking if textContent exists ( that's the logic in: textContent !== undefined ) or if you need to use the function innerText. It's basically a short-cut method of choosing the setting method that exists in your browser. (as one of them might not exist) You send in the element ID (<input id="name"> would equal ID = name) and the value to set it to. setText('name', 'Thomas'); would therefor set the input field to 'Thomas' by the best method possible supported by the browser.

 

var output; is actually the object from the input field with the ID of 'name' in my example. You save it to a variable so you don't have to look for the object each time with a call using document.getElementById(). It's a performance gain. document.getElementById is a native JavaScript function, so you can't 'find it' in your code.

 

The object saved to the variable output actually IS the HTML. More precisely, it's a node in the document model that makes up a HTML page. Because the variable contains that node (think of it as the input field itself) with functions to alter itself, we simple update the input field by using output.textContent or output.innerText. Those are functions for changing the internal data in the field, and it will be updated visually for the viewer.

 

Hope that makes the pieces click.

Link to comment
Share on other sites

Given the nature of your questions, I get the feeling that there is a bit of a disconnect with how JS and the DOM interact. I will do my best to explain what's happening (and I apologize if I say a bunch of things you already know).

 

The DOM is an API that is separate from JS. JS interacts with it, but in reality, the DOM is not a part of JS. This is done so that other languages can also interact with the DOM.

And when I say the DOM, I'm referring to a virtual tree structure that mimics the current state of the HTML document. Given that HTML is hierarchical in nature, it's probably not too hard to imagine what this virtual tree structure would look like (with the html node at the top, and then branching down to the head and body elements, etc.).

 

With all that said, when you use the JS built-in document.getElementById method (read "function"), you are telling JS to search through the DOM for an element with the specified ID (which is specified in string format). If no element with the specified ID exists, then null is returned, but assuming an element does exist with the specified ID, then the getElementById method returns a special JS object that contains a bunch of information about that element.

The easiest way to think of this special JS object is that it is the JS representation of the element in the DOM (i.e., the actual element displayed on the page in your HTML).

 

Given all that, when you call the setText function, you are passing the ID of the element you want to place the text in and the actual message to the function. Since both of these arguments should be strings, the function first validates that they're both strings, and assuming they are, Larry then using the document.getElementById method to find the element in the DOM with the specified ID. The corresponding JS object is then stored in the output variable.

 

From there, Larry then tests if the JS object returned by the document.getElementById method supports the textContent property. He does this because not all browsers support this property, so you need to test for its existence before you just assume it's okay to use. If the property is supported, he then assigns the message string to that property. This causes the message to appear on the screen immediately by rendering the message text within the element whose ID you specified. In other words, the message is output to within the element stored in the output variable.

 

If the textContent property is not supported by the browser, then Larry uses the innerText property instead, which essentially does the same thing. I think Larry explains in the book why textContent is preferable over innerText.

 

That all make sense and answer your questions/confusion?

 

Edit: Antonio and I responded at the same time, and I didn't see his response before posting mine. Sorry.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...