Ways to show div1 when hovering over div2 and make div1 fade out when the mouse moves away?

I'm looking to create an effect where div1 appears when hovering over div2, and only disappears when neither div1 nor div2 are being hovered over.

I attempted to achieve this using CSS and jQuery, but encountered an issue where div1 would disappear immediately after moving the mouse away from div2, making it difficult to access the content of div1.

    $(document).ready(function() {
      $('.about').hover(
      function() {
        $('.showsection').slideDown(800).addClass('show');
      }
      , function() {
        $('.showsection').slideToggle(800);
         });
      });
.showsection{
display:none;
    }
    .show{
display:block;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class=about>
  <h1>About</h1>
  </div>

  <div class="showsection">
  <h1>Title</h1>
</div>

Answer №1

To achieve this functionality, you can utilize the mouseenter and mouseleave events on the specific elements that you want to toggle visibility.

Here are the necessary steps:

  • Show the element with the class showsection when the mouse enters the element with the class about. This can be accomplished by using the mouseenter event on the about element.
  • Hide the element with the class showsection when the mouse is not hovering over either the showsection or about elements. This involves checking two conditions: ensuring that the mouse is not hovering over the showsection when it leaves the about, and also confirming that the mouse is not hovering over the about when it leaves the showsection. As a result, you need to attach mouseleave events to both the showsection and about elements.

The provided code snippet below demonstrates how to implement this functionality.

// JavaScript
$(document).ready(function() {  
  // When mouse enters .about
  $('.about').on('mouseenter', function() {
    $('.showsection').slideDown(800);
  });
  
  // When mouse leaves .about
  $('.about').on('mouseleave', function() {        
    // If mouse is not hovering over .showsection, hide it
    if (!$('.showsection').is(':hover')) {
      $('.showsection').slideToggle(800);
    }
  });
  
  // When mouse leaves .showsection
  $('.showsection').on('mouseleave', function() {        
    // If mouse is not hovering over .about, hide .showsection
    if (!$('.about').is(':hover')) {
      $('.showsection').slideToggle(800);
    }
  });
});
/* CSS */
.showsection {
  display: none;
  background: #ddd;
}

h1 { margin: 0; }

.about { background: #eee; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class=about>
  <h1>About</h1>
</div>

<div class="showsection">
  <h1>Title</h1>
</div>

Answer №2

When utilizing the CSS :hover attribute, it will solely affect the specific element it is applied to, which in this scenario would be div1. Therefore, to achieve your desired outcome, incorporating JavaScript is necessary.

To accomplish this task, use JavaScript to assign a mouseenter and mouseleave event to div1. Within these event listener functions, specify the actions you would like div2 to perform.

This approach outlines the steps needed to achieve the desired functionality.

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 RoundRect take the top left position of its rectangle container rather than its immediate parent (td)

I am currently troubleshooting an email-related issue that is specifically affecting Outlook In order to create a round Call To Action (CTA) button, I utilized Vector Markup Language (VML) The expected result should look like this: https://i.sstatic.net ...

The issue with the Ajax JSON Loader malfunctioning

Recently, I was working on creating a JavaScript AJAX loader for my blog. Unfortunately, it's not functioning as expected. Initially, everything was working fine until I decided to incorporate months into the parser and JSON file. From that point onwa ...

Execute a function in HTML that has been declared in the controller

Is there a way to automatically trigger a function when an HTML page is loaded? Currently, the function is manually invoked by clicking a button, as shown below: <p> {{address}} </p> <button class="btn btn-primary checkout" ng-click="g ...

Steps to saving an item in the browser's local storage in real-time

My current challenge involves constructing a child array nested within a data array. When a user clicks on buttons to input data, the information does not get saved in localStorage in real-time. For example, if there are 4 buttons with different user input ...

What is the best way to customize global styles in nextJS?

What's the best approach to override CSS rules from my global.css file for specific pages within my website? ...

A correct JSON format for presenting information within an AngularJs framework

I am looking to integrate JSON data into my website using AngularJs. Here is the approach I have taken: First, I created a database in phpMyAdmin. Next, I set up a table with two columns - subject and body. Should an id column be included? After work ...

The flow of events is not hindered by an if statement, even when the code within it is executed

I'm facing an issue where the console.log statement keeps executing even after calling the search function within the "if statements" in my code. Is there a way to prevent this from happening? function search() { /** * The Tweet checking algori ...

How can I efficiently load multiple database divs asynchronously?

Utilizing ajax and jQuery, my goal is to automatically refresh certain divs every 5 minutes with values retrieved from a database. For instance: <div id="1">One</div> <div id="2">Two</div> <div id="3">Three</div> &l ...

The addClass method in jQuery is failing to append the specified class to the element

I'm currently working on a registration form that includes selecting your gender: My goal is to have the male icon turn blue when clicked, and the female icon turn pink. The color change currently works when hovering, but not when clicked. Here is th ...

What is the best way to secure the installation of python packages for long-term use while executing my code within a python shell on NodeJS?

I have been encountering difficulties while attempting to install modules such as cv2 and numpy. Although I have come across a few solutions, each time the shell is used the installation process occurs again, resulting in increased response times. Below i ...

What is the best way to style the header of a table when scrolling in CSS?

Currently, I am facing an issue with applying the top CSS property to the thead element of a table while scrolling. I have attempted various methods but have been unsuccessful in achieving the desired outcome. Initially, I used the scroll event, however, ...

What is the process for obtaining X through the use of createElement('img')?

Is there a way to retrieve the X position from the left of the tag created using document.createElement('img'); var block00 = document.createElement("img"); block00.src = "images/sep1.png"; If so, how can it be done: if (block00.getBoundingCli ...

How can you transform this jQuery snippet into a unique Javascript function?

I've managed to get this code to work, but I'm looking for a way to streamline it using a JavaScript function. This would save me the hassle of writing it out repeatedly. $("#portfolio").waypoint(function() { for (var i = 0; i <= 8; i++) ...

Navigate through the Div and Unordered List with ease by scrolling

What is the reason behind the scrolling behavior of div with arrow keys while ul does not exhibit the same response? This issue is connected to a previous question that I have posted, but has not received any responses yet. ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

Utilize ajax to send both images and text simultaneously

I'm utilizing javascript's 'formData' to transmit image files through ajax. Is there a way to append extra data to formData, like a text string? JS: $("#post-image").on("click", function(){ $.ajax({ url: "../../build/ajaxe ...

What is the best way to ensure that the scroll position on each page in shinydashboard remains unaffected by changes in the scroll position on other pages?

When navigating between pages A and B in my shinydashboard app, I noticed that the scroll position of one page affects the scroll position of the other. How do I make the scrolls independent? To illustrate my issue, I've included a stable shinydashbo ...

Adjust the button's width as the text changes to create a dynamic animation

I'm trying to create an animation effect where the width of a button changes whenever the text inside it is updated. I've attempted using useRef on the button itself to grab its clientWidth and then applying that value to a CSS variable in order ...

Create a feature to disable user accounts using a combination of jQuery, AJAX, and PHP

I have added a deactivate feature to a website I'm currently working on. The feature includes a form with a textarea for users to input their reason for deactivating their account, as well as a button that becomes enabled once the textarea is filled o ...

What is the best way to target an HTML attribute using jQuery?

I have customized a Textbox by adding a special attribute: <asp.TextBox MyCustomAttribute="SomeValue"><asp.TextBox> Now, I want to retrieve this value from within an AJAX success function. Please note that I have excluded irrelevant attribut ...