0
votes

I'm trying to find a simple way with jquery to add a transparent caption to selected images that either slides or fades, using either the alt or title attribute (whichever would be better practice), that also doesn't add additional divs.

Does anyone have a simple way to do this that they can think of?

1
the answer with jquery and css is always: add another div. Why don't you want to add another div?themerlinproject
I was thinking that might be the case, anyway, I was just hoping to be able to add captions without affecting my current css.user1031508
You could just use CSS pseudo-elements instead?Nightfirecat
very true, would it be better to add the new element through html or jquery?user1031508
If you have an answer, post it! Comments are not the place for extensive code. You can answer your own questions. Or update the original post with a "here's one idea" sample.Greg Pettit

1 Answers

1
votes

I've used this method before. Seems to work pretty well, and you're not creating and deleting elements constantly, just moving and changing the contents of one.

See the working Fiddle

Start with your single empty div:

<div id='caption'></div>

The JS: Event listeners on hover and mouseout, to position the div, write the caption, and fade it in.

$('img').hover(function(){
    var yoffset = $(this).height();
    var width = $(this).width();
    var coords = $(this).offset();

    $('#caption').html($(this).data('caption'))
        .width(width)
        .animate({
            top: coords.top + yoffset - $('#caption').height(),
            left: coords.left            
        }, 0, function(){
            $(this).animate({
                opacity: 'show'
            }, 200);   
        });
});

$('img').mouseout(function(){
    $('#caption').animate({
        opacity: 'hide'
    }, 100);   
});

The CSS for that div: Absolutely positioned so you can place it anywhere, make sure it's not nested inside another div to make sure this works the way it should.

#caption {
    position: absolute;
    z-index: 99;
    display: none;
    background: rgba(0,0,0,0.6);
    color: white;
    padding: 2px;  
}

As for whether you use the title or alt attributes, you could and use .attr instead of .data, but this way you can specify the caption text without hurting anything. HTML5 data attributes are used as follows with jQuery

<img src='#' data-caption='This is some caption text' />

and then accessed like so:

$('img').data('caption'); //returns our caption text