Home > Software engineering >  Cleanest way to toggle class in list through setInterval
Cleanest way to toggle class in list through setInterval

Time:02-25

I would like to toggle an 'active' class in a list of elements:

<div ref="gallery" >
  <div >
  <div >
  <div >
</div>

Using Vue and Vanilla JS

Slider() {
  const slider = document.querySelectorAll('.slider')
  for (const slide of slider) {
    setInterval(function () {
      const current = slide.querySelector('.active')
      current.classList.remove('active')
      const next = current.nextElementSibling || slide.firstElementChild
      next.classList.add('active')
    }, 5000)
  }
}

While the above code does work, I feel it is not as clean as it could be.

Also, and mainly, if I target the slider using a Vue ref like:

const slider = this.$refs.gallery

it stops working

CodePudding user response:

Try this out!

I presume this is what you were trying to do. If you have any questions. Just ask!

Without setInterval:

function slider() {
  const slider = document.querySelectorAll('.slider');
  slider.forEach((slide) => {
    slides = Array.from(slide.children)
    slides.forEach((child) => {
      child.classList.toggle("active")
    });
  });
};

With setInterval:

function slider() {
  const slider = document.querySelectorAll('.slider');
  slider.forEach((slide) => {
    let slides = Array.from(slide.children)
    slides.forEach((child) => {
      setTimeout(() => child.classList.toggle("active"), 5000);
    });
  });
};

CodePudding user response:

I made this demo in vue.js format as per your request. Please have a look and see if this is what you actually want to achieve.

Demo :

new Vue({
  el: '#app',
  data: {
    slideData: [{
        name: 'Slide 1',
      isActive: true
    }, {
        name: 'Slide 2',
      isActive: false    
    }, {
        name: 'Slide 3',
      isActive: false    
    }]
  },
  mounted() {
    this.slideData.forEach((obj) => {
      setInterval(() => {
        obj.isActive = !obj.isActive;
      }, 3000);
    });
  }
})
.active {
  color: white;
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(slider, index) in slideData"  :>
  {{ slider.name}}
</div>
</div>

  • Related