Blog

My Log

Vanilla JS Marquee

Here is an example of creating a smooth Marquee effect using HTML/CSS and Javascript.

Here is the HTML code:

<div class="marquee">
  <h1>Nepal * Himalayas * Mountains * Everest</h1>
</div>

Here is the CSS code:

.marquee {
  overflow: hidden;
  border-top: 1px solid #000;
  border-bottom: 1px solid #000;
  display: flex;
}

.marquee h1{
  font-size: 5em;
  white-space: nowrap;
  text-transform: uppercase
}

Here is the Javascript code:

    function Marquee(selector, speed) {
      const parentSelector = document.querySelector(selector);
      const clone = parentSelector.innerHTML;
      const firstElement = parentSelector.children[0];
      let i = 0;
      console.log(firstElement);
      parentSelector.insertAdjacentHTML('beforeend', clone);
      parentSelector.insertAdjacentHTML('beforeend', clone);
    
      setInterval(function () {
        firstElement.style.marginLeft = `-${i}px`;
        if (i > firstElement.clientWidth) {
          i = 0;
        }
        i = i + speed;
      }, 0);
    }
    
    //after window is loaded
    //1 class selector for marquee
    //2 marquee speed 0.2
    window.addEventListener('load', Marquee('.marquee', 0.2))

here is the example from codepen.