Utilizing Vue: Attaching click event to dynamically added elements

I am working on a Vue application that retrieves HTML content from an API. This HTML contains blocks with the class

<div class="play-video">...</div>

Using axios to call the API and a promise, I insert the content into the DOM like this:

<div v-if="content" v-html="content"></div>

My concern is how to attach click events to children elements with the .play-video class. Do I need to monitor changes in the content property and then use vanilla JS query selectors to bind the events?

Answer №1

To implement event delegation, you can utilize a @click handler and verify the target element by using the Element.closest() method.

new Vue({
  el: "#app",
  data: () => ({
    content: null
  }),
  methods: {
    handleClick(e) {
      const elt = e.target.closest(".play-video");
      if (elt) {
        console.log("Got a click on .play-video or a child element")
      }
    }
  },
  mounted () {
    // simulate loading content
    setTimeout(() => {
      this.content = `
        <div>
          <p>Some other element</p>
          <button>I'm not part of <code>.play-video</code></button>
          <div class="play-video">
            <p><button>Click me, I am!</button></p>
          </div>
        </div>
        `
    }, 1000)
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddaba8b89deff3e8f3efec">[email protected]</a>/dist/vue.min.js"></script>
<div id="app">
  <div v-if="content" v-html="content" @click="handleClick"></div>
  <p v-else>Loading...</p>
</div>

If you specifically want to capture click events only on the .play-video element itself and exclude its children, you can omit the .closest() call and use

if (e.target.matches(".play-video") {
  // ...
}

For information on browser compatibility and a possible polyfill, refer to https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#polyfill.

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 'this' variable is malfunctioning when trying to assign a JSONP array to an AngularJS controller

I'm working with a REST service in my angular controller and using JSONP to make the call. I need to store the array that is returned from the service into a variable. This is what I currently have: this.testTheRest = function() { $http.jsonp(&a ...

Enhance the visual representation of live updates through the utilization of socket.io in Express

I'm using handlebars as the view engine for my express app. But I'm unsure how to append new data coming in from socket.io. router.get('/', function(req, res) { io.on('connection', function(client) { client.on( ...

What is the best way to send an inline SVG string to my controller?

I am trying to send an inline svg string along with some other properties to my controller. When I replace the svg string with a normal string like "blabla", it successfully reaches my controller. However, with the actual svg string, it never makes it to ...

Error encountered: Invalid symbol detected ('<') while attempting to parse JSON in an Angular application

I am experiencing an issue with my Angular code when trying to submit a form. Upon clicking the submit button, an error saying JSON Parse error: Unrecognized token '<' appears, and empty records are being saved in the database. I have included ...

Two select boxes trigger multiple sorting operations

Struggling to implement 2 different sorting operations on two separate columns in a datagrid, using 2 different select boxes has proven to be challenging. I attempted the code below, but as a beginner, I was unable to solve it... In HTML: <select ng ...

Using a for loop in conjunction with Observable.forkJoin

In my component, I am striving to populate an array known as processes, containing individual process objects that each have a list of tasks. Currently, I am dealing with two API calls: /processes and /process/{processId}/tasks I utilize the /processes ...

Ensure that the placeholder remains visible as you type in the input field

Is there a way to implement an input text field in React with the placeholder "DD-MM-YYYY," that partially disappears as I start typing? For example, when I type "02-," only "-MM-YYYY" should remain visible as part of the placeholder. ...

What is the process for redirecting to an external URL while including post parameters?

When a user accesses my endpoint, I need it to automatically redirect them to an external URL with URL-encoded form parameters. Endpoint: https://example.com Form Parameters: Name: testing ID: 123456 I have attempted the following in Express. It succes ...

Importing an external JSON file into a ChartJs chart

As a newcomer to using libraries for drawing charts in JavaScript, I recently started playing around with Chartjs. However, I'm having trouble figuring out how to use getJson or any other method to load my json object and update the labels and data. I ...

Discovering the summation of chosen options multiplied by input fields with the assistance of jQuery

I am attempting to calculate the average for different subjects and print it immediately whenever the user modifies a value. To input the marks, I am using input fields and corresponding select options for the hours allotted to each subject. I can accura ...

I am in search of a clean and efficient method to modify the class of a link that triggers an HTMX request in Django. Perhaps something like "auto-refresh" or a similar solution would be ideal

I've encountered an issue with HTMX in Django. The page consists of two main components: a list of categories and the content that is displayed when a category is clicked. Initially, everything was working smoothly with standard htmx functionality. H ...

I'm having trouble retrieving data from the server using the AngularJS $http.get() function. What am I doing wrong

Ensure that your question is clear and that your code properly showcases the issue at hand. Feel free to leave any questions or comments below for clarification. app.js var express = require('express'); var app = express(); app.use(express.sta ...

Select a checkbox automatically after receiving an ajax response

I am currently working with a form that contains multiple checkboxes like the one below: <label class="checkbox"> <input type="checkbox" id="user_ids_for_edit" name="user_ids_for_edit[]" data-toggle="checkbox" data-toggle="checkbox" value="14"&g ...

I'm experiencing an issue where my JavaScript function is only being triggered

I have a simple wizard sequence that I designed. Upon selecting an option from a dropdown menu on the first page, a new page is loaded using jQuery ajax. However, when clicking back to return to the original page, my modelSelect() function, responsible for ...

The Angular route functions flawlessly in the development environment, but encounters issues when deployed to

I have a project built with Angular 2, During development on localhost, everything runs smoothly. However, once I build a production version using (npm run build: prod) and navigate to the route on the server, I encounter a 404 error indicating that the r ...

Issue with Node Webpack identifying the "Import" statement

I'm diving into the world of Node and Webpack, but I'm struggling with getting my project to compile properly. Every time I try to load it in the browser, I encounter the error message: Uncaught SyntaxError: Unexpected token import. Let me share ...

Guide to declaring variables using jQuery

Currently tackling a school project, I stumbled upon some online example solutions and managed to decipher most of the code. However, there is one line that has me puzzled. var $newTweet = $('<div class=tweet></div>'); My assumption ...

When using AngularJS, encountered an issue where a view was not updating with new data from a $http request

When making a request to the 500px API using $http for popular photos, the response object is successfully returned. However, I am facing difficulty in pushing the retrieved photo items to the view. Below is my current controller code: meanApp.controller ...

Unique Revision: "Identification Zone within a Single-page Application"

Seeking insights from a seasoned DOM/JS Architect. In reference to another discussion about maintaining a clean id space in a Single Page Application (SPA). Due to certain restrictions, I am unable to utilize data binding frameworks and have to work with ...

The functionality of JQuery stops functioning once ajax (Node.js, PUG) is integrated

I've been attempting to incorporate a like feature on my blog post website. When I click on the likes count, it's supposed to trigger an ajax call. In my server.js file, there's a function that handles the POST request to update the number ...