Home > Software engineering >  Problem in using translate CSS transposed in JS
Problem in using translate CSS transposed in JS

Time:09-14

I made a div that translates infinitely horizontally like the marquee tag and when the mouse is over, the animation is paused ... I would like to make sure that when the mouse wheel activates its event the div translates some pixels. But in my attempt, the div stays stuck at the point where the animation was paused. Below I leave the code:

var widgets = document.querySelector(`.widgets`);

widgets.addEventListener(`wheel`, (e) => {
  widgets.style.transform = "translateX(200px) !important"
});
.main .widgets {
  display: flex;
  animation: marquee 20s linear infinite;
}

.main .widgets:hover {
  animation-play-state: paused;
}

@keyframes marquee {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}
<div >
  <div >
    <div >classeviva</div>
    <div >moodle</div>
    <div >circolari</div>
    <div >gmail</div>
    <div >ECDL</div>
    <div >cambdridge assessment english</div>
    <div >PON</div>
    <div >erasmus </div>
    <div >amministrazione trasparente</div>
    <div >albo online</div>
  </div>
</div>

CodePudding user response:

Since you are using @keyframes you need to target those CSS properties.

Using this answer: Passing parameters to css animation, I set up a CSS variable to use for the initial translateX value. Using JS, we can then change that value using [setProperty][1] on the wheel event.

var widgets = document.querySelector(`.widgets`);

widgets.addEventListener(`wheel`, (e) => {
  e.preventDefault;
  widgets.style.setProperty('--translate-x', '200px');
}, {
  passive: false
});
:root {
  --translate-x: 100%;
}

.main .widgets {
  display: flex;
  animation: marquee 20s linear infinite;
}

.main .widgets:hover {
  animation-play-state: paused;
}

@keyframes marquee {
  0% {
    transform: translateX(var(--translate-x));
  }
  100% {
    transform: translateX(-100%);
  }
}
<div >
  <div >
    <div >classeviva</div>
    <div >moodle</div>
    <div >circolari</div>
    <div >gmail</div>
    <div >ECDL</div>
    <div >cambdridge assessment english</div>
    <div >PON</div>
    <div >erasmus </div>
    <div >amministrazione trasparente</div>
    <div >albo online</div>
  </div>
</div>

  • Related