Exploring the connection between two divs using onmouseover and onmouseout events in JavaScript

I am currently working on creating a function that displays a button when the mouse hovers over an element and hides it when the mouse is moved away. The example below illustrates my issue:

------------------------------------------------------------


 ---------
| button2 |           DIV#1                 Button1
|         |
| DIV#2   |
|         |
----------------------------------------------------------
|         |
-----------

**The CSS** 
#div1{

    height: 200px;
    width:500px;
    position: relative;
}
#div2{
    height: 150px;
    width: 150px;
    left: 19px;
    top: 76px;
    position: absolute;
}

**Javascript**
$("#button1").hide();
$("#button2").hide();

$('#div1').mouseover(function() {
$("#button1").show();
});

$('#div1').mouseout(function() {
$("#button1").hide();
});

$('#div2').mouseover(function() {
$("#button2").show();
});

$('#div2').mouseout(function() {
$("#button2").hide();
});

HTML There are many elements in my document, but for clarity:

<div id='div1'>  <div id='div2'>example button2 </div> example button1 </div>

The issue at hand:

When hovering over DIV#2, Button1 also shows up. It seems like these two divs are somehow connected. Is there a way to ensure that Button1 only displays when hovering over DIV#1?

I attempted to use z-index, but it did not solve the problem.

Answer №1

If div2 is positioned on top of div1, there may be an issue when the mouse hovers over the area where both divs overlap. In such cases, both divs may trigger a mouseover event. To prevent this from happening, you can use event propagation on #div2 to ensure that the mouseover event does not transfer down to the underlying div1 when the cursor moves over div2 and into the overlapping region.

$('#div2').mouseover(function(event) {
    $("#button2").show();
    event.stopPropagation(); // prevents mouseover event on other div
});

Similarly, you might want to include code that hides button1 when the mouse transitions from div1 to

div2</code without fully exiting the underlying <code>div1
- specifically in the overlapping zone.

$('#div2').mouseover(function(event) {
    $("#button1").hide();
    $("#button2").show();
    event.stopPropagation();
});

Answer №2

When div two is a child of div one, the hover event on div two bubbles up to div one. To prevent this from happening, you can use event.stopPropagation() like so:

/* CSS */
#button1, #button2 {
    display: none;
}

/* jQuery */

$(function() {

    $('#div2').hover(
        function(event) {
            event.stopPropagation();
            $('#button2').toggle();
        },
        function(event) {    
            event.stopPropagation();   
            $('#button2').toggle();
        });

    $('#div1').hover(
        function() {
            $('#button1).toggle();
        },
        function() {
            $('#button2').toggle();
        });


});

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

Ways to control the display of pagination pages in a React application

I am working on a web application using the MERN stack. The pagination feature has been implemented in React and Bootstrap. https://i.sstatic.net/ZqbLm.jpg https://i.sstatic.net/iAOIL.jpg WHAT AM I LOOKING FOR? I currently have a small data set, so the pa ...

A guide to incorporating nested loops with the map method in React JS

I've come across numerous threads addressing the nested loop using map in React JS issue, but I'm still struggling to implement it in my code. Despite multiple attempts, I keep encountering errors. Here are some topics I've explored but cou ...

Fixing the issue: "Tricky situation with JavaScript not working within Bootstrap 4's div tag while JS functions properly elsewhere"

Currently, I'm working on implementing a hide/show function for comments using JavaScript. Fortunately, I was able to find a helpful solution here (thanks to "PiggyPlex" for providing the solution on How can I hide/show a div when a button is clicked? ...

Using Javascript and the Document Object Model (DOM) to parse a Key/Value

When a server sends a string to the Firefox Browser, it is in the following format: "KEY:a1 VAL:123.45" This string can consist of multiple records like this. Below is the code I wrote to handle this information: var e; var reply = request.resp ...

Only the (click) event is functional in Angular, while the (blur), (focus), and (focusout) events are not functioning

I have a unique HTML element as shown below <div (hover)="onHover()" (double-click)="onDoubleClick()" (resize)="resize()" (dragend)="dragEnd()"> These 4 functions are designed to display information onHover ...

Adding a hash to asset paths in NextJS static builds

After running next build && next export, I receive a directory named out, which is great. When examining the source code, such as in the index.html file, it requests assets from <link rel="preload" href="/_next/static/css/styles.aa216922.chunk. ...

Issue with Showing Hidden Section using Jquery - Try it Out on JSfiddle!

I'm struggling with a script that should reveal a hidden <div> when a checkbox is clicked. Despite my best efforts, I can't seem to get the section to display correctly. The snippet of code in question looks like this... If you'd like ...

angular dropdowns that cascade

I want to create cascading drop-down menus in Angular, where each menu populates based on the selection made in the previous one. There will be a total of 5 dropdowns, with only the first one initially populated. The subsequent dropdowns should populate ba ...

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...

Mixed Protocol Error (HTTP/HTTPS)

I'm experiencing a mixed content error on my website, as it is using both http and https protocols. Chrome console displays the following error: Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure XMLHttpReques ...

Issue with SALON theme causing logo to not display on Wordpress site

It's puzzling why the logo image I uploaded to the WP theme isn't showing up on the front-end. I've reached out to the theme developers multiple times, but it's been two months without a response, and my client, as well as myself, are ...

Display the text area when the "Yes" radio button is clicked, while it remains hidden either by default or when the "No" radio button is selected

I am currently working on an html code and I am looking for a way to use java script in order to create a text area box only when the "Yes" radio button is selected. This text area should be hidden by default or when selecting "NO". <table class="tab ...

When it comes to adjusting the height of an element, there are two ways to go about it: using $(element).height

function adjustHeight(){ var headerHeight=$(element).find('.header').outerHeight(); console.log(headerHeight); var temp=$(window).height()-headerHeight; console.log(temp); $('.users ...

Convert a number to binary in JavaScript, but display the result as infinity

data = parseInt(num); bin =0; pow=1; var rem=0 ; while(data != 0){ rem = data % 2; data = data / 2; bin = rem * pow + bin; pow = pow *10; } document.write(bin); I encountered an issue with my JavaScript code. Even though the example should output 11011 ...

Having trouble with jQuery loading for the first time

I am having trouble getting the jQuery to load properly. My goal is to toggle classes on specific items identified by their ID. When an item is clicked, I want it to have the class "menu-selected" while the other item has the class "unselected." I have i ...

What is the process behind managing today's Google image of the day?

After coming across the javascript picture control on the Google search page, I became interested in replicating it myself. The feature zooms in on a picture when hovering over it, but I couldn't locate the HTML code they were using for it. Is there ...

Verify whether the element within an iFrame contains any content

After conducting extensive research, I have been unable to find a satisfactory answer to my question. Therefore, I am reaching out to see if anyone has the knowledge I seek. The Goal: I aim to check the contents within an iFrame and determine whether it ...

Assign the DatePicker Object to an HTML Element

I am currently using a SyncFusion date picker in my project and the implementation looks like this: var datepicker = null; $("#datepicker").hide(); $("#click").click(function(){ $("#datepicker").show(); datepicker = new ej.calendars.DatePi ...

Align the label vertically with the corresponding input field

I am currently in the process of revamping an old HTML form to eliminate the use of tables. I found a solution on this site to give the label a fixed width, and here is how it looks in the current code: HTML <div id="form"> <label for="field ...

Error loading ngsw-worker.js in Angular 7

Issue An app that utilizes a Service Worker is experiencing problems. The app was recently upgraded from Angular 6.1 to version 7. Upon uploading the updated files to the server, an error message is displayed: https://i.sstatic.net/B7uPf.png Error Det ...