Free JavaScript Resourses at:

Click image above to go to web site.

 

JavaScript Vital Few

There are a few concepts that you have to always be aware of when writing JavaScript code:

Execute Script Immediately

  1. Write the following heading in between the <body></body> tags:

    <body> 
      <h1>JavaScript Vital Few</h1>
    </body>

  2. Write the following script ABOVE the closing head tag (</head>):

    <script>
    alert("Hello, world");
    </script
    >
    </head>

    ALTERNATIVES: You could also replace the alert("Hello, World") with:
    confirm("Do you want to delete this file?"); or
    prompt("What is your favorite color?", "");

  3. CHECK POINT: Save the file and preview it in a browser. You should see the alert dialog box shows IMMEDIATELY. However, the page is not visible because the script executes BEFORE the page loads and the page gets SUSPENDED until you click the OK button. Once you click the OK button then you will be able to see the page.

Write Text To A Page

There are two major ways to write text to a page.

The first way to write text DIRECTLY to a page is to use a write() method

  1. Delete or comment out the alert statement in the head tag using two forward slashes:

     // alert("Hello, World");

  2. Write the following code in between the body tags:

    <body>
    <script>
    document.write("This is computer generated text");
    </script>
    </body>

  3. CHECK POINT: Save the file and preview it in a browser. You should see that the text is written to the page.

You can write text INDIRECTLY to a page. While using the write() method is a COMMON practice, it is not the BEST practice. It is better to use innerHTML to write text to an existing tag whether it is empty or not.

  1. Write the following id selector in the heading tag:

    <h1 id="JS_heading">JavaScript Vital Few</h1>

  2. Write the following script BELOW the <h1> tag:

    <h1 id="JS_heading">JavaScript Vital Few</h1>
    <script>
    document.getElementById("JS_heading").innerHTML = "JavaScript is Awesome!!!";
    </script>

    CAUTION: Be careful not to make a common mistake of treating the innerHTML property like a method by wrapping the message in parenthesis instead of using an equal sign:

    document.getElementById("JS_heading").innerHTML("JavaScript is Awesome!!!");

    NOTE: While the code above works if it is BELOW the code that it refers to, if you were to MOVE the same script ABOVE the heading, it will not work.

  3. Move the entire script tag BELOW the heading tag.

    <script>
    document.getElementById("JS_heading").innerHTML = "JavaScript is Awesome!!!";
    </script>

    <h1 id="JS_heading">JavaScript Vital Few</h1>

  4. CHECK POINT: Save the file and preview it in a browser. You should see that the heading DID NOT change to "JavaScript is Awesome!!!" because the script is executed BEFORE it could refer the object (heading) it needed in the code itself. To resolve this problem, we will wrap the code in a window.onload code block in the next step.

  5. Move the script tag BELOW the <h1> tag:

    <h1 id="JS_heading">JavaScript Vital Few</h1>
    <script>
    document.getElementById("JS_heading").innerHTML = "JavaScript is Awesome!!!";
    </script>


  6. CHECK POINT: Save the file and preview it in a browser. You should see the header now displayed "JavaScript is Awesome!!!" because the h1 tag is stored in memory and can be referenced by the code with it reachs the script code. However, is is not best practice to have the script code in the body of the page.

  7. Move the script block back in the head and then wrap the entire line within a window.onload code block:

    <script>
    // alert("Hello, World"); window.onload = function() {
    document.getElementById("JS_heading").innerHTML = "JavaScript is Awesome!!!";
    } // end of window.load code block
    </script> </head>

  8. CHECK POINT: Save the file and preview it in a browser. You should see the header now displayed "JavaScript is Awesome!!!" even though the script is ABOVE the heading tag because this time the page loads first because of the window.onload code block and then the code executes and has a reference to the heading tag it needs to communicate with.

Make A Button Interactive

In the first example above, the alert dialog box displayed before the page even loads. Typically, you want an something to happen (e.g., an alert dialog box to be displayed) only after an event happens (e.g., a button is clicked).

There are four ways to make a button interactive:

The first way is to embed an event handler directly inside an element. While this is the easy way to create an event, it is the least preferred method because you are tightly coupling the HTML code which makes it harder to reuse.

  1. Write the following code for a button tag with an in-line event handler below the heading tag:

    <h1 id="JS_heading">JavaScript Vital Few</h1>
    <button onClick="alert('Hello, World')">Click to open Alert</button>
    NOTE: Notice that the attribute is onClick and not onclick. Also note the statement is in single quotes because that attribute is in double quotes. Also, multiple statements could be added by separating them with semicolon.

  2. CHECK POINT: Save the file and preview it in a browser. You should see that the alert dialog box does not show immediately as before. It only displays when you "click on" the button as the onclick method implies.

The second way is to write a function in the <head> and make a call to it FROM another object (e.g., a button). While this is a better approach is still couples that code (e.g., event handler) with the object (e.g., button):

  1. Replace the alert statement ("alert('Hello, World')") with the following function name INSIDE the button tag:

    <button onClick="showAlert()">Click to open Alert</button>

  2. OUTSIDE of the window.onload code block but WITHIN the script tag, write the showAlert function:

    <script>
    window.onload = function() {
    document.getElementById("JS_heading").innerHTML = "JavaScript is Awesome!!!";
    } // end of window.load code block
    function showAlert()
    {
    alert("Hello, World");
    }
    </script>

  3. CHECK POINT: Save the file and preview it in a browser. You should see that it works as before. However, this time while the code (event handler function) is still coupled to the object (button), it is not as tightly coupled as the inline event handler in the previous example.

    IMPORTANT NOTE: It is important to note that the function is placed OUTSIDE of the window.onload code block. That's because the window.online code block only execute ONCE. So if you attempt to call the showAlert() function after the page loads, it would execute.

The third way is to write an event using the object dot syntax that uses an anynomous function (e.g., object.event):

  1. Add an id attribute to the button tag AND delete the event handler (onClick="alert('Hello, World')").

    <button id="showAlertButton">Click to open Alert</button>

  2. Write the following highlighted code and comment out the showAlert function as it will be used again later.

    <script>
    // alert("Hello, World");
    window.onload = function() {
    document.getElementById("JS_heading").innerHTML = "JavaScript is Awesome!!!";

    var alertButton = document.getElementById("showAlertButton");
    alertButton.onclick = function()
    {
    alert("Hello, World");
    }
    } // end of window.load code block /*function showAlert()
    {
    alert("Hello, World");
    }*/

    </script>
    NOTE: Unlike a regular function that needs to be called or invoked outside of the function, this anynomous function is "called" when an event happens and as such there is no need for a function name.

  3. CHECK POINT: Save the file and preview it in a browser. You should see that it works as before but this time the click event is called FROM the code TO the button. In the previous examples, the click event was called FROM the button TO the code. While this is even better, it still couples the code and the object together.

The last and best way to make an button interactive is to get a reference to the object in code and then tell the object to do something when an event happens. This is accomplished by usin an addEventListener using the following syntax that listen for an event and then run a function when the event happens.

element.addEventListener('eventName', eventHandler, boolean)

  1. Replace the onclick event handler with an addEventListener:

    var alertButton = document.getElementById("showAlertButton");
    alertButton.addEventListener("click", function(){alert("Hello, World")});
    } // end of window.load code block
    NOTE: Notice the event is without the word "on" as used with a click handler. You also have an removeEventListener to remove the event once it is not needed anymore.

  2. CHECK POINT: Save the file and preview it in a browser. You should see that it works as before but this time the code is UNCOUPLED from the object. As such, you can copy the code and paste in in another page within a window.load code block and then give the object the same name or a difference name in the code and object and it will work the same. However, having the function INSIDE of addEventListener method is not recommeded. This will be fix in the next step.
  3. Uncomment and move the showAlert function INSIDE of the window.load code block:

    <script>
    // alert("Hello, World");
    window.onload = function() {
    document.getElementById("JS_heading").innerHTML = "JavaScript is Awesome!!!";

    var alertButton = document.getElementById("showAlertButton");
    alertButton.addEventListener("click", showAlert);
    function showAlert()
    {
    alert("Hello, World");
    }

    } // end of window.load code block
    </script>

  4. CHECK POINT: Save the file and preview it in a browser. You should see that it works as before but this time the code is easier to read and update.