Learn how to create an alert ticker using HTML, CSS, and JavaScript with this easy-to-follow guide. Perfect for beginners looking to enhance their web development skills.
Table of Contents
Creating an alert ticker can add a dynamic touch to your website, making it more engaging for visitors. An alert ticker is a scrolling text box that displays important messages or updates. In this guide, we'll walk you through the process of creating an alert ticker using HTML, CSS, and JavaScript. Whether you’re a beginner or just looking to add a new feature to your site, this tutorial is designed to be straightforward and easy to follow.
Source Code
Step 1 (HTML Code):
Start by creating a basic HTML structure. This will include a container for the ticker and the alert messages.
Here's an explanation of the HTML code:
1. <!DOCTYPE html>
: This declaration defines the document type and version of HTML (HTML5 here). It helps the browser render the page correctly.
2. <html lang="en">
: The root element of the HTML document. The lang="en" attribute specifies that the document's language is English.
3. <head>
: Contains meta-information about the document:
<meta charset="UTF-8">
: Sets the character encoding to UTF-8, which includes most characters from all languages.<meta name="viewport" content="width=device-width, initial-scale=1.0">
: Ensures the page is responsive and scales correctly on different devices, setting the width to the device's width and the initial zoom level to 1.<title>
Alert Ticker</title>
: Sets the title of the webpage, which appears in the browser's title bar or tab.<link rel="stylesheet" href="https://fonts.googleapis.com/...;
: Links to a Google Fonts stylesheet to use the Poppins font in different weights.<link rel="stylesheet" href="styles.css">
: Links to an external CSS file (styles.css) for additional styling of the page.
4. <body>
: Contains the content of the webpage:
<div class="news-ticker-container">
: A container for the news ticker element.<div class="news-ticker">
: The main container for the ticker.<div class="ticker-text">
: Contains the ticker items.<span class="news-item" data-text="...">
</span>
: Each<span>
represents a news item, with the data-text attribute holding the text of the news item.
5. <script src="script.js">
</script>
: Links to an external JavaScript file (script.js) that contains the functionality for the news ticker, such as animating the ticker or handling the display of news items.
Step 2 (CSS Code):
Next, style your ticker to make it visually appealing. This involves setting up the dimensions, colors, and animations.
Here's an explanation of the CSS code:
Global Styles
body
:font-family: 'Poppins', sans-serif;
: Sets the font for the entire page to Poppins, falling back to a generic sans-serif font if Poppins isn't available.margin: 0;
: Removes default margin around the body.padding: 0;
: Removes default padding around the body.display: flex;
: Uses Flexbox for layout, aligning children elements in a flexible way.justify-content: center;
: Centers the content horizontally within the body.height: 100vh;
: Sets the height of the body to 100% of the viewport height.background: #f4f4f9;
: Sets a light gray background color.color: #fff;
: Sets the text color to white.
News Ticker Container
.news-ticker-container
:width: 100%;
: Makes the container take up the full width of its parent element.max-width: 700px;
: Limits the container's width to a maximum of 700px.padding: 15px;
: Adds padding inside the container.box-sizing: border-box;
: Ensures padding and border are included in the element's total width and height.
News Ticker
.news-ticker
:background: linear-gradient(135deg, #ff416c, #ff4b2b);
: Applies a diagonal gradient background from pink to red.padding: 15px;
: Adds padding inside the ticker.border-radius: 10px;
: Rounds the corners of the ticker.box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
: Adds a shadow below the ticker to create a sense of depth.overflow: hidden;
: Hides any content that overflows the ticker's boundaries.position: relative;
: Positions the ticker relative to its normal position, allowing for absolute positioning of child elements.
Ticker Text
.ticker-text
:display: flex;
: Uses Flexbox for layout within the ticker.align-items: center;
: Vertically centers items within the ticker.height: 100%;
: Makes the ticker text take up the full height of its parent.overflow: hidden;
: Hides any text that overflows the ticker's boundaries.white-space: nowrap;
: Prevents the text from wrapping to the next line.font-size: 20px;
: Sets the font size to 20 pixels.font-weight: 600;
: Sets the font weight to 600 (semi-bold).
News Item
.news-item
:display: none;
: Hides the news items by default.position: absolute;
: Positions the items absolutely within the ticker, allowing for overlapping content.
Keyframe Animations
@keyframes typing
: Defines a typing animation that gradually increases the width from 0 to 100%.@keyframes blink-caret
: Creates a blinking caret effect by toggling the border color between transparent and a semi-transparent white.@keyframes typing-caret
: Simulates a typing caret by changing its content between "_" and an empty string.
Caret Animation
.ticker-text::after
:content: "_";
: Adds a caret (underscore) after the text content.animation: typing-caret 1s steps(1, end) infinite;
: Applies the caret animation, making it blink with a 1-second cycle.
body {
font-family: 'Poppins', sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
height: 100vh;
background: #f4f4f9;
color: #fff;
}
.news-ticker-container {
width: 100%;
max-width: 700px;
padding: 15px;
box-sizing: border-box;
}
.news-ticker {
background: linear-gradient(135deg, #ff416c, #ff4b2b);
padding: 15px;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
overflow: hidden;
position: relative;
}
.ticker-text {
display: flex;
align-items: center;
height: 100%;
overflow: hidden;
white-space: nowrap;
font-size: 20px;
font-weight: 600;
}
.news-item {
display: none;
position: absolute;
}
@keyframes typing {
from { width: 0; }
to { width: 100%; }
}
@keyframes blink-caret {
from, to { border-color: transparent; }
50% { border-color: rgba(255, 255, 255, 0.75); }
}
@keyframes typing-caret {
0% { content: "_"; }
50% { content: ""; }
100% { content: "_"; }
}
.ticker-text::after {
content: "_";
animation: typing-caret 1s steps(1, end) infinite;
}
Step 3 (JavaScript Code):
Finally, we need to create a function in JavaScript.
Here's an explanation of the JavaScript code:
1. Selecting News Items
const newsItems = document.querySelectorAll('.news-item');
document.querySelectorAll('.news-item')
: Selects all elements with the classnews-item
and stores them in thenewsItems
NodeList.
2. Index Initialization
let index = 0;
index
: A variable to keep track of the current news item being displayed.
3. Typing Animation Function
function typeWriter(text, i, fnCallback) { if (i < text.length) { document.querySelector('.ticker-text').innerHTML = text.substring(0, i + 1); setTimeout(() => { typeWriter(text, i + 1, fnCallback); }, 100); } else if (typeof fnCallback === 'function') { setTimeout(fnCallback, 1000); } }
typeWriter(text, i, fnCallback)
: This function simulates typing text character by character.text
: The full text to be typed.i
: The current character index to be displayed.fnCallback
: A callback function to execute after the typing is finished.document.querySelector('.ticker-text').innerHTML = text.substring(0, i + 1);
: Updates the text content of the ticker to show the current typed portion.setTimeout(() => { typeWriter(text, i + 1, fnCallback); }, 100);
: CallstypeWriter
recursively to type the next character after a 100ms delay.else if (typeof fnCallback === 'function') { setTimeout(fnCallback, 1000); }
: If typing is complete and a callback is provided, it executes the callback after a 1000ms delay (1 second).
4. Starting Text Animation
function startTextAnimation(i) { if (typeof newsItems[i] === 'undefined') { setTimeout(() => { startTextAnimation(0); }, 2000); } else { const text = newsItems[i].getAttribute('data-text'); typeWriter(text, 0, () => { startTextAnimation(i + 1); }); } }
startTextAnimation(i)
: Manages the animation of news items.if (typeof newsItems[i] === 'undefined') { setTimeout(() => { startTextAnimation(0); }, 2000); }
: If the current indexi
exceeds the number of news items, restart the animation from the first item after a 2000ms delay (2 seconds).else { const text = newsItems[i].getAttribute('data-text'); typeWriter(text, 0, () => { startTextAnimation(i + 1); }); }
: If there are more news items, get the text from thedata-text
attribute, start the typing animation for that text, and then callstartTextAnimation
with the next index once the typing is complete.
5. Starting the Animation on Page Load
document.addEventListener('DOMContentLoaded', () => { startTextAnimation(0); });
document.addEventListener('DOMContentLoaded', () => { startTextAnimation(0); });
: Ensures that the typing animation starts as soon as the DOM content is fully loaded.
const newsItems = document.querySelectorAll('.news-item');
let index = 0;
function typeWriter(text, i, fnCallback) {
if (i < text.length) {
document.querySelector('.ticker-text').innerHTML = text.substring(0, i + 1);
setTimeout(() => {
typeWriter(text, i + 1, fnCallback);
}, 100);
} else if (typeof fnCallback === 'function') {
setTimeout(fnCallback, 1000);
}
}
function startTextAnimation(i) {
if (typeof newsItems[i] === 'undefined') {
setTimeout(() => {
startTextAnimation(0);
}, 2000);
} else {
const text = newsItems[i].getAttribute('data-text');
typeWriter(text, 0, () => {
startTextAnimation(i + 1);
});
}
}
document.addEventListener('DOMContentLoaded', () => {
startTextAnimation(0);
});
Final Output:
Conclusion:
Congratulations! You've successfully created an alert ticker using HTML, CSS, and JavaScript. This simple feature can help keep your visitors informed and engaged. By following these steps, you’ve learned how to set up the HTML structure, style it with CSS, and add dynamic content with JavaScript. Feel free to customize the ticker to fit your website's design and messaging needs.
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊