Mike Barwick
Mike Barwick

Reputation: 5367

jQuery - HOVER applied to one CLASS at a time

I have the following HTML added to various DIV's cross my application. It's an overlay that I want to show on only the DIV that's hovered. However, if I hover over any element with the HTML block of code below, as the overlays will show on all the DIVs. But I only want the overlay to show on the DIV i hover, not all of them. I was attempting to find the .parent(), but it's not working. What am i doing wrong?

<div id="appBillboard">
    <!-- edit window overlay -->
    <div class="editOverlay">
        <div class="editBTN">
            <div class="editIcon bL5"></div>
            <div class="editTxt bR5 bRLight">EDIT</div>
        </div>
    </div>
</div>

JS:

//HOVER HIDE & SHOW EDIT OVERLAY AND BUTTON

var editBTN = $('.editBTN');
var overlay = $('.editOverlay');

$(editBTN).fadeTo(0, 0.90);

$(overlay).hover(function () {

    //find parent div
    var location = $(this).parent();

    $(overlay, location).fadeTo(0, 1);
    $(editBTN, location).fadeTo(0, 1);
    $(overlay, location).addClass('overlayBKGND');

}, function () {
    $(overlay).removeClass('overlayBKGND');
    $(editBTN).fadeTo(0, 0.90);

});

Upvotes: 0

Views: 89

Answers (3)

jfriend00
jfriend00

Reputation: 707326

You need to use selectors that are scoped only to the hierarchy that you are in. As such, you can't use your cached jQuery objects as they include all objects.

In addition, you have to recalculate the location variable in each of the two functions passed to .hover() as they are separate functions and don't share local variables.

I also don't know why you're using fadeTo() with a 0 for the duration of the animation. It's probably better to just use .css("opacity", value) rather than go through the whole animation code.

Change your code to this:

$(overlay).hover(function () {
    //find parent div
    var location = $(this).parent().parent();
    $('.editOverlay', location).fadeTo(0, 1).addClass('overlayBKGND');
    $('.editBTN', location).fadeTo(0, 1);

}, function () {
    var location = $(this).parent().parent();
    $('.editOverlay', location).removeClass('overlayBKGND');
    $('.editBTN', location).fadeTo(0, 0.90);

});

Upvotes: 1

Ram
Ram

Reputation: 144689

Instead of using parent() methods and using $(selector, context) for selecting the current hovered element, why not using this? try the following:

$('.editBTN').fadeTo(0, 0.90);

$('.editOverlay').hover(function () {
    $(this).fadeTo(0, 1).addClass('overlayBKGND');
    $('.editBTN', this).fadeTo(0, 1);
}, function () {
    $(this).removeClass('overlayBKGND');
    $('.editBTN', this).fadeTo(0, 0.90);
});

Upvotes: 0

Eru
Eru

Reputation: 675

This line of code matches the parent of 'overlay' div:

var location = $(this).parent().parent();

Based on html code u pasted I think you wanted just to get parent div, so:

var location = $(this).parent();

Upvotes: 0

Related Questions