What is the implementation approach for mouseover delegation in pure JavaScript?

How can I successfully apply event delegation for the mouseenter event?

I've been searching for a way to achieve what this jQuery code does, but I'm struggling to grasp how it works internally:

$(document).on('mouseenter', '.demo', foo);

I came across another question discussing this issue, but unfortunately, a satisfactory solution wasn't provided.

The documentation on Mozilla about mouseenter and event delegation mentions that it's not fully supported by all browsers. The example they presented even throws errors in the console without functioning properly.

I also tested out this codepen example, which failed to work correctly in Chrome (though I haven't checked other browsers).

Do you have any suggestions or insights on this matter?

Here is my current attempt at implementing event delegation, but it appears that the target element continues to bubble up:

document.addEventListener('mouseenter', function(e) {
    console.log('==============================');
    console.log(e.currentTarget); //document
    console.log(e.target); //document 
    console.log(e.relatedTarget); //nothing
    console.log(e.handleObj); //nothing
});

You can experiment with the code in this jsfiddle link.

Answer №1

To capture events, you must add an event listener during the capturing phase by passing true as the third argument:

document.body.addEventListener("mouseenter", function(e) {
    if(e.target.className === "demo") {
        console.log("catched");
    }
},true); // capturing phase

You can implement more advanced techniques to target specific elements, but this approach is the key.

View a live demo here: https://codepen.io/anon/pen/Xqaxwd

Answer №2

You might consider utilizing the mousemove event and keeping track of the current element (taking into account parent elements) in a similar way to this:

let lastTarget = null;

document.addEventListener('mousemove', function(e) {
 const target = checkWithParents(e.target);
 if (target && target != lastTarget) {
   alert('mouseenter');
 }
 lastTarget = target;
})

function checkWithParents(el) {
  while (el) {
    if (el && el.classList && el.classList.contains('demo')) {
      return el;
    }
    el = el.parentNode;
  }
  return null;
}
.demo {
  background-color: tomato;
  height: 300px;
  width: 300px;
  margin: 50px;
}
<div class="demo"><div class="inner"></div></div>
<div class="demo"><div class="inner"></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

Having trouble displaying dynamically added images in my jsx-react component. The images are not showing up as expected

import React from "react"; import ReactDOM from "react-dom"; var bImg = prompt("Enter the URL of the image you want to set as the background:"); const bStyle = { backgroundImage: "url(bImg)"; // The link is stored ...

Attempting to elegantly shift div elements using jQuery

There is a foreach loop that brings in 4 divs containing external images (replaced by "dummy" content in this snippet for demonstration purposes). When clicking on the image, the hidden content should appear. The issue I am facing is how to smoothly transi ...

Issue encountered while utilizing property dependent on ViewChildren

Recently, I designed a custom component which houses a form under <address></address>. Meanwhile, there is a parent component that contains an array of these components: @ViewChildren(AddressComponent) addressComponents: QueryList<AddressCo ...

Utilizing parameters and variables as function arguments in reactjs

I have created a function type React component: function Card(props, {icon}) { return ( <div className="card"> <FontAwesomeIcon icon={icon} className="icon"/> <h3 className="text">{props.name}</h3&g ...

React application triggers `OnKeyDown` event just once

Hey there! I'm diving into the world of web development and could use some help. My current challenge involves manipulating input data based on key combinations like ctr + ArrowUp (increase) and ctr + ArrowDown (decrease). The dynamic part should be h ...

What could be causing the appearance of a mysterious grey box hovering in the upper left portion of my image and why is the code only adjusting the size of the grey box instead of the entire

I've been working on embedding some JavaScript into my Showit website to create a drag-and-drop feature that displays a collage/mood board effect. Everything is functioning correctly, but I'm running into issues with resizing the images. There&a ...

Utilizing npm/buffer package within a TypeScript module

I'm interested in implementing this NPM package: https://www.npmjs.com/package/buffer I'm unsure about how to convert this line of code into typescript: var Buffer = require('buffer/').Buffer Could you provide me with the correct code ...

An error was encountered in the JSON syntax: Unexpected symbol <

I have encountered a problem with my code that I cannot seem to resolve. Despite the JSON data being successfully sent to the backend and processed correctly, the success function of the call is never triggered. Here is the snippet of my function: Regist ...

Place the new item right under the chosen items within the nested list

My nested list with a collapse feature is almost complete. However, I am encountering an issue where I need to add content just below the selected item when I click on the "add" button. For example, in the attached demo, there is a nested list. If I select ...

Display Image based on AngularJS value

Within my data, there exists a value {{catadata2.EndorsementList['0'].Rating}}. This value can be either 3, 4, or 5. Based on this value, I am looking to display the image <img src="/assets/img/rating.png" /> a certain number of times. For ...

Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure: export interface Passenger { id: number, name: string, checkedIn: boolean, checkedInDate?: Date // <- Is it possible to make this f ...

Leverage jQuery to convert local variables into global variables

I'm trying to pass the logged in username from a login form to a global variable so I can use it across my site. The goal is to store the value of the username obtained from the userLogin() function in a global variable called "username". Below is t ...

pg-promise received an error due to an incorrect parameter being passed in for options

I have been working on transitioning my files from utilizing the pg package to the pg-promise package. Initially, everything was functioning correctly with the original pg solution I had in place. However, upon switching to pg-promise and referencing the d ...

Guide to incorporating external CSS and JavaScript into an Angular 2 project with Express.js and Node.js

As a newcomer to Angular2 and NodeJs, I am eager to learn how to integrate external CSS and JS in an Angular2 and Nodejs express app. Specifically, I am looking to integrate a bootstrap admin theme into my Nodejs application. The screenshots below provide ...

Creating Vue methods functions in separate JavaScript files

Hi there, I'm new to this so please forgive me if my question seems silly. I have a vue component called vuu /path_to_main/vue_file/app.js const vuu = new Vue({ el: '#vuu', data: { latitude: 'longi', long ...

Print directly without the need for a preview or dialog box

Is there a way to easily print content with just one click, without having to go through the preview or print dialog box? Here is a snippet of my code: <head> <style type="text/css"> #printable { display: none; } @media print { #non-pr ...

Tips for extracting function data and storing it within scope after resolving a route in AngularJS

Is there a way to fetch data from a function and store it in the scope using resolve in an AngularJS route? For instance: .state('list.employee_list', { url: "/employee_list", templateUrl: "views/list/employee_list.html" ...

Vue 3 Router view fails to capture child's event

After some testing, I discovered that the router-view component in Vue 3 does not capture events sent from its child components. An example of this scenario is as follows: <router-view @event-test="$emit('new-test-event')" /& ...

Access information stored within nested JSON objects on a local server

After creating a test page, this is the structure that I have set up: <!DOCTYPE html> <html lang="en" class="no-js"> <head> <title>Get JSON Value</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/ ...

"Looking to modify a style within an iframe with React? Here's how you can do it

I want to include an iframe in my react component, but I need to hide a specific element within it. The iframe source comes from an external domain. Is there a way to add custom CSS to the iframe so that I can achieve this? Below is the code for my compo ...