How to make sliding news banner in a website
A sliding news banner is a popular feature on many websites, allowing users to easily view and navigate through a list of news articles or updates. Here's a step-by-step guide on how to create a sliding news banner in a website:
HTML Structure
First, create an HTML structure for your news banner. You can use a container element (e.g., div
) to wrap all the news items. Each news item can be represented by a separate div
element with a class or ID to identify it.
<div class="news-banner">
<div class="news-item">
<h2>News Item 1</h2>
<p>This is the first news item.</p>
</div>
<div class="news-item">
<h2>News Item 2</h2>
<p>This is the second news item.</p>
</div>
<!-- Add more news items here -->
</div>
CSS Styles
Next, add CSS styles to position and style your news banner. You can use CSS transitions to create a sliding effect.
.news-banner {
position: relative;
width: 100%;
height: 200px; /* adjust the height to your liking */
overflow: hidden;
padding: 10px;
}
.news-item {
position: relative;
display: inline-block;
width: 100%;
height: 100%;
margin-right: 10px;
padding: 10px;
border-bottom: 1px solid #ccc;
transition: transform 0.5s ease-in-out;
}
.news-item:last-child {
margin-right: 0;
}
.news-item.active {
transform: translateX(0);
}
.news-item.inactive {
transform: translateX(-100%);
}
JavaScript Code
To create the sliding effect, you'll need to add JavaScript code to animate the news items. You can use a library like jQuery or vanilla JavaScript.
Using jQuery
$(document).ready(function() {
var newsItems = $(".news-item");
var newsBanner = $(".news-banner");
var currentSlide = 0;
newsItems.eq(0).addClass("active");
newsItems.on("click", function() {
var index = newsItems.index(this);
newsItems.removeClass("active");
newsItems.eq(index).addClass("active");
currentSlide = index;
});
setInterval(function() {
currentSlide = (currentSlide + 1) % newsItems.length;
newsItems.removeClass("active");
newsItems.eq(currentSlide).addClass("active");
}, 5000); // adjust the interval time to your liking
});
Using Vanilla JavaScript
const newsItems = document.querySelectorAll(".news-item");
const newsBanner = document.querySelector(".news-banner");
let currentSlide = 0;
newsItems.forEach((item, index) => {
if (index === 0) {
item.classList.add("active");
}
});
newsItems.forEach((item) => {
item.addEventListener("click", () => {
newsItems.forEach((item) => item.classList.remove("active"));
item.classList.add("active");
currentSlide = newsItems.indexOf(item);
});
});
setInterval(() => {
currentSlide = (currentSlide + 1) % newsItems.length;
newsItems.forEach((item) => item.classList.remove("active"));
newsItems[currentSlide].classList.add("active");
}, 5000); // adjust the interval time to your liking
Putting it all together
Combine the HTML, CSS, and JavaScript code to create a sliding news banner on your website.
Remember to adjust the styles and JavaScript code to fit your specific needs and design requirements.