What is the best way to programmatically change the event tied to an element's click

    <div id="filters"></div>

    <div id="available">
        <span class="badge badge-pill" onclick="addFilter()">Label</span>
    </div>

function addFilter(event) {
   document.getElementById("filters").appendChild(event.target);
   event.target.removeEventListener('click', addFilter);
   event.target.addEventListener('click', removeFilter);
}

function removeFilter(event) {
   document.getElementById("available").appendChild(event.target);
   event.target.removeEventListener('click', removeFilter);
   event.target.addEventListener('click', addFilter);
}

So, removeEventListener doesn't work is this case. Is there any way that I can accomplish to "toggle" the onclick event?

Answer №1

Here's a demonstration with a single function. It validates whether the selected item in a list of HTMLCollection filters matches the clicked item using its innerText property. I included a second element with the same class to illustrate that the function works properly even when the text differs.

new Vue({
  el: "#app",
  data() {
    return {}
  },
  methods: {
    toggle_filter: function(event){  
      if([...this.$refs.filters.children].filter(child=>child.innerText==event.target.innerText).length==0){
        this.$refs.filters.appendChild(event.target)
      }else{
        this.$refs.available.appendChild(event.target)
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>Filters</h2>
  <div ref="filters"></div>

<h2>Available</h2>
  <div ref="available">
    <span class="badge badge-pill" @click="toggle_filter">Label 1</span>
    <span class="badge badge-pill" @click="toggle_filter">Label 2</span>
  </div>
</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

The react-redux developer tool appears to be disabled and is not displaying the current state of the application on the extension toolbar

Just finished the redux-tutorial and attempting to view the state in the redux-devtools. However, the redux-devtools seems to be inactive on the extensions bar. Upon clicking it, a menu appears with options like "to right, to left etc". Selecting one of ...

Exploring the realms of software testing with a blend of manual testing and automation using powerful tools such as

Although I am still relatively new to automation, I have already created a handful of tests using Webdriver and TestNG. These tests are data-driven, pulling parameters from Excel sheets. As someone who primarily works manually on test plans, teaching mysel ...

Error: The function user.comparePassword does not exist or is not defined

I am facing an error that says TypeError: user.comparePassword is not a function. I have ensured that all dependencies are installed and the APP is linked to all the libraries. I tried using Postman to retrieve data, but it doesn't seem to be workin ...

Having trouble identifying the issue with the dependent select drop down in my Active Admin setup (Rails 3.2, Active Admin 1.0)

I am currently working on developing a Ruby on Rails application that involves three models: Games that can be categorized into a Sector (referred to as GameSector) and a subsector (known as GameSubsector) A sector consists of multiple subsectors. A Subs ...

Tips for saving information to a JSON file in Reactjs

Perhaps the real question should be How can I save data to a JSON file using Reactjs and Nodejs? I'm new to React and unsure about which database to use. On a side note, it's simple to read from a json file with var data = require('./d ...

Creating a dynamic image carousel using jQuery

Today, I completed the jQuery course on Code Academy and am now trying to create an image slider using it. While I have a general idea of how it should work, I feel like I'm missing a key element. My goal is to have the slider continuously running whe ...

Unable to send a POST request to http://localhost:5000/api/createuser

During my journey through a MERN stack project tutorial on YouTube, I've come across a roadblock in the middle of my progress. The issue at hand involves the incorporation of user registration, which is a recent addition to my project. Utilizing Thund ...

The ideal scenarios for employing functional setState

Lately, I've been delving into the world of React, immersing myself in tutorials and explanations on how to manipulate elements in different ways. One aspect that has caught my interest is the setState function, which allows you to update or override ...

Incorporating a new data series into your candlestick chart with Highstock

I've encountered an issue with adding a data series to my candlestick chart in Highstock using Highcharts. Here's the script I'm using: $.ajax({ url : 'indicator', type : 'GET', data ...

Monitoring and recording the current line number during evaluation

Recently, I've been experimenting with eval to modify a $scope object named variables. This is the watcher I'm using: $scope.$watch(function () { return $scope.variables; }, function (variables) { console.log('changed!'); }, true) ...

Synchronization-free API and callback functions

I am in need of utilizing an asynchronous service. My current approach involves sending data to this service using PHP and CURL, as well as receiving data from a URL provided by the service. How can I effectively respond or wait for feedback from this serv ...

Navigating with jQuery Scrollbars

Looking to incorporate a bit of animation in jQuery, trying out the following line: window.parent.scroll(coord[0], coord[1]); The next block of code doesn't seem to be achieving what I had in mind. Do you have any suggestions? $(window.parent).anim ...

Retrieve the id of the anchor tag that was selected upon clicking, and then dynamically change the content of another div

Seeking guidance on how to dynamically change the content of a div element based on which anchor tag is clicked. Below is the HTML structure and JavaScript function I have attempted: HTML: <div> <a id="a1" href="javascript: changeDiv();">tag1 ...

Is it possible to stack one Canvas on top of another?

Right now, I am engaged in a process that involves: creating a canvas and attaching it to a division applying a background image through CSS to that canvas. drawing a hex grid on the canvas placing PNGs on the canvas. animating those PNGs to show "movem ...

Challenges with the Sumo Select Refresh Feature

I am having trouble with Sumo select not refreshing the data properly. The action method is returning the correct list, but it seems like the JQUERY multi-select rebuild() function is missing. Is there something I'm overlooking? $("#ddlCountry&q ...

Combining Multiple Optional Async AJAX Calls

In my Angular 1.5.8 app, I have different views that require various combinations of the same 3 ajax requests. Some views need data from all three endpoints, while others only need data from one or two. To efficiently manage the retrieval of this data, I ...

How to get the total number of rows/records in a JSON store using ExtJS?

My dilemma involves a JSON store that provides data in JSON format. I am currently attempting to determine the number of rows or records in the JSON string. However, when utilizing the store.getCount() function, it consistently returns 0. Strangely, the ...

Eliminate the ripple effect from the icon button

I am looking to create an icon that will perform the button's task of loading, while also removing the rounded button effect from this icon. Is there a way to achieve this? Visit this link for more details. <div id="app"> <v-app id="inspi ...

Tips for eliminating the domain name from the src URL attribute using Jquery

Is there a way to extract the img src attribute and retrieve only the image path without the domain name included? var imgurl = "http://nitseditor.dev/img/home/bg.jpg"; For instance, I would like to display img/home/bg.jpg instead of the full URL. Any id ...

responsive cascading dropdown.. preassigned value

I've come across this interesting script on a website and it's been working pretty well for me so far. The script can be found at the following link: . However, I have a specific requirement when it comes to setting a certain value for the catego ...