0

Sorry if I misphrase anything, not sure how to phrase the need I'm having.

Say I have a paragraph inside a div:

<div style="width: 50px">
    <p>Hi</p>
</div>
  1. I want to move the paragraph (which covers 0-2px), up until the 50px.
  2. When it reaches 49/50, 1 letter will be gone.
  3. When it reaches 50/50, all 2 letters be gone, and the same behavior will start again, from scratch...

To clarify: I mean to create these "old school" moving text bars, in which a text starts in the right edge of the bar, and moves pixel after pixel, in some speed, to the left edge, disappears, and again the same pattern.

I didn't find any code for "moving a text" (surly not in ES6) [1], [2]. Most of what I found is in Jquery, like this article, but I desire an ES6 vanilla solution.

Osi
  • 1
  • 3
  • 9
  • 30

2 Answers2

4

You can achieve that with CSS animations:

div {
  overflow: hidden;
}

p {
  animation: marquee 2s linear infinite;
}

@keyframes marquee {
  from {transform: translateX(-100%); }
  to {transform: translateX(100%); }
}
<div style="width: 50px">
    <p>Hi</p>
</div>
FcoRodr
  • 1,583
  • 7
  • 15
0

I updated an old Javascript solution on SO below:

const marquees = [...document.querySelectorAll('.marquee')];
marquees.forEach((marquee) => {
  marquee.innerHTML = marquee.innerHTML + '&nbsp;'.repeat(5);
  marquee.i = 0;
  marquee.step = 3;
 marquee.width = (marquee.clientWidth + 1);
  marquee.style.position = '';
  marquee.innerHTML = `${marquee.innerHTML}&nbsp;`.repeat(10);
  marquee.addEventListener('mouseenter', () => marquee.step = 0, false);
  marquee.addEventListener('mouseleave', () => marquee.step = 3, false);
});

setInterval(move, 50);

function move() {
  marquees
  .forEach((marquee) => {
  marquee.style.marginLeft = `-${marquee.i}px`;;
  marquee.i = marquee.i < marquee.width ? marquee.i + marquee.step : 1;
  }); 
}
// Modified from StackOverflow answer by Stano:
// https://stackoverflow.com/questions/337330/javascript-marquee-to-replace-marquee-tags
.marquee {
    background: #eee;
    overflow: hidden;
    white-space: nowrap;
    position: absolute;
}
<div class="marquee">Hey there!</div>

Hopefully this helps. Cheers!

JSFiddle

LMulvey
  • 1,662
  • 8
  • 14