Alex
Alex

Reputation: 49

jQuery Displaying Different Elements (divs) when hovering over other specific elements

FIDDLE >> http://jsfiddle.net/8bwSD/1/

I'm making a website using HTML5, CSS3 and jQuery.

I have a gallery of images. All images have an info box (simple div with some styling) situated within them.

When hovering over the info box, relevant information is shown.

Below is the jQuery to show/hide (slide in/out) the relevant info:

$(".info").hover(function(){
  $(".cap2").slideDown(400);
}, function(){
   $(".cap2").slideUp(300);
});

The info for the images sits inside the HTML.

The 'info' boxes (which are to be hovered over) are also inside the HTML.

Currently, image info and info boxes have their own CSS styling, so whenever I hover over one info box, information is displayed for ALL images at the same time.

So my QUESTION is:

Is there a way to create clean/simple code to show relevant information for each image without having to create seperate CSS styling and jQuery code for each and every info box?

Any help is much appreciated. Thank you!

Upvotes: 1

Views: 248

Answers (2)

Trevor
Trevor

Reputation: 16116

 .hover(function () {
        $(this).next(".cap2")
            .show();
    }, function () {
        $(".cap2")
            .hide();
    });

http://jsfiddle.net/8bwSD/2/

Update

As Milimetric points out you can use next on the hover out function as well. This should improve performance because jQuery does not need to look for all .cap2 elements in the dom just the next one to hide it.

$(document).ready(function () {
    $(".info").hover(function () {
        console.log(this);
        $(this).next(".cap2").show();
    }, function () {
        $(this).next(".cap2").hide();
    });
});

Milimetric's fiddle for reference

jsfiddle.net/8bwSD/4

Upvotes: 2

codingrose
codingrose

Reputation: 15699

Try:

$(".info").hover(function () {
    $(this).closest(".imgcontainer").find(".cap2").show();
}, function () {
    $(this).closest(".imgcontainer").find(".cap2").hide();
});

Updated fiddle here.

Upvotes: 1

Related Questions