News ticker js
A news ticker is a scrolling display of news headlines or updates that can be used on a website or application. Here is an example of how you can create a basic news ticker using JavaScript:
HTML:
<div id="news-ticker"></div>
CSS:
#news-ticker {
width: 300px;
height: 20px;
overflow: hidden;
background-color: #f0f0f0;
padding: 10px;
border: 1px solid #ccc;
font-size: 14px;
font-family: Arial, sans-serif;
}
#news-ticker span {
display: inline-block;
width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
JavaScript:
var newsTicker = document.getElementById("news-ticker");
var newsItems = ["News Item 1", "News Item 2", "News Item 3", "News Item 4", "News Item 5"];
var newsIndex = 0;
function updateTicker() {
newsTicker.innerHTML = "";
for (var i = 0; i < newsItems.length; i++) {
var newsItem = newsItems[i];
var newsSpan = document.createElement("span");
newsSpan.textContent = newsItem;
newsTicker.appendChild(newsSpan);
}
newsTicker.scrollLeft = newsIndex * newsTicker.offsetWidth;
newsIndex = (newsIndex + 1) % newsItems.length;
setTimeout(updateTicker, 5000); // update every 5 seconds
}
updateTicker();
This code creates a div
element with the ID "news-ticker" and sets its styles using CSS. It then creates an array of news items and initializes a variable newsIndex
to 0.
The updateTicker
function is called every 5 seconds using setTimeout
. It clears the news-ticker
element and appends each news item to it as a span
element. It then sets the scrollLeft
property of the news-ticker
element to the current newsIndex
multiplied by the width of the element, which scrolls the news items to the left. Finally, it increments the newsIndex
and updates the news-ticker
element.
You can customize this code to fit your specific needs, such as changing the speed of the scrolling or adding more features like pause and resume.
Here is a working example of the news ticker:
Note: This is a basic example and you may want to add more features like handling multiple news items, adding images, or making it responsive.