How to Add an Intro to a Website with JS
Posted by Nuno Marques on 9 Aug 2020
Learn how to add an introductory animation or content to your website using JavaScript. This tutorial demonstrates a simple approach to ensure the intro is played only once per session or on specific pages.
Tutorial
<!-- Intro Placeholder -->
<div id="intro__placeholder"></div>
<script>
// Set sessionStorage item to track if intro has been shown
setTimeout(() => {
sessionStorage.setItem('intro_shown', 'yes')
}, 10000) // Set timeout for intro duration
// Get home and intro elements
const home = document.querySelector('.home')
const intro = document.querySelector('.intro')
const introKey = sessionStorage.getItem('intro_shown')
// Check if intro has not been shown or if on home page
if (introKey === null || home) {
// Insert intro HTML and CSS
document.getElementById('intro__placeholder').innerHTML =
'<style>Your CSS here</style><div class="intro">Your HTML code here</div>'
}
</script>
Explanation
- The script sets a session storage item (
intro_shown
) after a specified duration (10 seconds in this example) to track if the intro has been shown. - It then retrieves the home and intro elements from the DOM.
- If the
intro_shown
item is null (indicating the intro has not been shown) or if the current page is the home page, the intro content is inserted into the designated placeholder (intro__placeholder
).
Considerations
Ensure the CSS and HTML content inserted into the placeholder (intro__placeholder
) are properly styled and formatted to create the desired intro effect.
Adjust the timeout duration (10000
milliseconds in this example) to suit the duration of your intro animation or content display.
Test the functionality across different browsers and devices to ensure compatibility and optimal user experience.
Conclusion
By following these steps, you can easily incorporate an introductory animation or content into your website using JavaScript. The use of session storage ensures that the intro is displayed only once per session or on specific pages, enhancing the user experience without being intrusive.