Lesson Nineteen: Introduction to Objects

  1. Objects allow you to develop code that is more functional, more readable, and more manageable.
  2. For this lesson you will use the same HTML and CSS code. However, you will make a new JavaScript file and link the HTML file to the new file.
  3. Enter this code into Notepad and save the file as histevents2.js. Be sure to change the link in your HTML file to call the new JavaScript file.
    var hevents1 = {
    event1: "488 Million Years Ago the Mollusks Appeared",
    image1: "images/mollusk1.jpg",
    historyevents: function() {
    h1 = document.getElementById("h1");
    h1.innerHTML = hevents1.event1;
    img = document.getElementById("i1");
    img.src = hevents1.image1;
    }
    };
    function changedesign1() {
    link = document.getElementById("link1");
    link.href = "histevents2.css";
    }
    function changedesign2() {
    link = document.getElementById("link1");
    link.href = "histevents3.css";
    }
  4. Line one in this code uses the var command to establish an object named hevents1. Lines two and three establish event1 and image1 as properties of the hevents object (the properties take the place of the variables that you used previously.) Line 4 should look familiar, it is the same function that you used in your earlier code. Only now the historyevents function becomes a property of the hevents1 object. When a property of an object is also a function it is refered to as a method. Therefore, historyevents is now a method of the hevents object.
  5. Notice that lines six and eight now use the new object and its property separated by a period.
  6. In your HTML code you now call the new object and its method with this code:
    <input type="button" id="b1" value="Next Event" onclick="hevents1.historyevents()"; >
    <img id="i1" src="images/compass2.png" alt="History Tree Compass Image" onclick="hevents1.historyevents()";

    Test your program with the new code. Your page should look like this: Sample
  7. The entire code to incorporate the rest of the events is shown in the next lesson, but try to complete the program without looking ahead.
  8. Test your program with the new code. Your page should look like this: Sample

Lesson Twenty: The Object Code