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:

  1. We create a newsItems array to store the news items.
  2. We get a reference to the news-ticker element using document.getElementById.
  3. We define a currentIndex variable to keep track of the current news item.
  4. We define an intervalId variable to store the interval ID returned by setInterval.
  5. The updateTicker function is called every 5 seconds using setInterval. It creates a new li element, sets its text content to the current news item, and appends it to the news-ticker element.
  6. We increment the currentIndex variable to move to the next news item.
  7. We use the modulo operator (%) to wrap around to the beginning of the newsItems array when we reach the end.

Note that this is a basic example, and you may want to add more features, such as: