Javascript news ticker
A JavaScript news ticker! Here's a simple example to get you started:
HTML
<div id="news-ticker"></div>
CSS
#news-ticker {
position: relative;
width: 300px; /* adjust to your desired width */
height: 20px; /* adjust to your desired height */
overflow: hidden;
background-color: #f0f0f0;
padding: 5px;
border: 1px solid #ccc;
}
#news-ticker ul {
list-style: none;
margin: 0;
padding: 0;
}
#news-ticker li {
display: inline-block;
margin-right: 10px;
font-size: 14px;
font-weight: bold;
color: #333;
}
#news-ticker li:last-child {
margin-right: 0;
}
JavaScript
const newsTicker = document.getElementById('news-ticker');
const newsItems = [
'Breaking News: COVID-19 vaccine approved for emergency use',
'Stock market surges as economy shows signs of recovery',
'New study reveals surprising benefits of meditation',
'NASA's Perseverance rover discovers evidence of ancient lake on Mars',
'Weather forecast: Heavy rain expected in the Northeast'
];
let currentIndex = 0;
let intervalId = null;
function updateTicker() {
const currentNewsItem = newsItems[currentIndex];
const newsItemElement = document.createElement('li');
newsItemElement.textContent = currentNewsItem;
newsTicker.appendChild(newsItemElement);
currentIndex = (currentIndex + 1) % newsItems.length;
setTimeout(updateTicker, 5000); // update every 5 seconds
}
intervalId = setInterval(updateTicker, 5000);
This code creates a simple news ticker that displays a list of news items. Each news item is displayed for 5 seconds before being replaced by the next one. You can adjust the width, height, and other styles to fit your needs.
Here's how it works:
- We create a
newsItems
array to store the news items. - We get a reference to the
news-ticker
element usingdocument.getElementById
. - We define a
currentIndex
variable to keep track of the current news item. - We define an
intervalId
variable to store the interval ID returned bysetInterval
. - The
updateTicker
function is called every 5 seconds usingsetInterval
. It creates a newli
element, sets its text content to the current news item, and appends it to thenews-ticker
element. - We increment the
currentIndex
variable to move to the next news item. - We use the modulo operator (
%
) to wrap around to the beginning of thenewsItems
array when we reach the end.
Note that this is a basic example, and you may want to add more features, such as:
- Animating the news items (e.g., sliding or fading in/out)
- Adding a pause or stop button
- Displaying a "more" link to show additional news items
- Using a more advanced animation library (e.g., GSAP)