JQuery's hover functionality is causing problems

I am experiencing an issue with the hover function. Here is an example:

<a href="http://jsfiddle.net/sushanth009/YeBMA/1/">Click here  </a>

$('.curtain').hover(function() {
  var $container = $(this).closest('div.container');
  $container.find('.containerLeft').addClass('lefthover');
  $container.find('.containerRight').addClass('righthover');
}, function() {
  var $container = $(this).closest('div.container');
  $container.find('.containerLeft').removeClass('lefthover');
  $container.find('.containerRight').removeClass('righthover');
});
.lefthover {
  border: 2px solid green;
}
.righthover {
  border: 2px solid orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <img class="curtain containerLeft" src="http://example.com/containerleft.jpg" />
  <img class="curtain containerRight" src="http://example.com/containerright.jpg" />
</div>
<div class="container">
  <img class="curtain containerLeft" src="http://example.com/containerleft.jpg" />
  <img class="curtain containerRight" src="http://example.com/containerright.jpg" />
</div>
<div class="container">
  <img class="curtain containerLeft" src="http://example.com/containerleft.jpg" />
  <img class="curtain containerRight" src="http://example.com/containerright.jpg" />
</div>

When I hover over an image, a class should be added and then removed, but instead the class gets added multiple times automatically.

Could anyone provide assistance?

Answer №1

Try using this updated jQuery code and see the results

$('.curtain').hover(function() {
  var $container = $(this).parent('.container');
  $container.children('.containerLeft').addClass('lefthover');
  $container.children('.containerRight').addClass('righthover');
}, function() {
  var $container = $(this).parent('div.container');
  $container.children('.containerLeft').removeClass('lefthover');
  $container.children('.containerRight').removeClass('righthover');
});

Feel free to test it out on this fiddle link

Answer №2

The main cause of this issue is the rapid firing of the hover function, especially when using mouseenter and mouseleave, which is what triggers jQuery's hover function.

I have personally found a solution in the form of a plugin called hoverIntent. You can access it here. Essentially, this plugin calculates distance (when your mouse enters the "area", and if it exits within a certain timeframe). By making these calculations, it prevents the event (hover) from triggering multiple times and only activates it when the user genuinely hovers for a specified duration (based on the options provided). You have the flexibility to customize and pass in various options during initialization of the plugin.

This tool has been available for quite some time now and has proven to be extremely helpful on numerous occasions. I highly endorse its usage.

Below is an example demonstrating how you can implement hoverIntent:

$('.container').hoverIntent({
    selector: '.curtain',   // similar to using jquery's `on` event
    sensitivity: 2,  // adjust as needed - refer to documentation
    interval: 50, // default is 100
    over: function () {
       var $container = $(this).closest('div.container');
       $container.find('.containerLeft').addClass('lefthover');
       $container.find('.containerRight').addClass('righthover');
    },
    out: function() {
      var $container = $(this).closest('div.container');
      $container.find('.containerLeft').removeClass('lefthover');
      $container.find('.containerRight').removeClass('righthover');
    }
});

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

"Exploring the world of jQuery and optimizing navigation for mobile

I am currently developing an HTML5 Mobile App where I have implemented panels as pages in the following way: <div class="upage panel" id="account_page" data-header="af-header-4" data-footer="none"> Additionally, I have created a login page structur ...

What could be causing my website to resize when I test it offline versus when I upload it online?

I've been working on a new website and I keep all my files in a folder on my desktop for easy access. During the testing phase, I usually open the index page in various browsers to preview how it looks as I build it. Everything appeared correctly in F ...

Tips on ensuring a jQuery script continues to run even after the window location has been changed

Is there a way to wait for the page to reload from HTTP to HTTPS using document.location before continuing the jQuery script? The script seems to be executing before the new location is fully loaded. How can I ensure that the script waits for the reload ...

Using a specialized component to trigger the opening of a Material UI dialog

I have a requirement where I need to pass a custom component to an MUI Dialog so that the Dialog can open itself and render its children. const CustomDialog = ({children, someCustomComponent}) => { const handleClickOpen = () => { setOpen(true); } ...

What is the best way to add a custom class alongside cdk-overlay-pane for a material menu in Angular 7?

I have a specific requirement to create a mega menu using Angular Material Menu. I attempted to apply some custom styling to the cdk-overlay-pane using my own class, but it did not work as expected. I tried to add a custom class to the mat-menu element us ...

Simple steps to trigger a PHP page from a JavaScript page by utilizing express functions

Currently, I am attempting to showcase a PHP page using JavaScript with express functions. Here is an illustration of the code: var express = require('express') var app = express() app.get('/', function (req, res) { res.send(' ...

What is the process for bringing an array from a .js file into an HTML document?

Exploring the world of JS and HTML, I recently came across an assignment that involved working with a file named stocks.js, which houses an array of stock information: 'use strict'; const stocks = [ { company: 'Splunk', symbol: &ap ...

When a button is clicked in AngularJS 2, choose a HTML element and attach it to a different element

I need to implement functionality in Angular2 where I can select an HTML element and append it to another div upon clicking a button. Initial HTML structure as follows: <div class="parent"> <ul class="level1"> <li> <div cl ...

Webpack fails to handle CSS background images

I'm having trouble with my Webpack configuration as it's not processing CSS images set in the background property: background: url('./hero.jpg') no-repeat right; This is resulting in an error message that reads: ERROR in ./src/app/comp ...

What could be causing my function to execute thrice?

I cannot seem to figure out why my tag cloud is causing the required function to run multiple times instead of just once when I click on a tag. This issue persists whether using jQuery or plain JavaScript. What am I missing? The code I have is very simple, ...

Preserving input data based on click and change events

Upon form submission, I encounter an issue with displaying only the divs that contain fields with saved values. The form saves user-entered values using PHP, where some of the fields are initially hidden within div elements until an onclick or onchange eve ...

Tips for updating the background color of your navigation bar:

I've been using bootstrap and I want to customize the active page background color to green, but for some reason it doesn't seem to be working. .navbar-inverse { color: #fff; background-color: #4CAF50; } <nav class="navbar navbar-invers ...

Achieving Flexbox alignment in a responsive layout

Struggling with achieving a responsive layout using Flexbox. Picture a page filled with panels. The main objective is to display a certain number of panels per row, aligned both horizontally and vertically like the rest. The main issue I am encountering ...

Breaking HTML attribute values into separate lines will make the code more organized and easier

Is it possible to format HTML attribute values so they can span across multiple lines? Essentially, I'm wondering if there is a way to include line breaks within a regular typed HTML attribute value. For instance, in the functional code snippet below ...

The video auto plays in a pop up window, but if the pop up doesn't appear, I can still hear the audio

I recently added a pop-up to my website and attempted to include autoplay functionality. However, I encountered an issue where the sound would still play even if the pop-up did not appear upon refreshing the page. How can I prevent the autoplay when the po ...

Having difficulty adjusting the padding of the Material UI table

I have been using the Table component provided by the material-ui library in my React project. However, I have encountered an issue where each row, including the header, has a padding of 24px on the top and bottom that I am unable to modify or overwrite. D ...

Navigating through Dojo Web Tables nested within <Div> elements

click here to view image descriptionI am facing a challenge with a web page that contains a table where I need to select a specific element. In traditional tables, this can be done by counting rows and columns, but in the Dojo page, these elements are ne ...

Dynamically loading audio references in a foreach loop using C# MVC

One approach I am exploring involves utilizing a foreach loop to play an audio file by first storing a reference to the sound. The method in place successfully achieves this using <audio controls> <source src="~/Sounds/@item.Irish_Tr" id="@ ...

When using Visual Studio, inserting text into a cshtml file results in the deletion of existing

When working in Visual Studio 2022 (version 17.2.1), I've noticed a strange issue. Whenever I paste some text into a cshtml file, the pasted text appears to be copied but then immediately deleted, sometimes even taking part of the existing text along ...

Interactions between JavaScript and PHP scripts within a web application

THE SCENARIO In the midst of creating a web application that dynamically loads content by fetching data from a MongoDB database where items and their respective authors are stored in separate collections within the same database. The author's ID is s ...