How can I use Vue to close the side Navbar by targeting the body tag and clicking anywhere on the screen?

I am looking to make a change in the Navbar position by moving it right: -500px (to close the navbar) when clicking anywhere on the window. In HTML and JS, I can achieve this by targeting the body tag. How can I accomplish this in Vue? I already have functions for opening and closing the navbar with buttons. However, I want to add an extra feature that allows hiding the Navbar by clicking anywhere on the screen. Below is my code snippet:

<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>

What I have done with two methods:

methods: {
    openWindow() {
        document.getElementById('sidebar').style.right = '0';
    },
    closeWindow() {
        document.getElementById('sidebar').style.right = '-500px';
    },
},

Answer №1

Although I'm not the most experienced with Vue.js, could you possibly avoid registering an event handler on the body within 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Express 4 does not support Angular ngRoute

I am trying to set up client-side routes using Angular along with Express 4. I have successfully used the ngView directive as per the guide ngView without Express, but once I enable Express routing, ngRoute stops working. How can I configure Express to wor ...

Scrolling back to the top of the page using Jquery instead of a specific div

Check out the code for my project here. The isotope feature is functioning correctly, however, when clicking on the image, instead of scrolling to the navigation under the red box as intended, the page scrolls all the way to the top. If I modify the follo ...

Requiring three parameters, yet received four

Encountering an error in the dashboard.tsx file while trying to implement a line of code: "const { filteredEvents, stats, tableApps, formattedDate } = filterData(dataAll, Prefix, listApp, dateSelected);" The issue arose with the dateSelected parameter resu ...

The @change event in Vue/Vuetify lacks certain properties in the $event object

Working on a project using Vuetify, I am implementing an edit-in-place feature. The transition between the span and text field is functioning properly, sending updates to the server as expected. One final task remains before considering this functionality ...

How can I extract and display chosen values from multiple dropdown menus in designated text boxes based on their unique identifiers?

A website for evaluating car values is in the works, using a combination of PHP, MYSQL, JQUERY, and JavaScript. The database includes 3 tables: Table "car_make": id make 1 BMW Table "model": model_id model_name make_id 1 M3 1 Table "ca ...

Tips for setting a default checked radio button in Vuejs

Upon page load, the radio button status should initially be checked. Then, when the radio button is changed, a div below it should hide and show accordingly. I have attempted to write the code for this functionality, but unfortunately it is not working a ...

Setting up the permanent class path for Nodejs in Linux Mint

Recently, I attempted to install Nodejs Version 6.9.4 on my Linux Mint system using the following steps: $ cd /tmp $ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz $ tar xvfz node-v6.3.1-linux-x64.tar.gz $ mkdir -p /usr/local/nodejs $ mv ...

What could be causing the span class data to not be retrieved by the getText method

Looking to retrieve the value of a span class called 'spacer-right big project-card-measure-secondary-info' <span class="spacer-right big project-card-measure-secondary-info">1</span> snippet of code: browser.waitForEl ...

Mobile authentication using Vue3, Ionic, and Sanctum results in a 419 error code

I am currently working on implementing token authentication in my Vue3 Ionic mobile app. The setup involves two separate repositories - one for the Laravel 10 backend API and the other for the Vue3 Ionic app. I am utilizing Sanctum for Laravel 10 API authe ...

CORS headers not functioning as expected for Access-Control-Allow-Origin

Can someone help me figure out how to add Access-Control-Allow-Origin: 'http://localhost:8080' in Node.js and Express.js? I keep getting this CORS error: Access to XMLHttpRequest at http://localhost:3000 from origin 'http://localhost:8080&ap ...

The jQuery AJAX request is not returning a truthy value when parsing

On my website, I am dealing with a large form and using the serialize() method to process it. However, I have encountered an issue: After completing the form, the result always returns false. I checked this using Firebug. Even though data.ok == true has ...

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...

What does the error message "Uncaught TypeError: Cannot access property 'style' of an undefined object" mean?

I've been attempting to execute the code below, but I keep encountering an error. I even tried including document.addEventListener('DOMContentLoaded', (event) => yet it still doesn't work. Interestingly, there are no errors if I run ...

All browsers experiencing issues with autoplay audio function

While creating an HTML page, I decided to include an audio element in the header using the code below: <audio id="audio_play"> <source src="voice/Story 2_A.m4a" type="audio/ogg" /> </audio> <img class= ...

Angular (2/4) application utilizing custom-named routing within a single page architecture

I'm currently working on an Angular application that consists of a login component and a home component which serves as the main handler for the entire single page application. Additionally, I have three more components named users, each with function ...

React is currently in the process of downloading images that were not fetched during

(Update: Initially, I suspected React Router was the cause of this issue. However, after eliminating React Router from the codebase, the problem persists. Therefore, I have extensively revised this inquiry.) Situation: I am dealing with paginated pages th ...

Why does ng-bind fail to display values from rootScope that have been set by using ng-click?

I am trying to save a variable within $rootScope. When I have the following structure, everything works fine and the second div displays the value: <html ng-app> ... <body> <button ng-click="$rootScope.pr = !$rootScope.pr"></b ...

Leveraging depends alongside max for jQuery validation

Trying to implement a conditional max value on a field using jQuery validation, but encountering issues. Even though I've utilized the depends function, it seems like the validate function is not functioning as expected. The code block appears correc ...

Modal shows full JSON information instead of just a single item

This is a sample of my JSON data. I am looking to showcase the content of the clicked element in a modal window. [{ "id": 1, "companyName": "test", "image": "https://mmelektronik.com.pl/w ...

I am having trouble authorizing a GET request with fetch

I've been attempting to utilize fetch in the browser, but it's not cooperating. Here's what I tried: fetch('https://api-2sizcg3ipa-uc.a.run.app/fats', { headers: {'Authorization': 'Basic ' + btoa('username ...