Ways to access the attribute of the element being hovered over

So, I am currently attaching event listeners to an array of elements with the intention that when a specific element is hovered over, it will set a property to the id of that element. However, instead of grabbing the id of the hovered element, it seems to be selecting the id of the last element to which the event listener was added.

My main query here is how can I retrieve the id of the element being hovered over?

It's important to mention that I am utilizing Vue and attempted to use the @mouseover event, but it seems that because I'm using it on a package called vue-pdf, the event is not registering properly.

<pdf 
    v-for="i in numPages"
    :key="i"
    :page="i"
    :src="src"
    v-if="!loading"
    @num-pages="pageCount = $event"
    :ref="`${i}`"
    :id="`${i}`"
    @mouseover="setPage(i)"
/>

After rendering the document, I call this method:

methods:{
addListener() {
  if(this.numPages > 0) {
    for(var i = 0; i < this.numPages; i++) {
       var span = this.$refs[i+1][0].$el

       //this is where I encounter issues
       span.addEventListener('mouseover', () => {    
          this.currentPage = span.getAttribute('id')
        })
       }
    } else {
    console.log('didnt work')
  }
},
}

mounted() {
   this.addListener()
}

In addition, I have devised a workaround involving getBoundingClientRect, but I believe there should be a simpler way to determine the currently viewed element.

Answer №1

Exploring further into the issue you presented, I also delved into event bubbling and methods to prevent it.

I discovered that in cases where a container had nested elements with sub-events, all three events would be triggered. More information on Event Bubbling can be found here.

In addition, using arrow functions for events may sometimes exclude crucial event details.

//----------------------------------^--
span.addEventListener('mouseover', (e) => {    

     // this.currentPage = span.getAttribute('id')
     let myEvent = e.target || e.currentTarget ;
     this.currentPage = myEvent.getAttribute('id') ;

     //Check out details of the event ....
     console.log(myEvent );
    })

The "e" references the event, so retrieving the attribute with "myEvent.getAttribute('id')" is essential. Regarding bubbling, clicking on a child element nested within the element with the event may require referencing e.target.parentElement or e.target.parentElement.parentElement to reach the specific element details holding the event.

If multiple nested elements each have their own events, such as a div with its event and a span separate event inside the div, preventing event bubbling and triggering the parent div's event can be achieved by using e.stopPropagation();

This effectively prevents the triggering of the parent

div

event when triggering the

span

event.

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

Show the elements of an array (that have been read and processed from a text file) on separate lines using JavaScript

Hello, I have the code below where a user can upload a text file. I attempted to display the output in a div after splitting it using the @ character. The array elements stored in variables are correctly displayed with new lines in an alert, but they are p ...

How do I add a "Switch to Desktop Site" link on a mobile site that redirects to the desktop version without redirecting back to the mobile version once it loads?

After creating a custom mobile skin for a website, I faced an issue with looping back to the mobile version when trying to add a "view desktop version" link. The code snippet below detects the screen size and redirects accordingly: <script type="text/j ...

Is there a way to make divs expand on top of existing content when hovering over them, in order to avoid needing to scroll through overflow content? I am currently working with

I am working with 9 boxes contained within divs, each box includes data that exceeds the size of the box itself (represented by Some Text repeated for demonstration purposes). I am seeking a solution where hovering over any box will cause it to enlarge and ...

Encountering Next.JS Router Issue: Unable to Access Properties of Null (specifically 'useContext')

As a beginner in Next.js and React, I'm facing an issue with redirecting users from the "Projects" page to the Product Page Details. Here's the code snippet I am using: const openProjectDetails = () => { Router.push('/api/' + props ...

When attempting to process JSON using the fetch method, the value for a valid JSON key

Currently, I am facing a challenge wherein I need to fetch data from my REST server to populate the frontend of my UI. This requires me to make requests not only to my own server but also to other servers. One specific request involves retrieving a list of ...

Execute a JavaScript function daily for each new user

Can someone help me understand how to execute a JavaScript/jQuery function that triggers a PopUp once for each new user visiting a webpage? Below is the code I need assistance with. $(window).load(function() { $('#index9').fadeIn("slow"); ...

Obtaining the value of a JavaScript confirm popup in C#.NET

I am trying to implement a javascript confirm popup that returns a value from the code behind. When the user selects the ok button on the confirm popup, certain code will execute, and if they select cancel, different code will run. Is there a way to retri ...

How can I restrict the navigation buttons in FullCalendar to only allow viewing the current month and the next one?

I recently downloaded the FullCalendar plugin from Is there a way to disable the previous button so that only the current month is visible? Also, how can I limit the next button so that only one upcoming month is shown? In my header, I included this code ...

Node.js: Configuring keep-alive settings in Express.js

How can I properly implement "keep alive" in an express.js web server? I came across a few examples.. Example 1: var express = require('express'); var app = express(); var server = app.listen(5001); server.on('connection', function(s ...

Develop an array in JavaScript using PHP on the server side

I have successfully created a JavaScript array in PHP and sent it to the client. However, I am now wondering how to create a JavaScript array with PHP and store it on the server. Can anyone provide some guidance on this? Thanks in advance! ...

Exploring methods to verify a service subscription to a topic provided by a different service

My services provide the following functionalities: @Injectable({ providedIn: 'root' }) export class Service1 { dataHasChanged = new Subject(); private data1; private data2; constructor() {} getData() { return { data1: th ...

Renaming form elements using JQuery's .load method

This is a page named A.html <form name=form> <input type=text id = txtA> </form> When I use jQuery to load it into B.html, it loads multiple times. <form name=form> <input type=text id = txtA> </form> <form name=f ...

Using Sequelize to update all values in a JSON file through an Express router.put operation

I've been working on a feature in my Express router that updates data in a MySQL schema for 'members' of clubs. The members table has various columns like member_id, forename, surname, address, etc. I've successfully created an Express ...

Steps to remove a row from a table in a ReactJS component

I'm struggling with implementing a delete operation for table rows and encountering errors. Any assistance in resolving this issue would be greatly appreciated. Since I am unsure how to set an auto-incrementing id, I used Date.now(). Now my goal is t ...

Can you provide instructions on how to configure the npm settings to use the current directory in a pre

I'm currently working on setting the installation directory from where the user is installing to an npm config variable. This will help me reference it in my installation script. Can anyone advise if there is a command line solution for this or will ...

Achievement with ajax: If the status code is 200, execute one function; otherwise, execute a

I can't figure out why this isn't working... I'm using $.ajax to run file.php and pass a POST value from an input field. Even though the file.php is functioning properly (it successfully adds a user to my newsletter), my ajax function seems ...

Using JSON to dynamically generate pages in Gatsby programatically

Currently, I am utilizing Gatsby to dynamically generate pages, and I am looking to do so at two distinct paths: covers/{json.name}.js and styles/{json.name}.js. While I have successfully set this up using the gatsby-node.js file, I would like to transit ...

Using Vue.js to Duplicate a Component Across a Page Multiple Times

My objective: I am working on implementing filters that will be displayed on a page to filter the products shown. For mobile devices, I want to hide these filters behind a button which, upon being clicked, will reveal the filters in a side-slide menu. Alt ...

Header misalignment occurs when the user scrolls up too quickly causing it to display

One interesting feature on my website is that the header disappears as users scroll down the page, but reappears when they start scrolling back up, even if they are halfway down. However, if a user quickly scrolls up and down, there seems to be an issue wi ...

I need help figuring out the right way to define the scope for ng-model within a directive

I found a straightforward directive to automate sliders: app.directive('slider', function() { return { restrict: 'AE', link: function(scope, element, attrs) { element.slider({ value: scop ...