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

Centering navigation using HTML5

I've been struggling a bit trying to build a website, particularly with centering my <nav> tag. Despite reading numerous suggestions like using CSS properties such as margin: 0 auto; or text-align: center, nothing seems to be working for me. Si ...

Error messages encountered following the latest update to the subsequent project

Recently, I upgraded a Next project from version 12 to 14, and now I'm encountering numerous import errors when attempting to run the project locally. There are too many errors to list completely, but here are a few examples: Import trace for requeste ...

Cease the progress of a Sequelize promise within an Express.js application

Exploring the realm of promises is a new adventure for me, and I'm still trying to grasp their full potential in certain situations. It's refreshing to see Sequelize now supporting promises, as it greatly enhances the readability of my code. One ...

What is the best way to transfer a variable from a node server to a javascript client when the page is first

My web application is mainly static, but I need to dynamically send the user's username if they are logged in and the room name they specify in the URL to the client-side JavaScript upon page load. Finding a simple solution has been challenging for me ...

wrap <td> data in a link with vue depending on certain conditions

I'm trying to customize the display of a particular table cell td. I want to show the data in a link if a certain condition is met, and if not, just show the data as text. However, I'm encountering some difficulties in implementing this. I have ...

Navigating through a predetermined list of HTML pages with next and previous options

Hey there, I'm in a bit of a quandary at the moment. I've been searching on Google for quite some time now, but unfortunately, I can't seem to find what I'm looking for. Hopefully, you guys can lend me a hand. What I'm trying to d ...

Electron: Interactive menu customization

Is there a way in Electron to dynamically enable/disable specific MenuItem in the context menu based on the element that the user right-clicks on? Additionally, I am looking for a method to identify the exact element clicked and pass that information to th ...

When Selenium in JavaScript cannot locate a button element, use `console.log("text")` instead

I am trying to capture the error when there is no button element available by using console.log("No element"). However, my code is not working as expected. const {Builder, By} = require("selenium-webdriver"); let driver = new Builder().forBrowser("chrome ...

Ways to prevent horizontal scrolling in an image

Currently, I am working on a scrolling animation page that is optimized for mobile devices. One issue I am encountering is when an element is larger than the screen size, such as when an image is wider than the mobile device. In this scenario, the user can ...

A Guide to Effectively Extracting Data from Second Level JSON Arrays with

Hi, I'm having difficulty fetching the two attributes under CategoryImage in the second level of the JSON array parsing. Can someone help me with this? Thank you. <script> $(document).ready(function() { var cat=""; ...

"Patience is key when it comes to waiting for an HTTP response

Looking for a solution in AngularJS, I have a service that calls the backend to get some data. Here is how the service looks: app.factory('myService', ['$http', '$window', '$rootScope', function ($http, $window, $ro ...

Extract string data from JSON payload

How can I extract the itemlocation from itemInfo and display it in a new column in my react table using Material UI? While I know this can be done on the backend, I am looking for a way to achieve this without backend involvement. Below is an example of ho ...

Command for DiscordJS to verify users

I have a requirement to develop a verification command using discord.js v12. This command will assign a verified role based on the configuration specified in a config file. Config file: { "token": "my-token", "status": " ...

Modifying the array structure will deselect all individual <Input> elements that have been iterated

Hoping to create a system for adding/removing sub-items with buttons that increment/decrement slots in an array, where input fields are automatically added and removed: <div *ngFor="let item of itemsInNewOrder; let i = index"> <input [(ngModel) ...

retrieve the value of a text form using jQuery and its corresponding id

I need help with a basic HTML form that includes jQuery. My goal is to: 1) Retrieve the value into a JavaScript variable. 2) Send it as JSON to a server. Here is the form: <div data-role="main" class="ui-content"> <data=role "form" ...

Different approach to iterating through elements

Looking to implement .forEach instead of a traditional for loop? 'use strict'; var score = (function(){ function updateScore() { for(var i = 0; i < arguments.length; i++) { this.score += arguments[i]; ...

Parsing nested JSON files to present data on a webpage

I have a JSON file containing Reddit post titles and their respective scores: { "'JavaFX Simple Inventory Management App - Open source'": 39, "'Creating Formula Dependency Maps from Excel Spreadsheets'": 5, "'CVE-2017-5645 ...

Extracting data from websites by manipulating the Document Object Model with the help of Javascript and Ajax

Currently, I am in search of data for educational purposes from a website. Specifically, the website focuses on statistics in web development. The challenge lies in the fact that this particular site uses Javascript/Ajax to constantly update numbers. I w ...

Parsing JSON data in JavaScript with multiple objects

I just received a JSON Object from an HTTP request [ { "location": { "name": "Seattle, WA", "lat": "47.604", "long": "-122.329", "timezone": "-7", "alert": "", "degreetype": "F", "imagerelativeurl": "http:&b ...

Is it secure to use ES6 in Typescript with nodejs/koa?

As I transition to using TypeScript in a Node.js/koa project, I came across the need to modify the .tsconfig file to target ES6. Otherwise, an error message will appear stating: Generators are only available when targeting ECMAScript 6 or higher. // index ...