[Vuejs]-I am trying to hide a div after 5 seconds of page load. Why is it not working?

1๐Ÿ‘

โœ…

As you are working with Vue.js, I will suggest you to use v-show directive to show and hide the popup.

Demo:

new Vue({
  el: '#app',
  data: {
      isVisible: true
  },
  mounted() {
    this.poppupShow();
  },
  methods: {
    poppupShow() {
      setTimeout(() => {
        this.isVisible = false;
      }, 5000);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div class="pop-up-chat" v-show="isVisible">
    <div id="div1">
      <div class="pop-up-msg regular-text">Hi, How may I help you?</div>
      <div class="triangle-down"></div>
    </div>
  </div>
</div>
๐Ÿ‘คDebug Diva

2๐Ÿ‘

Just add new property to data showPopup and set it to true then change it to false within mounted hooks

Using v-show to show or hide the wanted element v-if-vs-v-show

<template>
  <div>
    <!-- binding style -->
    <div :style="{visibility: showPopup ? 'visible' : 'hidden' }"

    <!-- or use v-show directive to show | hide element -->
    <div v-show="showPopup" class="pop-up-chat">
      <div id="div1">
        <div class="pop-up-msg regular-text">Hi, How may I help you?</div>
        <div class="triangle-down"></div>
      </div>
    </div>
  <!-- The rest of your template -->
  </div>
</template>

<script>
export default {
  name: 'PopUpMsg',
  data() {
    return {
      showPopup: true,
    }
  }
  mounted() {
    this.msgShow();
  },
  methods: {
    msgShow() {
      setTimeout(() => {
        this.showPopup = false
      }, 5000)
    },
  },
}
</script>

Or you can create custom directive v-visible

<div v-visible="showPopup" />

Vue.directive('visible', function(el, binding) {
    el.style.visibility = Boolean(binding.value) ? 'visible' : 'hidden';
});
๐Ÿ‘คnart

0๐Ÿ‘

It works this way

methods: {
    msgShow() {
        const msg = document.getElementById('msg');
        setTimeout(() => {
            msg.style.display = 'block';
            setTimeout(() => {
                msg.style.display = 'none';
            }, 10000);
        }, 5000);
    },
},

.pop-up-chat {
display : none; //initially
}

๐Ÿ‘คSiddharth Gope

Leave a comment