samedi 23 mars 2019

How do I write an if expression for current transform: translate() value?

I'm trying to create my first switch.

I have 2 keyframe animations. One to make the switch move right and the other to move the switch left.

Now, for the Javascript I think I need an if statement because I need Javascript to know what to do when the switch is in specific positions right?

The problem is I'm not quite sure what to put as the if expression.

I was hoping I could just use this as the if expression to return a boolean true value:

sliderCircle[0].style.transform = 'translate(0px, -20px)'

HTML:

<div class="row">
  <div class="slider">
    <div class="slider-back"></div>
    <div class="slider-circle"></div>
  </div>
</div>

CSS:

.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 55vw;
  height: auto;
  padding: 0 1vw;
  border-top: 2px solid rgba(255 ,255, 255, 0.4);
  transition: 1s;
}

.slider {
  height: 12px;
  margin-top: 2vw;
  cursor: pointer;
}

.slider-back {
  width: 45px;
  height: 12px;
  border-radius: 15px;
  background: -webkit-linear-gradient(100deg, rgba(172,174,203,0.6) 0%, rgba(255,255,255,0.6) 80%);
}

.slider-circle {
  width: 28px;
  height: 28px;
  border-radius: 25px;
  background: -webkit-linear-gradient(100deg, rgba(172,174,203,1) 0%, rgba(255,255,255,1) 80%);
  transform: translate(0, -20px);
}

.slide-anim-r {
  animation-name: slider-r;
  animation-duration: 0.5s;
}

.slide-anim-l {
  animation-name: slider-l;
  animation-duration: 0.5s;
}

@keyframes slider-r {
  0% {
    transform: translate(0, -20px);
  }
  100% {
    transform: translate(22px, -20px);
  }
}

@keyframes slider-l {
  0% {
    transform: translate(22px, -20px);
  }
  100% {
    transform: translate(0, -20px);
  }
}

Javascript:

const slider = document.getElementsByClassName('slider');  // slider toggle
const sliderCircle = document.getElementsByClassName('slider-circle');

slider[0].addEventListener('click', () => {
  if (sliderCircle[0].style.transform = 'translate(0px, -20px)') {
    sliderCircle[0].classList.add('slide-anim-r');
    sliderCircle[0].style.transform = 'translate(22px, -20px)';
  } else {
    sliderCircle[0].classList.add('slide-anim-l');
    sliderCircle[0].style.transform = 'translate(0px, -20px)';
  }
});

At the moment I can click on the switch and it animates right but then I can't click on it to move it back again.

If anyone can advise a better way to do this please let me know!

Thanks!

Aucun commentaire:

Enregistrer un commentaire