Drowning Rat
Drowning Rat

Reputation: 35

Multiple hidden divs to be shown

I have a series of images, behind each of which I have a div with absolute positioning. I'm looking for a way to use jQuery, with one bit of code as short and sweet as possible to enable me to show the otherwise hidden div.

$(document).ready(function(){
    $('#image1').mouseenter(function(){
        $('#imageDescriptor1').show('fast');
    });

    $('#image1').mouseleave(function(){
        $('#imageDescriptor1').hide('fast');
        $('#imageDescriptor1').clearQueue();
    });
});

Obviously in an ideal world, I'd rather not have to repeat the code 5 times; and the text in the imageDescriptoris unique too obviously.
Is there something glaringly obvious I've missed here? Perhaps a way to use $(this) from behind the image? Thanks in advance!

#imageDescriptor1, #imageDescriptor2, #imageDescriptor3, #imageDescriptor4, #imageDescriptor5{
position:absolute;
top:100px;
left:50px;
z-index:50;
display:none;
padding:5px 5px 5px 5px;
background-color:#f3be05;
-webkit-border-radius: 5px 5px 5px 5px;
border-radius: 5px 5px 5px 5px;
max-width:200px;
}

Upvotes: 2

Views: 72

Answers (3)

DaniP
DaniP

Reputation: 38252

Based on your Fiddle example you can do this:

  • First assign a class for the footerBox divs and for the imageDescriptor divs, this to make refference for the Jquery function:

    <div id="footerBox1" class="box">
       <div id="imageDescriptor1" class="inside">
    
  • After you can refference the function with those class names and use the hover() handler:

    $('.box').hover(
        function(){
          $('.inside',this).show('fast');
        },
        function(){
          $('.inside',this).hide('fast').clearQueue();
    });
    

See the demo http://jsfiddle.net/V2rCn/11/

Upvotes: 1

Michal Trojanowski
Michal Trojanowski

Reputation: 12322

You can select an image using its' class (which will apply to all your images) and then traverse the DOM to find the right description using either:

  • find() or children() if the description is a descendant of the image

  • closest() or parent() if the description is an ancestor of the image

  • next() if the description is a sibling of the image

  • or a combination of those above if the DOM structure is more complicated

e.g.

$('.image').mouseenter(function() { 
    $(this).find('.description').show(); 
});

Upvotes: 0

Patrick Moore
Patrick Moore

Reputation: 13344

You could use jQuery .closest() and give your HTML elements classes:

HTML like so:

<img class="image" />
<p class="descriptor">[...]</p>

jQuery Javascript like so (you can include this in DOM ready as in your example):

$(".image").on( "hover", function(){ // mouse enter
    $(this).closest(".descriptor").show('fast');
}, function(){ // mouse leave
    $(this).closest(".descriptor").hide('fast').clearQueue();
});

Upvotes: 0

Related Questions