Discovering mouse interactions on overlapping HTML elements

Can mouse events be detected on an object that is adjacent to, but not a child of, another element in the HTML?

For instance:

<style>
#test, test2 {
     width: 100%;
     height: 100%
}
</style>

<html>
    <section class="full" id="test">
    Full Screen 
    </section>


    <section class="anotherFull" id="test2">
    Full Screen As well
    </section>


<script>

        var elem = document.querySelector('#test2');

        elem.addEventListener('hover', function(){
          alert('you are hovering');
        }, false);

</script>
<html>

Even if I hover over the page and try different methods like mouseenter, mouseover, or hover, and examine the e object from

document.addEventListener('hover', function(e){}, false)
; (such as e.target), I cannot detect a hover event on the second adjacent element.

Answer №1

Unique Demo

To solve this issue, one approach is to connect the events in a sequential manner. This can be achieved by utilizing both addEventListener and dispatchEvent functions. For detailed instructions, you can refer to an informative article on MDN titled Custom Event Handling Guide

var
 outer = document.getElementById("outer"),
 inner = document.getElementById("inner")
;

inner.addEventListener('mouseenter',function(e){
 alert('hovering inner');
},false);

outer.addEventListener('mouseenter',function(ev){
 alert('hovering outer');
 this.style.display = "none";
 var tar = document.elementFromPoint(ev.clientX, ev.clientY);
 this.style.display = "block";
 tar.dispatchEvent(new Event('mouseenter'));
},false);
#screen{
    position:relative;
    width:50px;
    height:50px;
}
#outer{
    position:absolute;
    top:0;
    left:0;
    z-index:2;
    width:50px;
    height:50px;
    background-color:blue;
}
#inner{
    position:absolute;
    top:0;
    left:0;
    z-index:1;
    width:50px;
    height:50px;
    background-color:red;
}
<fieldset>
    <legend>Screen Mockup</legend>
    <div id="screen">
        <div id="outer"></div>
        <div id="inner"></div>
    </div>
</fieldset>

Answer №2

I'm not sure I understand your post completely, so here are a couple of suggestions.

If you're looking to bind a hover event to the sibling of a specific selector that you already know...

JavaScript

const element = document.getElementById('example').nextElementSibling;
element.addEventListener('mouseover', function(event){...});

CSS

#example+div:hover {
    ...
}

IMPORTANT: Remember that HTML id attributes should be unique. Avoid having multiple elements with the same id in your markup.

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

What are the steps to add a Search Box to my HTML Website?

Currently, I am in search of a way to incorporate a "Search" feature on my website that is built solely with HTML. I have added a Search box for the users but I'm uncertain about how to proceed next. Can I use PHP to enable the Search functionality o ...

Utilize SVGs efficiently by loading them once and reusing them

Is it possible to use the same SVG element twice on a web page without having to load it again? I am changing the CSS of the SVG using JavaScript, so I believe the SVG must be directly embedded in the HTML rather than included as an object. Both instance ...

JavaScript - asynchronous XMLHttpRequest with increment operation

Hello, it's my debut on SO, although I've been a regular user for quite some time and found all the answers I needed here...until now. I'm currently grappling with an intricate issue involving XHR. While I consider myself a bit of a JS newb ...

Having trouble selecting a subset of data from an AJAX request using Jquery?

I have successfully implemented a modal for form submission. However, I am encountering an issue with replacing a part of the modal with a section of the data retrieved from the ajax call. $.ajax({ url: actionUrl, method: 'post', data: dataToSen ...

Creating an Array of dynamically generated elements using jQuery

A dynamic table is being generated using jQuery's .append() function: $el.append('<tr data-id=' + data[i].id + ' data-token=' + data[i].token + '><td>' + data[i].order + '</td>\n\<td&g ...

Removing the initial string before an object can be done by utilizing various techniques and

The response I am receiving is in the following format: javax.xml.rpc.ServiceException: [{"ReturnCode":0,"counter":"\\\\sap\\CTI \\CTIConnection"},{"ReturnCode":101,"ErrSt ...

Encountering an error in Angular where the property 'nativeElement' is undefined when using @ViewChild

I have a div in my code named #map that will be displayed after a certain condition is met in a for loop. <div *ngFor="let message of fullMessagesArr"> <div *ngIf="message.replyMap"> <div #gmap style="width:100px;height:400px"></d ...

Display a new div with its content every 5th item

I am currently working with a Smarty template that contains the following code output: Check out my other question on Stackoverflow My problem lies in the fact that the provided code does not repeat the inserted HTML after every 5 elements... Could some ...

The MAC slideshow circles at the bottom have been mysteriously chopped off

Utilizing the popular JQuery plugin Cycle for a slideshow on this site: bybyweb.com/pbm An issue has arisen - everything functions as expected on windows (across all major browsers), BUT on MAC (running lion 10.7.5, tested on one machine so far; unsure of ...

Within a loop featuring multiple buttons, apply a class toggle specifically to the button that is clicked on

CSS: .btn-category-list-col { background:#f4f6f9; border: 0 !important; } .btn-category-list-col:hover { background: #E2EEFC; } .btn-category-list-col button:hover { font-weight: bold; } .btn-category-list-col-click { background: #E2EE ...

The React-Virtualized Autosizer component is returning a height value of 0 when used with VirtualScroll

Despite AutoSizer's width providing the correct value, I am consistently encountering a height of 0 for Autosizer. This is causing the VirtualScroll component to not display properly. However, when using the disableHeight prop and setting a fixed heig ...

The determination of the volume value was impossible using only the values from the object nested within an array

I am currently developing a react app that includes a button labeled Add to create a new calculation. Each calculation consists of two input fields for thickness and surface, as well as an output field for Volume. There is also a button labelled "X" to rem ...

Issue with Jquery Drag and Drop functionality, navigate to a different page

I am trying to incorporate a page with js from quotemedia.com using Jquery. When I insert the js into the sortable, and then drag and drop the element containing the js, it suddenly switches to full page display. This issue occurs in Firefox, but IE works ...

Oops! A JSON parsing error occurred due to the presence of an unexpected token '}'

I encountered an issue while trying to develop a registration route using passportjs. When sending a request via Postman, I received the following error message: SyntaxError: Unexpected token } in JSON at position 119    at JS ...

The default export of Nuxt, referred to as 'mod', could not be located

Using Nuxt with Typescript, I have created a custom component as shown below: <template> <div class="field"> <label class="label" v-if="typeof label !== 'undefined'">{{ label }}</label> <div class=" ...

What is the best way to create a collapsible list menu?

I created a menu with 4 main items, each containing 3 to 5 sub-items. <ul id="navigation"> <li><a>Diagonóstico</a> </li> <li class="sub"><a href="javascript:void(0);" class="sub_di1"> › Grátis (na ...

Prevent Buttons from Being Clicked While Another is Active in Angular

I am facing a challenge with my Angular functions that enable search features. My goal is to allow only one feature to be selected at a time. /* Trauma Search functionality */ $scope.traumaSearch = false; $scope.traumaText = "Trauma Center"; $scope.togg ...

WordPress display issue: AMCharts chart won't appear

I recently crafted an XY 2 series chart using the Amcharts library and have successfully integrated it into my WordPress website with the necessary plugin. This particular chart showcases load span values for construction spreader beams, and it was built ...

Learn about generating PDF files with React Native Expo using the react-native-html-to-pdf library!

I'm currently attempting to execute a 'Hello World' code utilizing the react-native-html-to-pdf library in order to generate a PDF, but I am encountering difficulties setting it up in Expo. Would you be able to provide assistance? I have tri ...

angularjs ngmodel directive with dual values

I need help with customizing my dropdown control <div ng-repeat="prop in props" style="margin-bottom: 10px;"> <label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.Value}})</label> <div class="col-md-8"> < ...