'How to target body tag to close the side Navbar clicking any where on the screen using Vue?
I want to move the Navbar right: -500px (close the navbar) by clicking anywhere on the window. In Html, JS I can target body tag to do the same. How to do it in vue? I have two functions for two (open and close) button. Still I want to add additional functionality to hide the Navbar by clicking anywhere on the screen. My code
<div class="chatbot-whole-wrap">
<PopUpMsg class="pop-up-chat" />
<div class="chat-bot-wrapper">
<input id="open" type="checkbox" />
<img id="chat-btn" alt="chat-icon" src="@/assets/chat-bot-bee-icon.svg" @click="openWindow()" />
<div id="sidebar">
<img id="chat-close-btn" alt="chat-icon" src="@/assets/close-icon.svg" @click="closeWindow()" />
<iframe class="chat-bot-iframe" src="https://hggsbnjsggxvbxjkksb/" width="100%" height="100%"></iframe>
</div>
</div>
</div>
Here are two methods I have used
methods: {
openWindow() {
document.getElementById('sidebar').style.right = '0';
},
closeWindow() {
document.getElementById('sidebar').style.right = '-500px';
},
},
Solution 1:[1]
I'm not the most fluent in Vue.js, but could you not register an event handler on the body in a lifecycle method?
function closeNavIfOpen () {
console.log('do your thing')
}
var app = new Vue({
el: '#app',
data: {
message: 'Click anywhere in the body!'
},
mounted () {
window.document.body.addEventListener('click', closeNavIfOpen, false)
},
destroyed () {
window.document.body.removeEventListener('click', closeNavIfOpen, false)
}
})
body {
margin: 0;
min-height: 100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{ message }}
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
