From fd90e1e862cb0cb7114184bdfe902bf0e3edfe73 Mon Sep 17 00:00:00 2001 From: vista-man <524715@vistacollege.nl> Date: Sat, 25 Jan 2025 21:46:33 +0100 Subject: [PATCH] refactor fade-in effect in script.js for smoother opacity transition --- script.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/script.js b/script.js index b75fd82..88a5e2a 100644 --- a/script.js +++ b/script.js @@ -2,25 +2,26 @@ window.onload = function() { // Select all paragraphs that immediately follow an h2 element const articles = document.querySelectorAll('h2 + p'); - articles.forEach(article => { + articles.forEach((article, index) => { // Set initial opacity of each article to 0 (hidden) article.style.opacity = '0'; // Function to gradually increase the opacity of the article const fadeIn = () => { let opacity = 0; - const interval = setInterval(() => { + const increaseOpacity = () => { opacity += 0.05; article.style.opacity = opacity; - // Stop the interval when opacity reaches 1 (fully visible) - if (opacity >= 1) { - clearInterval(interval); + // Continue the animation until opacity reaches 1 (fully visible) + if (opacity < 1) { + requestAnimationFrame(increaseOpacity); } - }, 30); + }; + requestAnimationFrame(increaseOpacity); }; // Delay the fade-in effect based on the article's index - setTimeout(fadeIn, 500 * articles.indexOf(article)); + setTimeout(fadeIn, 500 * index); }); }; \ No newline at end of file