Vanilla Javascript Promotion Alternator
A friend of mine has an e-commerce website that displays a promotional blurb at the top of each page. He asked if it would be possible to have multiple promos and switch between them at regular intervals. Here is my vanilla js implementation. Let me know what you think.
I used css classes to control visibility and setInterval()
to iterate through the list of promos and toggle the classes of each one.
<html> <head> <style type="text/css"> .active_promo_text { display: inline; } .inactive_promo_text { display: none; } </style> <script> const visibility_time = 5; // time, in seconds, to display each promo const promos = document.getElementsByClassName('promo_text'); let active_promo_index = 0; setInterval(() => { let previous = promos[active_promo_index]; previous.className = previous.className.replace(/active/g, "inactive"); active_promo_index++; if(active_promo_index === promos.length){ active_promo_index = 0; } let next = promos[active_promo_index]; next.className = next.className.replace(/inactive/g, "active"); }, visibility_time*1000); </script> </head> <body> <div> <span class="promo_text active_promo_text"> free 3-5 day shipping-no tax *details </span> <span class="promo_text inactive_promo_text"> Now shipping to Canada </span> <span class="promo_text inactive_promo_text"> Some other promo </span> </div> </body> </html>