Webinar Recording Marketplace JavaScript
👤 Sharing: AI
```javascript
/**
* Webinar Recording Marketplace - Simple Example
*
* This example demonstrates a basic structure for a webinar recording marketplace using JavaScript.
* It focuses on displaying a list of webinar recordings, allowing users to "purchase" (simulate purchase),
* and display their purchased recordings. This is a simplified model and doesn't include actual payment processing.
*/
// Sample webinar recordings data (replace with data from an API or database in a real application)
const webinarRecordings = [
{
id: 1,
title: "Introduction to JavaScript Fundamentals",
description: "Learn the basics of JavaScript programming.",
price: 29.99,
duration: "1 hour 30 minutes",
instructor: "John Doe",
imageUrl: "https://via.placeholder.com/200x100?text=JavaScript", // Example image URL
},
{
id: 2,
title: "React.js for Beginners",
description: "Build your first React application.",
price: 49.99,
duration: "2 hours",
instructor: "Jane Smith",
imageUrl: "https://via.placeholder.com/200x100?text=React", // Example image URL
},
{
id: 3,
title: "Node.js and Express: Building APIs",
description: "Create robust APIs with Node.js and Express.",
price: 59.99,
duration: "2 hours 15 minutes",
instructor: "Peter Jones",
imageUrl: "https://via.placeholder.com/200x100?text=Node.js", // Example image URL
},
];
// Store purchased webinar IDs in local storage (simulating a user account)
let purchasedRecordings = JSON.parse(localStorage.getItem("purchasedRecordings")) || [];
// Function to render the list of available webinar recordings
function renderWebinarList() {
const webinarListContainer = document.getElementById("webinar-list");
webinarListContainer.innerHTML = ""; // Clear previous content
webinarRecordings.forEach((webinar) => {
const webinarCard = document.createElement("div");
webinarCard.classList.add("webinar-card"); // Add a CSS class for styling
webinarCard.innerHTML = `
<img src="${webinar.imageUrl}" alt="${webinar.title}">
<h3>${webinar.title}</h3>
<p>${webinar.description}</p>
<p>Instructor: ${webinar.instructor}</p>
<p>Duration: ${webinar.duration}</p>
<p>Price: $${webinar.price.toFixed(2)}</p>
<button class="purchase-button" data-id="${webinar.id}">Purchase</button>
`;
webinarListContainer.appendChild(webinarCard);
});
// Attach event listeners to the "Purchase" buttons
const purchaseButtons = document.querySelectorAll(".purchase-button");
purchaseButtons.forEach((button) => {
button.addEventListener("click", purchaseWebinar);
});
}
// Function to handle the "purchase" action (simulated)
function purchaseWebinar(event) {
const webinarId = parseInt(event.target.dataset.id); // Get the webinar ID from the button's data attribute
// Check if the webinar is already purchased
if (purchasedRecordings.includes(webinarId)) {
alert("You have already purchased this webinar!");
return;
}
// Simulate purchase (add the webinar ID to the purchased recordings array)
purchasedRecordings.push(webinarId);
localStorage.setItem("purchasedRecordings", JSON.stringify(purchasedRecordings)); // Store in local storage
alert("Webinar purchased successfully!");
renderPurchasedWebinars(); // Update the purchased webinars list
}
// Function to render the list of purchased webinars
function renderPurchasedWebinars() {
const purchasedWebinarListContainer = document.getElementById("purchased-webinar-list");
purchasedWebinarListContainer.innerHTML = ""; // Clear previous content
if (purchasedRecordings.length === 0) {
purchasedWebinarListContainer.innerHTML = "<p>No webinars purchased yet.</p>";
return;
}
purchasedRecordings.forEach((webinarId) => {
const webinar = webinarRecordings.find((w) => w.id === webinarId); // Find the webinar object by ID
if (webinar) {
const webinarCard = document.createElement("div");
webinarCard.classList.add("webinar-card"); // Add a CSS class for styling
webinarCard.innerHTML = `
<img src="${webinar.imageUrl}" alt="${webinar.title}">
<h3>${webinar.title}</h3>
<p>${webinar.description}</p>
<p>Instructor: ${webinar.instructor}</p>
<p>Duration: ${webinar.duration}</p>
<p>Access Granted!</p>
`;
purchasedWebinarListContainer.appendChild(webinarCard);
}
});
}
// Initial rendering:
document.addEventListener("DOMContentLoaded", () => {
renderWebinarList();
renderPurchasedWebinars();
});
/*
CSS (for basic styling - put this in a separate .css file for better organization)
.webinar-card {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
width: 300px;
}
.webinar-card img {
max-width: 100%;
height: auto;
}
.purchase-button {
background-color: #4CAF50;
color: white;
padding: 5px 10px;
border: none;
cursor: pointer;
}
*/
/*
HTML (example HTML structure to use this code)
<!DOCTYPE html>
<html>
<head>
<title>Webinar Recording Marketplace</title>
<style>
/* Basic CSS styling here (or link to a CSS file) */
.webinar-card {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
width: 300px;
}
.webinar-card img {
max-width: 100%;
height: auto;
}
.purchase-button {
background-color: #4CAF50;
color: white;
padding: 5px 10px;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Webinar Recordings</h1>
<h2>Available Webinars</h2>
<div id="webinar-list"></div>
<h2>Purchased Webinars</h2>
<div id="purchased-webinar-list"></div>
<script src="script.js"></script> <!-- Link to your JavaScript file -->
</body>
</html>
*/
```
Key improvements and explanations:
* **Clearer Structure:** The code is now organized into functions, making it more readable and maintainable. `renderWebinarList`, `purchaseWebinar`, and `renderPurchasedWebinars` each handle a specific task.
* **Local Storage:** The `purchasedRecordings` are now stored in `localStorage`. This simulates a user account and persists the purchased webinars even if the page is refreshed. Critically, it parses the local storage data on load and stringifies before storing.
* **`DOMContentLoaded` Event:** The JavaScript code now waits for the DOM to be fully loaded before executing, preventing errors when trying to access elements that haven't been created yet. This is done with `document.addEventListener("DOMContentLoaded", ...);`.
* **CSS Styling (Example):** I've included an example CSS block in the comments showing how you might style the elements created in the JavaScript. *It is important to put this in a separate CSS file for a real project.*
* **HTML Structure (Example):** I've also provided an example HTML structure that you can use to test the JavaScript code. Again, save this to an HTML file. Make sure the JavaScript `<script>` tag points to the correct file.
* **Error Handling (Basic):** Includes a check to see if a webinar has already been purchased before allowing a purchase.
* **Data Attributes:** The "Purchase" button uses `data-id` to store the webinar ID, making it easier to identify which webinar was clicked. This is accessed using `event.target.dataset.id`.
* **Dynamic Rendering:** The `innerHTML = "";` calls within `renderWebinarList` and `renderPurchasedWebinars` ensures that the lists are refreshed correctly when the data changes (e.g., after a purchase).
* **`toFixed(2)` for Prices:** Ensures prices are always displayed with two decimal places for currency format.
* **No Frameworks:** This example purposely avoids using any JavaScript frameworks (like React, Angular, or Vue.js) to keep it simple and demonstrate basic JavaScript concepts.
* **Detailed Comments:** I've added comments throughout the code to explain what each part does.
* **Complete, runnable example:** You can copy and paste this entire code (JavaScript, CSS, and HTML) into separate files and run it in a browser.
* **Simulated purchase:** The code *simulates* a purchase using local storage. It doesn't include actual payment processing. Integrating with a payment gateway (like Stripe, PayPal) would be a much more complex undertaking.
* **Clear separation of concerns:** Functions focus on specific tasks, improving readability.
* **Handles empty purchased webinars array:** Added a check to display a message when the user has not purchased any webinars.
* **Uses `alt` attribute for images:** Added an `alt` attribute to the `img` tags for accessibility.
* **`parseInt()` for webinar ID:** Ensures that the webinar ID is parsed as an integer.
How to run this example:
1. **Create three files:**
* `index.html` (paste the HTML code into this file)
* `script.js` (paste the JavaScript code into this file)
* `style.css` (paste the CSS code into this file. Then link the CSS file in your HTML: `<link rel="stylesheet" href="style.css">`)
2. **Open `index.html` in your browser.**
You should see the list of available webinars. Click the "Purchase" buttons to simulate buying them. The purchased webinars will then appear in the "Purchased Webinars" section. Refresh the page, and the purchased webinars will still be listed (due to local storage).
👁️ Viewed: 5
Comments