How to display multiple news with marquee
A classic web design element!
To display multiple news items with a marquee effect, you can use HTML, CSS, and JavaScript. Here's a basic example to get you started:
HTML:
<div class="marquee">
<ul>
<li>News Item 1</li>
<li>News Item 2</li>
<li>News Item 3</li>
<li>News Item 4</li>
<li>News Item 5</li>
</ul>
</div>
CSS:
.marquee {
width: 500px; /* adjust the width to your liking */
overflow: hidden;
white-space: nowrap;
font-size: 16px;
font-family: Arial, sans-serif;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.marquee ul {
list-style: none;
margin: 0;
padding: 0;
}
.marquee li {
display: inline-block;
margin-right: 20px;
}
.marquee li:last-child {
margin-right: 0;
}
JavaScript:
// Get the marquee element
var marquee = document.querySelector('.marquee');
// Set the marquee speed (adjust to your liking)
var speed = 5; // pixels per second
// Set the marquee direction (1 = left, -1 = right)
var direction = 1;
// Set the marquee interval
var interval = setInterval(function() {
// Get the current scroll position
var scrollPosition = marquee.scrollLeft;
// Calculate the new scroll position
var newPosition = scrollPosition + (direction * speed);
// Update the scroll position
marquee.scrollLeft = newPosition;
// Check if the marquee has reached the end
if (newPosition >= marquee.scrollWidth - marquee.offsetWidth) {
direction = -1; // reverse direction
} else if (newPosition <= 0) {
direction = 1; // reverse direction
}
}, 16); // adjust the interval to your liking (lower values for faster scrolling)
How it works:
- The HTML creates a container element (
<div class="marquee">
) with an unordered list (<ul>
) containing the news items as list items (<li>
). - The CSS styles the marquee container and its contents, including setting the width, font, and padding.
- The JavaScript code gets the marquee element, sets the marquee speed and direction, and sets an interval to update the scroll position every 16 milliseconds (adjustable).
- The JavaScript code calculates the new scroll position based on the current position, speed, and direction.
- The JavaScript code updates the scroll position and checks if the marquee has reached the end. If so, it reverses the direction.
Tips and variations:
- Adjust the
speed
variable to control the marquee speed. - Adjust the
interval
value to control the marquee scrolling frequency. - Add more news items to the list by adding more
<li>
elements. - Use a different font or font size to change the appearance of the marquee.
- Add a pause or stop button to the marquee using JavaScript.
- Use a different marquee direction (e.g., vertical) by adjusting the
direction
variable and the CSS styles.
I hope this helps you create a basic marquee effect with multiple news items!