[Vuejs]-How to add dynamic class to multiple dynamic button on click of another button?

0👍

As you used nuxt.js, i suppose vue.js solution.

  1. append toggle value in data part
  data () {
    return {
      ...
      glow: false,
      ...
    }
  }
  1. Add class binding in each dynamic buttons. :class="{ glow }" attributes bind class name glow when glow data is true.
<button id="enroll" class="btn btn-primary btn-block text-center rounded" :class="{glow}" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
<button id="enroll" class="btn btn-primary btn-block text-center rounded" :class="{glow}" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
<button id="enroll" class="btn btn-primary btn-block text-center rounded" :class="{glow}" style="background: #2685ef;border: 2px solid #2685ef;">Buy Now</button>
  1. Control just glow data. It affect each button’s class name.
scrollToDiv() {
  this.glow = true
  setTimeout(() => {
      this.glow = false
  }, 2000)
}
  1. Set timeout id in data (like global variable in component). In your original code, timeout id scrollTimeout is local variable in scrollToDiv, clearTimeout is meaningless. Each execution of scrollToDiv generates new scrollTimenout in function scope.
  data () {
    return {
      ...
      glow: false,
      timer: null,
      ...
    }
  },
...
  methods: {
    ...
    scrollToDiv() {
      this.glow = true
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
          this.glow = false
      }, 2000)
    }
  }
...

0👍

The id of an element is supposed to be unique, so when you use getElementById you are only getting the first matching element.
I would try giving the three buttons the same class, and use getElementsByClassName(className), that will return you an HTMLCollection that will allow you to iterate through the elements. So something like:

scrollToDiv() {
  document.getElementById('pricing').scrollIntoView({
    behavior: 'smooth',
  })
  var elements = document.getElementsByClassName('example-classname')
  for(let e of elements) e.classList.add('glow')
  var scrollTimeout
  clearTimeout(scrollTimeout)
  scrollTimeout = setTimeout(function () {
    for(let e of elements) e.classList.remove('glow')
  }, 2000)
}

Leave a comment