Implementing mouse event listeners on dynamically created elements in Vue.js

I've been curious if anyone has attempted something similar to the following code snippet (created within a Vue.js method):

for (let i = 0; i < this.items.length; i++) {
    let bar = document.createElement('div');
  bar.className = this.items[i].colour;
  bar.style.cssText = `width: ${this.items[i].weight}%`;
  bar.setAttribute("mouseover", this.showBlock(500, false)); //not functioning as expected
    document.querySelector('.bar').appendChild(bar);
}

https://jsfiddle.net/phfilly/eywraw8t/167799/

I am attempting to implement a hover mouse event (line 32) for the dynamically created element. Are there alternative methods to achieve this functionality?

Answer №1

The issue at hand:

Let's examine the problematic line in question:

bar.setAttribute("mouseover", this.showBlock(500, false));

Key problems identified include:

  • It attempts to set the return value of this.showBlock(500, false) as the value for the mouseover attribute. Since the function does not return anything, this likely results in a value of undefined.
  • The use of the mouseover attribute is incorrect in HTML and Vue, where v-on:mouseover or @mouseover are typically used.
  • Vue looks for these attributes/directives during initialization, but here the elements are added after Vue initialization.

Potential resolutions:

A) Ensure your Vue model can be accessed globally (e.g., as window.app). Then, use the following approach with the onmouseover HTML attribute and stringifying the function call:

bar.setAttribute("onmouseover", "app.showBlock(500, false)");

B) Replace the attribute with an event listener. Here's an example:

bar.addEventListener("mouseover", function () { app.showBlock(500, false); });

Your Vue instance must be accessible for this method as well.

For a detailed solution, refer to @saiyan's answer.

C) Since the task doesn't require any functionality beyond what Vue offers, consider using Vue to create and manipulate your elements. Utilizing Vue for this purpose aligns with its main objective of simplifying element management. Given the for loop you mentioned, a Vue implementation in your HTML might look like this:

<div class="bar">
  <div v-for="i in items" :class="i.colour" :style="{ width: i.weight + '%' }" @mouseover="showBlock(500, false)"></div>
</div>

Check out @Bert's fiddle for a comprehensive solution.

Answer №2

Give this a try. I've made some modifications to your jsfiddle code.

for (let i = 0; i < this.items.length; i++) {
        let bar = document.createElement('div');
      bar.className = this.items[i].colour;
      bar.style.cssText = `width: ${this.items[i].weight}%`;
            // ?
     // bar.setAttribute("mouseover", this.showBlock(500, false));
        document.querySelector('.bar').appendChild(bar);



    }
    var that=this;
    setTimeout(function(){
      document.querySelector('.bar').childNodes.forEach(function(e,y){
        e.addEventListener("mouseover", function(){that.showBlock(500, false)});
      });},100);

This solution worked for me on jsfiddle

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

Exploring the transformation of asynchronous callbacks to promises in Node.js

As a novice, I am currently in the process of developing a User Management system using NodeJS. Previously, I had implemented it with MongoDB and Express, but now I am rebuilding it with Express, Sequelize, and Postgresql to enhance my understanding of cer ...

Preventing HTML form submission after displaying an alert in Vanilla JavaScript

I have created a quiz using HTML with validation. The next step is to score the quiz in JavaScript. The scoring system works fine, but I want to prevent the form from posting to result.html if the user scores 0 on the quiz. I've managed to display an ...

"Make sure to specify Safari input field as an email and mark

I am experiencing an issue with a contact form in my HTML/PHP code. Everything seems to be working fine, but when using the SAFARI browser, the form fails to validate if I try to submit without filling out all input fields. For example, my form includes: ...

Looking to implement a delay in the model popup using Pure JavaScript

Looking for a method to implement a delay in the popup... I've tried a few solutions without success. What's the secret to adding a delay to the modal below? Any help is greatly appreciated. var modal = document.querySelector(".modal"); var t ...

Utilizing logic classes in conjunction with styled components

I am seeking a way to utilize this logic in order to assign the appropriate class to an element: <ul onClick={handleClick} className={click ? 'dropdown-menu clicked' : 'dropdown-menu'}> However, as I am employing styled component ...

Warning: Promise rejection not handled in error

I've been working with nodejs, express, and argon2 in my project. However, I encountered an error that has left me puzzled as to why it's happening. Strangely, even though I don't have any callbacks in my code, this error keeps popping up. H ...

What is the best way to tally the frequency of words in a collection of URLs using JavaScript?

I have a JSON object in WordPress that contains a list of URLs. I would like to determine the frequency of occurrence of the second part of each URL. Currently, the code snippet below is able to extract the remaining part of the URL after the prefix https ...

Issue encountered while retrieving value from asynchronous dns.lookup() function

I am currently in the process of developing a function that validates a url by utilizing the dns.lookup() function, which is outlined below: const dns = require('dns'); const verifyURL = (url) => { const protocolRegEx = /^https?:\/& ...

Verify a unique cross-field rule for comparing two time strings, customized by Vee

I am currently facing an issue with validating two time strings in my buefy form using vue. The goal is to ensure that the second time input does not exceed a one-hour difference from the first time input. Both time fields have granularity down to millisec ...

Activate a click on a div element to enable smooth scrolling when using the page down and page up keys

Whenever I directly click on my div, the pageUp and pageDown keys scroll the contents of the div. But when I trigger a click programmatically, the scrolling with pageUp and pageDown stops working. How can I enable scrolling with pageUp and pageDown without ...

Incorporate an HTTP Header into a Wicket Ajax Request

I am trying to include a custom HTTP header in all Ajax (XHR) requests made by Wicket. I attempted the following: $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('X-My-Header', 'value'); } }); and $(doc ...

Concealing the nearest object

I am currently working on using jquery to hide certain content on a website's index page. Within the fiddle, there is commented out code which I have been experimenting with - however, it hides all content divs if any toggle link is clicked. HTML & ...

Facing the issue of "Protractor not syncing with the page" while trying to navigate an Angular website

I'm currently attempting to follow the tutorial for Protractor on the official Protractor website, but I've hit a roadblock at step 0. My setup involves using protractor and webdriver-manager version 6.0.0. I am running Linux (Ubuntu 18.06) as m ...

A guide on invoking a JavaScript function after receiving a response from an AJAX request

I am facing an issue with a $.POST call that returns the name of a function to be executed, however, the function is not being triggered and I'm unsure why. Below is an example: JavaScript file snippet: $(function(){ $.post('test.php&apos ...

Update the array state based on the selection of checkboxes and user input in real-time

In my current project using react js, I am working on a UI development task where I need to create a dynamic table based on data fetched from an API. Each row in the table includes a checkbox and a text input field that are dynamically generated. My goal i ...

Issue with vuejs: npm run dev command not functioning

I'm facing an issue with running VueJS webpack on a server using the command: npm run dev. Instead of it running smoothly, I am getting a long list of errors. You can view the screenshot of the errors by clicking here. ...

What are some strategies for circumventing the need for two switches?

My LayerEditor class consists of two private methods: export class LayerEditor { public layerManager: LayerManager; constructor() { this.layerManager = new LayerManager(this); } private executeCommand() { ...

Using Vue 3 or Nuxt, the v-if directive and watch property can cause issues with initializing

Visit this link: Currently using Nuxt 3.4.2 along with Supabase, I have implemented skeleton loading and pagination features. However, after adding these, the Flowbite off-canvas drawer stopped working properly. The issue arises when the data-drawer-targe ...

Code in JavaScript that shows only a portion of the selected option in a dropdown menu

I'm just starting to learn Javascript and I'm looking to create a script for a select tag that displays countries and their phone codes. My goal is to have the dropdown menu show both the country and code, but once the user selects an option, onl ...

Nuxt - asyncData ISSUE: "Variable '$axios' is inferred to have an 'any' type."

Referencing the guidelines provided at Encountering an error logged in console while executing yarn dev: ERROR ERROR in pages/index.vue:51:21 ...