Search code examples
javascriptjquerymarquee

Trying to reverse the direction of marquee loop javascript


I'm working from this code to create marquee, but I want the marquee to go left-to-right instead of right-to-left. I was able to make that happen but now the text doesn't loop like it did in the original.

Can't figure it out!

This is what I did to make the marquee scroll to the right:

function MarqueeOne(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);
}

I just took the - out of the -${i}px on line 11. This reverses the direction but now the text just scrolls off of the screen.

here's my CSS:

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

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

any advice on how to make this loop properly?


Solution

  • Hi i have edited your code and it's slide from left to right. I added flex-direction prop as row-reverse to css and it works fine. New css style is below.

    function Marquee(selector, speed) {
      const parentSelector = document.querySelector(selector);
      const clone = parentSelector.innerHTML;
    
      parentSelector.insertAdjacentHTML('beforeend', clone);
      parentSelector.insertAdjacentHTML('beforeend', clone);
      const firstElement = parentSelector.children[0];
      let i = 0;
      setInterval(function () {
        firstElement.style.marginRight = `-${i}px`;
        if (i > firstElement.clientWidth) {
          i = 0;
        }
        i = i + speed;
      }, 0);
    }
    window.addEventListener('load', Marquee('.marquee', 0.2))
    .marquee {
      overflow: hidden;
      border-top: 1px solid #000;
      border-bottom: 1px solid #000;
      display: flex;
      flex-direction: row-reverse;
    }
    
    .marquee h1{
      font-size: 5em;
      white-space: nowrap;
      text-transform: uppercase
    }
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Cemil</title></head>
      <body>
      <div class="marquee">
        <h1>Nepal * Himalayas * Mountains * Everest</h1>
      </div>
      </body>
    </html>