NewBoy
NewBoy

Reputation: 1144

Jquery next() function not returning class

I am still trying to get the hang of the next() function in jQuery. I have created a hover function, when you hover the image, a transparent overlay appears per image

Click here for an example

For some reason my next() is not working, I am assuming my jQuery set up is incorrect. Below is an a snippet of my code:

$(document).ready(function () {
    var $this = $(this);
    $('.dummy').removeClass('overlay2');
    $this.parent().next('.dummy').addClass('overlay2');
});
});

Can someone correct where I have gone wrong?

Upvotes: 1

Views: 71

Answers (1)

Joe
Joe

Reputation: 15528

This can be easily accomplished without using any javascript:

.dummy {
    height: 100%;
    width: 100%;
    position: absolute;
    top:0;
    background: #000;
    opacity: 0.50;
    display: none;
}

.figure-item:hover .dummy{
    display: block;
}

I just changed .overlay2 to .dummy in your stylesheet and added display: none;, then made it so hovering over .figure-item sets .dummy to display: block;.

Here it is working: http://jsfiddle.net/zaX5U/6/


Old JS Solution:

This should work for you:

$(document).ready(function () {
    $('.figure-img').on('mouseenter mouseleave', function(e){
        var $this = $(this),
            toggle = e.type === 'mouseenter';
        $('.dummy').removeClass('overlay2');
        $this.find('.dummy').toggleClass('overlay2', toggle);
    });
});

The reason your previous code wasn't working was because it looked like you'd forgotten to include the line with the event handler in (there was an unmatched }): in the fiddle). This meant that $(this) was actually document and so the code didn't work.

.hover() interally maps to .on( "mouseenter mouseleave" and in this case it makes the code smaller to use the full version. This also use the .toggleClass() function with the optional switch argument to either remove or add the class depending on the type of event.

Fiddle: http://jsfiddle.net/zaX5U/4/

Upvotes: 2

Related Questions