Skip to content
Advertisement

Best way toggle between three classes for an Element

I have 3 buttons, which on click would the change the layout to desktop , mobile and tab view. . So I’m calling the same method toggleView(), passing different param for different buttons. So i have written the method to toggle between the 3 classes. It’s working fine. I feel there would be a better way to do this in Javascript. I was not able to find out by search

It would be of great help if someone suggest a optimised solution to this

<div class="responsive-buttons">
  <button class="btn mb-3" type="button" @click="toggleView('preview-desktop')">Desktop</button>
  <button class="btn mb-3" type="button" @click="toggleView('preview-tab')">Tablet</button>
  <button class="btn mb-3" type="button" @click="toggleView('preview-mobile')">Mobile</button>
</div>

toggleView(message){
  var el = document.querySelector("#previewWrapper");
  if(message=='preview-desktop') {
     el.classList.remove('preview-tab', 'preview-mobile');
     el.classList.add(message);
  } else if(message=='preview-tab') {
     el.classList.remove('preview-desktop', 'preview-mobile');
     el.classList.add(message);
  } else if(message=='preview-mobile') {
     el.classList.remove('preview-desktop', 'preview-tab');
     el.classList.add(message);
  }
}

Advertisement

Answer

Use class bindings on #previewWrapper like this:

<div id="previewWrapper" :class="previewWrapperClass" />
...
data: {
  return {
     currentPreviewMode: null
  }
},
computed: {
   previewWrapperClass () {
     if (!this.currentPreviewMode) {
       return null
     }
     return {
        [this.currentPreviewMode]: true
     }
   }
},
methods: {
   toggleView(message){
        this.currentPreviewMode = message
   }
}

See Class and style bindings

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement