jQuery hoverIntent for only one div class when the class is being used multiple times

StackOverflow https://stackoverflow.com/questions/13127602

  •  15-07-2021
  •  | 
  •  

Вопрос

I am using the jQuery hoverIntent plugin to fade in a div when another div is being hovered over. There are 4 elements that share a class name, and I only want to fade in the children of the element I am hovering over, not every div that shares the class' children. The problem now is if I hover over one dive it fades in all 4 elements children. Where in my code little bit of code have I gone wrong?

Here's the html:

<div id="resources" class="faded">

<div class="resourcesHover"></div>

</div>

<div id="forBuilders" class="faded">

<div class="buildersHover"></div>

</div>

<div id="fam" class="faded">

<div class="famHover"></div>

</div>

<div id="homePlans" class="faded">

<div class="plansHover"></div>

</div>

Here's the jQuery

$(document).ready(function(){

$(".faded").hoverIntent({
    over:    fadeDivIn,
    timeout: 300,
    out:     fadeDivOut
});

function fadeDivIn() {
    var $kids = $('.faded').children();
    $($kids, this).fadeIn('slow');
}

function fadeDivOut() {
    var $kids = $('.faded').children();
    $($kids, this).fadeOut('slow');
}

});

Just in case anyone has a similar issue, I figured out the solution and posted it below.

Это было полезно?

Решение 3

Just figured it out. I added a this, to the line that sets the children into a variable, and also removed it from the .fadeIn and .fadeOut lines.

Here's the new jQuery:

$(document).ready(function(){

$(".faded").hoverIntent({
    over:    fadeDivIn,
    timeout: 300,
    out:     fadeDivOut
});

function fadeDivIn() {  
    var $kids = $(this,'.faded').children();
    $($kids).fadeIn('slow');
}

function fadeDivOut() {
    var $kids = $(this,'.faded').children();
    $($kids).fadeOut('slow');
}

});

Другие советы

Change your fadeDivIn and fadeDivOut functions as follows:

function fadeDivIn() {
    var $kids = $(this).children();
    $($kids).fadeIn('slow');
}

function fadeDivOut() {
    var $kids = $(this).children();
    $($kids).fadeOut('slow');
}

In your fade in and fade out functions, you need to select this instead of all elements of the class faded

$(document).ready(function(){

$(".faded").on('mouseover', function() {
    fadeDivIn(this);
});

$(".faded").on('mouseout', function() {
    fadeDivOut(this);
});

function fadeDivIn(hovered_over) {
    var $kids = $(hovered_over).children();
    $($kids).fadeIn('slow');
}

function fadeDivOut(hovered_over) {
    var $kids = $(hovered_over).children();
    $($kids).fadeOut('slow');
}

});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top