"Looking for a way to automatically close the <li> tag in Vuejs when clicked outside

  clickOutside: 0,

 methods: {
      outside: function(e) {
        this.clickOutside += 1
        // eslint-disable-next-line
          console.log('clicked outside!')
        },
        
   directives: {
      'click-outside': {
        bind: function(el, binding, vNode) {
          // Provided expression must evaluate to a function.
          if (typeof binding.value !== 'function') {
            const compName = vNode.context.name
            let warn = `[Vue-click-outside:] provided expression '${binding.expression}' 
            is not a function, but has to be`
            if (compName) { warn += `Found in component '${compName}'` }
            // eslint-disable-next-line
            console.warn(warn)
          }
          // Define Handler and cache it on the element
          const bubble = binding.modifiers.bubble
          const handler = (e) => {
            if (bubble || (!el.contains(e.target) && el !== e.target)) {
              binding.value(e)
            }
          }
          // eslint-disable-next-line
          el.__vueClickOutside__ = handler
  
          // add Event Listeners
          document.addEventListener('click', handler)
        },
        
        unbind: function(el, binding) {
          // Remove Event Listeners
          // eslint-disable-next-line
          document.removeEventListener('click', el.__vueClickOutside__)
          // eslint-disable-next-line
          el.__vueClickOutside__ = null
  
        }
      }
    }
<input
          class="form-control bg-light-blue"
          id="SearchText"
          type="text"
          v-model="search"
          />

<ul class="list-inline" v-if="showSearchHistory" v-click-outside="outside">
        
          <li
            class="list-inline-item list-group-item-primary"
            v-for="(item, index) in searchHistory
              .slice(-5)
              .reverse()
              .map((s) => s.trim())"
            :key="index"
            @click="selectPreviousSearch(index)"
          >
            {{ item }}
          </li>


</ul>

Onclick of input, li tag will open and then i want to close li tag. If user click outside the li tag. To do that i am counting the event, when clicked outside of li.

But now i want to close the li with some event on it.

In the console now i am able to see, When user clicked outside, now i am able to count the value.

Answer №1

Check out the v-click-outside feature suggested by @linus-borg over at: https://jsfiddle.net/Linusborg/Lx49LaL8/

This function triggers whenever a click occurs outside of the specified element.

UPDATE:

In your component, there is a method called outside, which handles whether the dropdown should be visible or hidden.

export default {
  /* ... */
  methods: {
    outside() {
      this.showSearchHistory = false;
    },
  },
  /* ... */
};

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

AngularJS provides a way to create opening pages with clickable buttons for a

I'm struggling to implement buttons that switch ons-templates when clicked. I've been following this example as a reference: Here's the code snippet I've been working on, but it just won't cooperate: <!doctype html> &l ...

Ways to efficiently handle numerous asynchronous requests in a NodeJS/Express API

I am looking to consolidate a variety of REST APIs into a single, easy-to-use API. My plan is to develop a straightforward nodejs/express API that will handle the individual calls asynchronously and then aggregate all the results together at once. The Jav ...

What is the best way to convert a series of sentences into JSON format?

I'm struggling with breaking down sentences. Here is a sample of the data: Head to the dining room. Open the cabinet and grab the bottle of whisky. Move to the kitchen. Open the fridge to get some lemonade for Jason. I am looking to format the outc ...

When arriving on a page via an HTML anchor tag, the CSS style does not appear. How can I "reinstate" it?

I have set up a website with an index.html page that links to a contact.html page using anchor tags. On the contact.html page, there are anchor tags that should navigate the user back to specific sections of the index.html page. The navigation works fine, ...

Ensure that the dynamically inserted <title> tag remains intact in Angular even when the page is re

Can the dynamic title tag be preserved when the page is refreshed? When I refresh the page, the title tag reverts back to the original one specified in the index.html temporarily before switching back to the dynamically added one. I want the title tag to ...

User authentication on AngularJs is only initiated on the second interaction

My personally built AngularJs user authentication system is experiencing an unusual issue. While everything seems to be working fine - I can login, check access for specific pages, etc. - there is a strange behavior with the token authentication. It seems ...

Setting up child routes can be easily accomplished by following these steps

I've been exploring the functionality of child routes within VueJS. My assumption was that setting up a news overview with links to individual news items and using a child route would allow me to view each item separately. However, it's not worki ...

Generating PDF files from HTML documents using Angular

I am currently working on an Angular 11 application and I have a specific requirement to download a PDF file from a given HTML content. The challenge is that the HTML content exists independent of my Angular app and looks something like this: < ...

I am having issues with my code because I am trying to call a method on the root from within a component

I'm working on a bootstrap modal component that includes a button labeled "Got It". I'm trying to call a method on the root instance when this button is clicked, but it's not working as expected. I've added a click handler and emitted t ...

How can I create a unique CSS or JS transition for a button that dynamically changes size based on text

My Angular app features a button labeled with "+". When the user hovers over it, I use element.append(' Add a New Number'); to add the text "Add a New Number" next to the + sign in the label. Upon clicking the button, a new number is added and ...

What is the best way to choose the unique identifier of an HTML element inside a for loop in a Django template?

I need help selecting an HTML button that is generated within a for loop in a Django template using JavaScript. How can I assign a unique ID to each button and select it correctly in JavaScript? Currently, all buttons have the same ID within the loop, resu ...

Necessary workaround needed for HTML time limit

Our HTML page has been designed to automatically timeout after 10 minutes of inactivity. This functionality is achieved through the following code: function CheckExpire() { $.ajax({ type:'GET', url:self.location.pathname+"?ch ...

Tracking dynamic collections in AngularJS ng-repeat using track by

I am attempting to utilize ng-repeat with the result of a function call, like this: <body ng-init='a = [1, 2, 3]'> <div ng-repeat='item in f(a) track by item[0]'>{{item}}</div> </body> where the function f is ...

Experiencing difficulties in transmitting multipart form data from React to Express Js accurately

I am facing an issue with uploading files using Dropzone and sending them to a Java backend API from React JS. In this scenario, React sends the document to Express backend where some keys are added before forwarding the final form data to the Java endpoin ...

Creating and deploying a basic Angular2 application in cordova

I have a pre-existing app developed in Angular2, which is quite basic. Upon attempting to build it for Android using Cordova, the debug build successfully installs on the system but gets stuck at the loading stage. I am seeking guidance on how to ensure th ...

Unable to Display Embed Request Using Javascript in IE9 and IE10

My website allows users to embed content they create on the site into their own blogs or pages using a series of embeds. Here is the code we provide them: <script src="[EMBED PROXY URL]" type="text/javascript"></script> When this code calls ...

The process of retrieving keys and values from localStorage in html5

I have stored some important key-value pairs in local storage. Now I need to retrieve both the keys and values, and then display them by appending the values in a list item (li). Currently, my attempt at this looks like: for (var i = 0; i < localStorag ...

When you call setTimeout from a static function, it does not get executed

Having a problem with starting a timer in my utility typescript class. The static function initTimer() uses setTimeout but when called from a react component, the timer doesn't start. StyleWrapper.tsx const StyleWrapper: FC = (props) => { cons ...

Accessing the admin panel of a headless CMS using Nuxt.js and WordPress

I'm facing an issue. I recently set up Wordpress and enabled the REST API. Following that, I created a Nuxt.js app. The app runs on localhost:3000 (using "npm run dev" command) I configured XAMPP so that the document root of the server points to the ...

I'm experiencing difficulties with the "AXIOS PATCH" functionality

I am attempting to modify a database record using the "axios patch" method. This is the code I have tried: editClient(client) { let data = new FormData(); data.append("name", this.client.name); data.append("email", this.client.email); data.append ...