Detecting mouse hover over a jQuery div element

I am looking to implement a mouse hover effect in my product section, where each image should display its title only when hovered over. Currently, all titles are being shown on mouseover, which is not the desired behavior.

The following code works for mouseover events but it applies the 'highlight' class to all elements. I want the script to only apply the 'highlight' class to the specific element being hovered over, such as the first div with the class='top-section'.

HTML

<div class ="featured">
    <div class="featured-section">
    <a href="#" class="featured-link">
    <div class="top-section">
        <img src="1.jpeg">
        <span class="highlight">
            <h3 class="title">title 1</h3>
        </span>
    </div>
    
    </a>
    </div>

   <div class="featured-section">
    <a href="#" class="featured-link">
    <div class="top-section">
        <img src="2.jpeg">
        <span class="highlight">
            <h3 class="title">title 2</h3>
        </span>
    </div>
    
    </a>
    </div>

   <div class="featured-section">
    <a href="#" class="featured-link">
    <div class="top-section">
        <img src="3.jpeg">
        <span class="highlight">
            <h3 class="title">title 3</h3>
        </span>
    </div>
    
    </a>
    </div>
</div>

Script

  $(".top-section").on({
    mouseenter: function () {
      $(this).find(".highlight").addClass("show").fadeIn();

    },
    mouseleave: function () {
        $(this).find('.highlight').removeClass("show").fadeOut();
    }
});

Answer №1

The problem arises because all .highlight elements in the DOM are selected when the events are triggered. It is important to only select the ones that are relevant to the .top-section that triggered the event.

To achieve this, use the this keyword in the event handler to reference the element that raised the event and then use find() from there:

$(".top-section").on({
  mouseenter: function() {
    $(this).find(".highlight").addClass("show").fadeIn();
  },
  mouseleave: function() {
    $(this).find('.highlight').removeClass("show").fadeOut();
  }
});
.highlight { 
  display: none; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="featured">
  <div class="featured-section">
    <a href="#" class="featured-link">
      <div class="top-section">
        <img src="1.jpeg">
        <span class="highlight">
          <h3 class="title">title 1</h3>
        </span>
      </div>
    </a>
  </div>

  <div class="featured-section">
    <a href="#" class="featured-link">
      <div class="top-section">
        <img src="2.jpeg">
        <span class="highlight">
          <h3 class="title">title 2</h3>
        </span>
      </div>
    </a>
  </div>

  <div class="featured-section">
    <a href="#" class="featured-link">
      <div class="top-section">
        <img src="3.jpeg">
        <span class="highlight">
          <h3 class="title">title 3</h3>
        </span>
      </div>
    </a>
  </div>
</div>

It should be noted that your approach can be improved by using CSS alone for better performance and efficiency:

.highlight { 
  opacity: 0;
  height: 0px;
  display: block;
  transition: opacity 0.3s, height 0.3s;
}

.top-section:hover .highlight {
  opacity: 1;
  height: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="featured">
  <div class="featured-section">
    <a href="#" class="featured-link">
      <div class="top-section">
        <img src="1.jpeg">
        <span class="highlight">
          <h3 class="title">title 1</h3>
        </span>
      </div>
    </a>
  </div>

  <div class="featured-section">
    <a href="#" class="featured-link">
      <div class="top-section">
        <img src="2.jpeg">
        <span class="highlight">
          <h3 class="title">title 2</h3>
        </span>
      </div>
    </a>
  </div>

  <div class="featured-section">
    <a href="#" class="featured-link">
      <div class="top-section">
        <img src="3.jpeg">
        <span class="highlight">
          <h3 class="title">title 3</h3>
        </span>
      </div>
    </a>
  </div>
</div>

Answer №2

If you're looking to achieve a similar effect, here's an option:

$(".header-section").on({
    mouseover: function () {
      // Using .children() with jQuery allows you to target specific elements within the parent
      $(this).children().last().addClass("display").fadeIn();

    },
    mouseout: function () {
        $(this).children().last().removeClass("display").fadeOut();
    }
});

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

Issue Encountered When Converting style.css.scss to style.css.scss.erb: File Not Found

Struggling with getting my background images to show up after deploying my Rails app on Heroku has been quite a challenge. After diving into the Heroku documentation, I discovered this helpful tip: In Rails 4 sprockets only generate digest filenames, whic ...

I plan to compile a collection of names in a text field and then have the ability to select and access each name individually with just a click

I am currently working on a project that involves creating an admin site using Firebase. One of the main features of the site is large text fields that display information which can be modified. For instance, the user management page includes text fields ...

What are the best methods for preventing scss styles from leaking between pages?

I'm currently working on a project that includes the following files: /* styles/1.scss */ body { /* Some other styles not related to background-color */ } /* styles/2.scss */ body { background-color: blue; } // pages/one.js import "../styles/ ...

I am trying to use jQuery to dynamically change classes based on certain conditions. However, I am encountering an issue where the class of my 'home' link remains unchanged even after clicking on another link. How

How can I modify my jQuery code to achieve the following: If the 'home page' is active, then apply CSS class A (dark green color) to the 'home link'; otherwise, apply CSS class B (brown color). (In essence, I want the relevant link to ...

Determine the div's width inside the viewport

I am trying to determine the width of a div within the viewport. When using .css(width) on my div, it calculates the overall width instead. Here is the code I am currently using: var $Windowwidth = $(window).width(); var $lefty = $("#gallerytop"); var $G ...

How to float two divs using flex in Bootstrap 4

I'm having trouble floating two divs within a row or container div. Despite using the classes .justify-content-md-start and .justify-content-md-end, the divs remain next to each other without any float. I've also tried using classes like float-l ...

Using Bootstrap 3's hidden-xs class can help slim down the width of

I am currently testing out the Bootstrap 3 responsive grids and attempting to hide a column from a row when the screen size is small. However, I find that when the column disappears, the entire row seems to shrink in width. Here's the code causing me ...

Error transitioning between login and sign up pages

I'm encountering an issue with the login overlay transitions. Everything seems to be working fine, but there's a problem when you click on "Forgot Your Password?", then click back on "Suddenly Remembered? Login Here", it closes the overlay instea ...

Steps to Retrieve and Showcase a Compilation of YouTube Clips with JavaScript

Recently, I managed to write a C code that retrieves the list of YouTube videos from the URL "*http://gdata.youtube.com/feeds/api/standardfeeds/top_rated*" using the libsoup library. By utilizing libxml2, I was able to parse the XML data and extract specif ...

What steps can be taken to eliminate the 1-pixel line between the background and gradient?

https://i.sstatic.net/nbtkK.png How can I remove the line that appears between the block and the gradient background when zooming in, especially noticeable in Safari (After zooming a couple times, Cmd +) For more details, please refer to this jsfiddle li ...

Deliver CSS and JS files from directories outside of the public folder in Laravel 5

Although it may seem to deviate from Laravel's structured approach, I have a method to my madness. My plan is to use a single installation of Laravel to host multiple database-driven websites. Currently, all these sites share the same layout, with a s ...

issue with mobile toggle functionality in bootstrap 4

I have successfully implemented a mobile nav using Bootstrap 3, but now I am trying to upgrade to Bootstrap 4. I am testing with local versions of the files and I believe everything is set up correctly. However, the toggle on mobile is ...

Exploring the Input Items to Extract Minimum and Maximum Values

I am seeking assistance with implementing JQuery Min Max Validation for dynamically created input items in a looping structure. On my PHP page, I have a dynamic table that iterates through data fetched from the database. The number of input items (cells) i ...

Apply the "active" class to the list item when its corresponding section is in view

I have a webpage with at least four sections. My goal is to dynamically apply the active class to the corresponding menu item when scrolling through each section. For instance, if the "About Us" section is visible on the screen, I want to mark the correspo ...

What is the best way to incorporate a description box for each city on the svg map that appears when you hover your mouse over it?

I am looking to display detailed descriptions for each city in the same consistent location on my map. With multiple pieces of information to include for each city, I want to ensure that the description box is positioned at the bottom of the map. Can any ...

Creating a custom directive for input validation in Angular

I am currently working on building a basic custom directive in AngularJS to validate if the user input is an integer or not. When the user types in an integer, I want an error message to display at the bottom that states "integers are not allowed". Do yo ...

Troubleshooting server-side sorting issues with AJAX implementation, encountering problems with headers functionality

I'm encountering a problem: Some headers are not functioning properly to sort the table. For example, Brand and Model work as expected, but VehicleType only works once, and CarID and ReleaseDate never seem to work. Here is my index.php file: index. ...

Positioning a sticky footer in a dual-column design

This updated post is a revised version of the one found at this link. I aim to provide a clearer explanation of my issue compared to the previous post. The problem revolves around the placement of the footer in two different scenarios. Scenario 1: https: ...

Creating a sleek animated analog clock using CSS and jQuery

I am facing a small issue with my CSS3/jQuery analog clock. Currently, the movement of the clock hands is a bit abrupt. I would like the animation to be smooth. I attempted using transition: all .1s, but it gets messy when the clock hands reach the top po ...

Begin by directing your view towards an object with FirstPersonControls

When I have FirstPersonControls enabled, my camera.lookAt(cube.position) doesn't work. How can I make it so that I start exploring by automatically looking at the object first? Thank you, ...