Display a div using Jquery when hovering over it with several classes

I want to create a hover effect where div2 fades in slowly when hovering over div1 within the same container. However, my jQuery code doesn't seem to be working as expected...

$(".div").hover(function() {

  $(this).find(".div2").animate({
    opacity: "1"
  }, {
    queue: false
  });
}, function() {
  $(this).find(".div2").animate({
    opacity: "0"
  }, {
    queue: false
  });
});
.div2 {
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div>
    <div class="div1">
    </div>
    <div class="div2">
    </div>
  </div>
  <div>
    <div class="div1">
    </div>
    <div class="div2">
    </div>
  </div>
  <div>
    <div class="div1">
    </div>
    <div class="div2">
    </div>
  </div>
</div>

Answer №1

When you're aiming for $('.div'), make sure you're not mistakenly targeting $('.div1') or $('div'). The element with the class .div doesn't exist in your code, so it's likely a typographical error.

Additionally, if you intend to trigger the event when hovering over a '.div1' element, switch from using .find() to .next(). This is because you want to pinpoint the next sibling rather than a child.

Here is a functional example to guide you:

https://jsbin.com/vipifolahe/edit?html,js,output

HTML

<div>
    <div>
         <div class="div1">
         </div>
         <div class="div2">
         </div>
    </div>
    <div>
         <div class="div1">
         </div>
         <div class="div2">
         </div>
    </div>
    <div>
         <div class="div1">
         </div>
         <div class="div2">
         </div>
    </div>
</div>

CSS

.div1 {
  height: 50px;
  background-color: red;
}

.div2 {
  height: 50px;
  background-color: green;
}

.div2 {
  opacity: 0;
}

JS

$(".div1").hover(function () {

  $(this).next(".div2").animate({
    opacity: "1"
  }, {
    queue: false
  });
}, function () {
  $(this).next(".div2").animate({
    opacity: "0"
  }, {
    queue: false
  });
});

If your aim is to trigger the event when hovering over the parent div, consider this example:

HTML

<div>
    <div class="parent">
         <div class="div1">
         </div>
         <div class="div2">
         </div>
    </div>
    <div class="parent">
         <div class="div1">
         </div>
         <div class="div2">
         </div>
    </div>
    <div class="parent">
         <div class="div1">
         </div>
         <div class="div2">
         </div>
    </div>
</div>

JS

$(".parent").hover(function () {

  $(this).find(".div2").animate({
    opacity: "1"
  }, {
    queue: false
  });
}, function () {
  $(this).find(".div2").animate({
    opacity: "0"
  }, {
    queue: false
  });
});

Answer №2

Check out the Live Demo

JavaScript Code

 $(document).ready(function(){
  $('.div1').mouseenter(function(){
    $(this).next('.div2').css('opacity','1');
  });
  $('.div1').mouseleave(function(){
    $(this).next('.div2').css('opacity','0');
  });
});

Answer №3

If you're interested in a CSS-only solution, try utilizing the sibling selector

.div2 {
  opacity: 0;
}

.div1, .div2 {
  border: 3px solid pink;
  width: 50px;
  height: 50px;
}

.div1:hover + .div2 {
  opacity: 1;
}
<div>
  <div>
    <div class="div1">
    </div>
    <div class="div2">
    </div>
  </div>
  <div>
    <div class="div1">
    </div>
    <div class="div2">
    </div>
  </div>
  <div>
    <div class="div1">
    </div>
    <div class="div2">
    </div>
  </div>
</div>

Answer №4

There is no element with the class div, so none of the divs are being selected. To make each div responsive to hover events, assign a class that will handle both mouseenter and mouseleave actions. Here is an example code snippet:

$(".wrapper").hover(function () {
    $(this).find(".div2").animate({
        opacity: "1"
    }, {
        queue: false
    });
}, function () {
    $(this).find(".div2").animate({
        opacity: "0"
    }, {
        queue: false
    });
});
.div2 {
    opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div class="wrapper">
         <div class="div1">one
         </div>
         <div class="div2">one hidden
         </div>
    </div>
    <div>
         <div class="div1">two
         </div>
         <div class="div2">two hidden
         </div>
    </div>
    <div>
         <div class="div1">three
         </div>
         <div class="div2">three hidden
         </div>
    </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

Using jQuery to Determine if a URL Contains a Query String

In the scenario where it is the first visit to the site and no query string has been added, or if there is only one query string attached to the URL '?hos' like , I need to apply the if condition. The else condition is functioning correctly. How ...

Dealing with audio bleed from a previous recording using fluent-ffmpeg

const Discord = require('discord.js'); const client = new Discord.Client(); const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg'); const ffmpeg = require('fluent-ffmpeg'); ffmpeg.setFfmpegPath(ffmpegInstaller.path); co ...

Delete the option to alter button in the Jasny file input tool

I recently incorporated the Jasny Fileinput Widget into my existing form. However, I noticed that when I select a new file, it displays two buttons: Change and Remove. In this case, I believe the Change button is unnecessary and would like to remove it com ...

Navigating the issue of updateMany not functioning properly in mongoose and nodejs

I need assistance with updating the author name of a post whenever the user updates their profile name. My code is as follows: router('/:id', async (req, res) { if (req.body._id == req.params.id) { try { const user = await ...

Using VBA and Selenium to access iframes within HTML with the #document tag

I am currently facing a challenge in accessing the HTML content within two iframes using Selenium Basic in VBA. Due to restrictions on our machines, we are unable to use IE and other tools like Python are not available to us. In the past, I was able to ac ...

What could be the reason my HTML5 application is not working offline on my android device?

Hello, I am encountering a problem and I could really use your assistance in figuring out what I am missing. There is a webpage that showcases numerous HTML5 mobile/web applications which can be found at For instance, let's look at this app where yo ...

html - Removing excess space following the footer

Having trouble getting rid of the excess white space below my footer on this website: I attempted to search for a solution online and even added padding:0; to the footer's CSS, but unfortunately it didn't solve the issue. Appreciate any assista ...

Adjusting the size of content with CSS

I've been attempting to get an image to cover the entire screen on a device using CSS, but so far I haven't had any success. The image is within an :after pseudo element and content tag. Since it needs to be laid over the HTML, I can't use t ...

Locate a jquery element that is within a parent element containing specific text

This is the format I currently have: <td width="270px"> <img class="bullet" border="0" valign="top" src="gray-bullet.gif"> this is the text </td> Can someone provide me with a query to specifically target the img element with the class ...

Ways to retrieve information from a URL using the .get() method in a secure HTTPS connection

As I work on handling user input from a form using node.js, express, and bodyParser, I encounter an issue. Even after using console.log(req.body), the output is {}. This is puzzling as there is data in the URL when the form is submitted successfully at htt ...

Challenge with uploading Minio presigned URLs

I am encountering a problem with the Minio presigned URL. While I have successfully obtained the URL and used the PUT method to insert my file into my Minio bucket, I am unable to open certain file types such as jpg, png, or pdf. This is due to Minio autom ...

What is the best way to display a removed item from the Redux state?

Display nothing when the delete button is clicked. The issue seems to be with arr.find, as it only renders the first item regardless of which button is pressed, while arr.filter renders an empty list. reducer: export default function reducer(state = initi ...

Personalize scrollbar appearance in Mozilla Firefox and Internet Explorer

When it comes to customizing the scrollbar in chrome, CSS makes it easy: ::-webkit-scrollbar { width: 7px; } Unfortunately, this method does not have the same result in Firefox (version 38) and IE (version 11). I attempted the following code as an alter ...

jQuery Ajax Load() causing screen to refresh unintentionally upon clicking

I am currently developing a web application that includes side menus. However, I am facing an issue with the functionality of these menus. Whenever I click on certain options, the entire page refreshes. For example, under my main menu "Planning the Engagem ...

Adding metadata fields to an existing Markdown file within TinaCMS

Is it feasible to enhance a Markdown file using TinaCMS by introducing new frontmatter fields? Instead of generating a brand new Markdown file, my goal is to modify the current one by appending new frontmatter fields. Currently, I am able to modify a sin ...

How to effectively use graph paper with both major and minor grids in the background?

Looking to create a 100px by 100px image in Inkscape with major lines every 100px and minor lines every 10px. This will help verify viewport size when used as a repeating background. What's the best approach for this? Thinking of using #888888 for ma ...

Guide on implementing jQuery Validation plugin with server-side validation at the form level

Does anyone have a suggestion for how to handle server-side validation errors that occur after passing the initial client-side validation on a form? $("#contact_form").validate({ submitHandler: function(form) { $.ajax({ type: 'POST', ...

Check out this awesome jQuery Image Hover Plugin that allows you to create dynamic animations when hovering over other elements

Is it possible to use Adipolo in a way that allows hovering over a different element for the image animations to work? Currently, I am using the following code: $('#img-caption-one').adipoli({ 'startEffect' : 'grayscale' ...

React JS: You must define 'Message' in order to avoid the react/jsx-no-undef error

As a novice learner in React JS, I am currently working on developing a messaging web application. However, as I was writing my code, I encountered the following error: Failed to compile. ./src/App.js Line 41:17: 'Message' is not defined react/j ...

Tips for stopping an image from stretching the cell in flexbox using CSS

When using Flexbox to style elements, the width of the parent should be determined by the text inside child1. The image inside child2 should grow proportionately as the parent grows. However, it is important to ensure that the parent div does not exceed it ...