"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

Encountered an npm ERR while executing the React project

I'm encountering an issue with running my React project. When I use the command "npx start", I receive the following error message. Can someone please assist me with this? npm ERR! could not determine executable to run npm ERR! A detailed log of thi ...

Is there a way to link code and unit testing directly to npm test?

Is there a method to conduct unit testing in real-time on my server without having to create temporary files? I am looking for a way to supply both the code to be tested and the corresponding unit test to npm test. The information provided in the npm test ...

What is the process for retrieving the information sent from the client application to the jsreport server?

I want to create a downloadable pdf report through my angular application using jsreport. The client app makes a POST request passing sample data to the report server in this manner. $http.post('http://localhost:5488/api/report', { ' ...

Building a stylish bootstrap button within the cell rows of a table using jquery

I need to insert a button in the "Details" column. <button class="btn btn-primary btn-fab btn-icon btn-round"> Here is my code: var tableRef = document.getElementById('ticker_table').getElementsByTagName('tbody')[0]; var ti ...

The connection between `this` and its calling context

Is all information from its call site accessible to a function? I was under the impression that a function would have access to the scope of its call site, but I could be mistaken. Any feedback and explanation would be greatly appreciated. function bar() ...

What is the best way to show an error message on a webpage using jQuery within a PHP environment?

I have a form in HTML that includes a submit button for posting status on a page. When a user clicks the submit button without entering anything into the form field, I want PHP to display a simple error message on the same page saying "This status update s ...

Is using $window.location.reload(true) the same as manually pressing CTRL+F5?

I'm working on developing a feature called "version updated" component that displays a banner notifying users when the website has been updated and prompts them to reload. The challenge I'm facing is that some users are experiencing issues with c ...

Utilizing App Script for Filtering Data with Multiple Criteria

Having trouble transferring data from a data sheet to my report sheet using multiple criteria for matching. I wrote some code that worked, but it's returning all data instead of filtering by criteria. I want the function to search for column criteria ...

Stopping form submission on a jQuery form

I am in the process of implementing a password control feature on a login form using jQuery and ajax. This is the current script I have: $(document).ready(function() { $("#login-form").submit(function(e) { var csrftoken = getCookie('csr ...

Vue.js is unable to render the template using Object

During this demonstration at https://jsfiddle.net/ccforward/fa35a2cc/, I encountered an issue where the template could not render and the data in resultWrong remained empty with a value of {} At https://jsfiddle.net/ccforward/zoo6xzc ...

Exploring the world of Node.JS and AngularJS through the integration of API routes

Currently, my backend is built using Node.JS with Express and serving as my API servlet. On the frontend, I'm utilizing AngularJS for the user interface. After numerous searches on Google, I was able to resolve an issue where I faced challenges using ...

Is it recommended to incorporate "return" in my callback function when coding in JavaScript?

Utilizing asynchronous functions in my JS application, I've encapsulated them within my own functions that take callback inputs. One question that I have is whether or not it's necessary to use the "return" keyword when calling the callback funct ...

Angular: Modify value when checkbox is ticked

Controller: promiseObj.physical = $http.get('search?sumBoth=1&customer=' + customer).success(function(data) { $scope.servers = data; // retrieve data from JSON }); View: <tr ng-repeat="data in servers | filter: { _id: { idc: item._ ...

What is the method for invoking an anonymous JavaScript object when its name is unknown?

I've been dynamically loading JavaScript modules with jQuery's getScript function. I want to be able to call an init method that all of these modules contain. Since the modules are loaded dynamically, I would rather not hard code their names. Is ...

Exploring the wonders of retrieving JSON data in PHP through an Ajax request

A front-end developer is sending an array of data formatted as a JSON object using an Ajax call. The JSON object structure is shown below: { "name": " Test Name ", "image_url": "test URL", "include": [ "1" ], "dimension": [ null ], "media_type" ...

To obtain the desired response, I must make an additional GET request

Upon sending the first GET request to this endpoint, I receive a response of allEvents = []. However, if I wait a few seconds and hit the endpoint again, I get the desired results with a populated allEvents array. It seems that the function is not executin ...

Automatically fill in an input field with jQuery by using the value from another input field

I am currently working on a loan calculator and am trying to find a way to automatically populate an interest rate field based on the loan amount entered. Here is an example scenario: For amounts ranging from 0 to 100,000, the interest rate is 4.50 For ...

What is the best way to show the associated ul tag?

I've constructed the following HTML: <input id="<code generated id>" type="text" value="select"/> <div id="<code generated id>" class="popup"> <ul id="<code generated id>" class="none"> <li>A</li& ...

"Sorry, but there seems to be an issue with

My shop: { customers: [ { id: 12345, name: Customer A }, { id: 54321, name: Customer B } ] } I am attempting to modify the name attribute for Customer A. I am utilizi ...

Extract the ID from the array, save it, and then delete it from the local storage

I am currently developing a mobile application using Angular, JavaScript, Ionic, and Cordova. Within one of my functions, I make use of an array called existingEntries, which is stored as a variable. categories: Array [276] [0...99] 0: Object id ...