Javascript

Dynamically Changing Content with Custom Objects

Dynamically Changing Content with Custom JavaScript Objects

JavaScript objects let you organize data and logic, while DOM manipulation lets you update the webpage dynamically. Combining both gives you powerful ways to display and update content based on object data.

Let’s see how!


Step 1: Define a Custom Object

Imagine you have an object representing a product:

js
const product = {
name: "Wireless Headphones",
price: 99.99,
description: "High-quality sound with noise cancellation.",
updatePrice(newPrice) {
this.price = newPrice;
}
};
  • Properties store product details.

  • The updatePrice method lets you change the price.


Step 2: Create HTML Structure to Display Content

html
<div id="productInfo">
<h2 id="productName"></h2>
<p id="productDescription"></p>
<p>Price: $<span id="productPrice"></span></p>
<button id="discountBtn">Apply 20% Discount</button>
</div>

Step 3: Use JavaScript to Dynamically Insert Content

js
const nameEl = document.getElementById('productName');
const descEl = document.getElementById('productDescription');
const priceEl = document.getElementById('productPrice');
const discountBtn = document.getElementById('discountBtn');

// Function to render product info
function renderProduct() {
nameEl.textContent = product.name;
descEl.textContent = product.description;
priceEl.textContent = product.price.toFixed(2);
}

// Initial render
renderProduct();

// Add event listener to button to update price
discountBtn.addEventListener('click', () => {
const discountedPrice = product.price * 0.8;
product.updatePrice(discountedPrice);
renderProduct(); // Re-render updated product info
});


How It Works:

  • Initially, the product details are inserted into the DOM.

  • Clicking the Apply 20% Discount button updates the product price in the object.

  • Then, the updated info is rendered again on the page — dynamically updating content without reload.


Why Use This Pattern?

  • Keeps data (product info) separate and structured in an object.

  • Updates to data are reflected immediately in the UI.

  • Scales well: add more properties or methods without messing with DOM code.


Bonus: Expanding the Object

You can add more methods like:

js
product.changeName = function(newName) {
this.name = newName;
};

Then update the UI by calling renderProduct() again.


Summary

  • Use custom JavaScript objects to store and manage data.

  • Use DOM manipulation to dynamically show that data on the webpage.

  • Update object properties and re-render content to reflect changes instantly.

Leave a Reply

Your email address will not be published. Required fields are marked *