JavaScript objects are powerful tools that allow you to model real-world entities and their behaviors in your web applications. Integrating JavaScript objects within HTML can enhance the interactivity and functionality of your web pages. This guide explains how to create and use JavaScript objects in HTML with practical examples.


Understanding JavaScript Objects

In JavaScript, objects are collections of properties, where a property is an association between a name (or key) and a value. The value can be a primitive value (like a string or number), another object, or even a function.

Here's a simple example of an object representing a car:

 
var car = {
    make: "Toyota",
    model: "Corolla",
    year: 2020,
    start: function() {
        console.log("Car started");
    },
    drive: function() {
        console.log("Car is driving");
    },
    stop: function() {
        console.log("Car stopped");
    }
};


In this object:
  • make, model, and year are properties.
  • start, drive, and stop are methods (functions associated with the object).
  • Integrating JavaScript Objects with HTML
  • To integrate JavaScript objects with HTML, you typically use the Document Object Model (DOM) to manipulate HTML elements. Let's build a simple web page that uses a JavaScript object to manage a car's status.

Example: Car Object in HTML

We'll create a web page where you can display a car's details and use buttons to start, drive, and stop the car, updating the car's status in real-time.

HTML Structure: Define the basic structure of your HTML page.
 


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Car Object Example</title>
</head>
<body>
    <h1>Car Object Example</h1>
    <div id="car-details"></div>
    <button onclick="car.start()">Start</button>
    <button onclick="car.drive()">Drive</button>
    <button onclick="car.stop()">Stop</button>
    <p id="status"></p>

    <script src="script.js"></script>
</body>
</html>
 



JavaScript Code: Create a script.js file to define the car object and its interaction with the HTML.

var car = {
    make: "Toyota",
    model: "Corolla",
    year: 2020,
    start: function() {
        document.getElementById("status").innerText = "Car started";
    },
    drive: function() {
        document.getElementById("status").innerText = "Car is driving";
    },
    stop: function() {
        document.getElementById("status").innerText = "Car stopped";
    }
};

function displayCarDetails() {
    document.getElementById("car-details").innerText = 
        "Make: " + car.make + ", Model: " + car.model + ", Year: " + car.year;
}

document.addEventListener("DOMContentLoaded", function() {
    displayCarDetails();
});



Explanation
HTML:
  • The <div id="car-details"></div> element will display the car's details.
  • The buttons are used to trigger the start, drive, and stop methods of the car object.
  • The <p id="status"></p> element will display the current status of the car.


JavaScript:
  • The car object is defined with properties (make, model, year) and methods (start, drive, stop).
  • The displayCarDetails function updates the car-details div with the car's properties.
  • The DOMContentLoaded event listener ensures that the car details are displayed once the DOM is fully loaded.

Result

When you open the HTML file in a browser, it will display the car details and provide buttons to start, drive, and stop the car. Clicking these buttons will update the status paragraph accordingly.


Dynamic Object Creation

Sometimes, you might need to create objects dynamically based on user input. Let's extend our example to allow users to create their own car objects.


Extended HTML Structure:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dynamic Car Object Example</title>
</head>
<body>
    <h1>Dynamic Car Object Example</h1>
    <input type="text" id="make" placeholder="Make">
    <input type="text" id="model" placeholder="Model">
    <input type="number" id="year" placeholder="Year">
    <button onclick="createCar()">Create Car</button>
    
    <div id="car-list"></div>
    <p id="status"></p>

    <script src="script.js"></script>
</body>
</html>
 


Extended JavaScript Code:

 
var cars = [];

function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
    this.start = function() {
        document.getElementById("status").innerText = this.make + " started";
    };
    this.drive = function() {
        document.getElementById("status").innerText = this.make + " is driving";
    };
    this.stop = function() {
        document.getElementById("status").innerText = this.make + " stopped";
    };
}

function createCar() {
    var make = document.getElementById("make").value;
    var model = document.getElementById("model").value;
    var year = document.getElementById("year").value;
    var car = new Car(make, model, year);
    cars.push(car);
    displayCarList();
}

function displayCarList() {
    var carList = document.getElementById("car-list");
    carList.innerHTML = "";
    cars.forEach(function(car, index) {
        var listItem = document.createElement("div");
        listItem.innerText = car.make + " " + car.model + " (" + car.year + ")";
        var startButton = document.createElement("button");
        startButton.innerText = "Start";
        startButton.onclick = function() { car.start(); };
        var driveButton = document.createElement("button");
        driveButton.innerText = "Drive";
        driveButton.onclick = function() { car.drive(); };
        var stopButton = document.createElement("button");
        stopButton.innerText = "Stop";
        stopButton.onclick = function() { car.stop(); };
        
        listItem.appendChild(startButton);
        listItem.appendChild(driveButton);
        listItem.appendChild(stopButton);
        carList.appendChild(listItem);
    });
}


Explanation
  • Added input fields for make, model, and year, and a button to create a new car.
  • The <div id="car-list"></div> element will list all created cars with buttons to start, drive, and stop each car.

JavaScript:
  • The Car constructor function allows the creation of multiple car objects with unique properties and methods.
  • The createCar function reads user input, creates a new Car object, and adds it to the cars array.
  • The displayCarList function dynamically updates the HTML to display all created cars and their associated buttons.



Practice Excercise Practice now