2. Dynamic News Section (JavaScript)
To make it easier to add news dynamically (without needing to hard-code each item in HTML), you can use JavaScript to dynamically inject news content.
Example: Dynamic News Section with JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic News Section</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Latest News</h1>
<div class="news-section" id="newsSection">
<!-- News items will be injected here by JavaScript -->
</div>
<script>
// Sample news data (you can replace this with data from an API)
const newsItems = [
{
title: 'New Feature Launched',
description: 'We are excited to announce the launch of a new feature that enhances user experience on our website.',
date: 'September 21, 2024'
},
{
title: 'Upcoming Event: Developer Conference',
description: 'Join us at the Developer Conference 2024 to learn about the latest trends in software development.',
date: 'September 19, 2024'
},
{
title: 'Maintenance Update',
description: 'Our website will be undergoing scheduled maintenance on September 25, 2024. Please be aware of possible downtime.',
date: 'September 15, 2024'
}
];
// Function to dynamically add news to the page
function displayNews() {
const newsSection = document.getElementById('newsSection');
newsItems.forEach(item => {
// Create a news item element
const newsItem = document.createElement('div');
newsItem.classList.add('news-item');
// Set the inner HTML of the news item
newsItem.innerHTML = `
<h3>${item.title}</h3>
<p>${item.description}</p>
<small>Published on: ${item.date}</small>
`;
// Append the news item to the news section
newsSection.appendChild(newsItem);
});
}
// Call the function to display the news
displayNews();
</script>
</body>
</html>
CSS for above component!
#css
.news-section {
padding: 20px;
background-color: #f9f9f9;
border: 1px solid #ddd;
margin: 20px;
}
.news-item {
margin-bottom: 15px;
}
.news-item h3 {
margin: 0;
font-size: 1.5em;
}
.news-item p {
margin: 5px 0 0;
}
Review:
- JavaScript: The news items are stored in an array (
newsItems
), and thedisplayNews()
function dynamically creates and appends the news items to the DOM. - HTML: The
newsSection
div is the container where the news is injected. - This approach is dynamic, and you can easily update the
newsItems
array to add more news. Alternatively, you can fetch the news from an API and display it. - Click to see dynamic working on this query using Javascript!
Key Benefits of Using Coding Filters in Software Development!
Using coding filters brings numerous benefits to developers, such as improved maintainability, easier debugging, and enhanced performance. Filters allow developers to isolate specific pieces of logic, reducing errors and making the codebase more modular, adaptable, and easier to manage in the long term.