Ryan
Ryan

Reputation: 2234

Display div IF image has ALT attribute

I have this caption function that worlds great. If I fill in the alt attribute it creates a caption, and the data attribute as a link for the caption. Works great.

Issue is if I don't have anything in the alt or data attribute, a div still appears. This is an issue, because as you can see in my CSS, the link has a background with padding, so with no data or alt attribute, a blank div appears with a black background.

I want to be able to change my function to say IF image has alt, display is along with the data info to create the caption, else, display the entire .caption to none.

I can't figure out to have jQuery check to see if there is the alt. I want the ALT attribute to control whether or not the alt and data info show.

Here is what I have currently:

Jquery:

function imageCaption() {
    var $image =$('img');

    $image.wrap('<div class="box"></div>');

    $image.each(function() {
        var caption = this.alt;
        var link = $(this).attr('data');
        $(this).after('<div class="caption"><a href="'+ link +'" target="blank">'+ caption +'</a></div>');
    });
}

HTML:

<img src="IMAGE URL" alt="This is my first image" data="http://www.google.com">
<img src="IMAGE URL">

^^ The second image has the caption box rendered, with a blank link with padding.

CSS:

    #photoWrapper .caption {
    position: absolute;
    bottom: 10px;
    right: 5px;
    text-transform: uppercase;
    font-size: 10px;
}

#photoWrapper .caption a {
    text-decoration: none;
    color: #F1F1F1;
    padding: 5px 10px 5px 10px;
    background: rgba(0,0,0,0.7);
}

#photoWrapper .caption a:hover {
    background: rgba(0,0,0,0.9);
    color: #ff6666;
}

So to wrap it up, just looking to change my function with an IF statement that looks to see if the image has an alt attribute, and if so, show caption with link and text, and if not, hide caption.

Thanks!

Upvotes: 4

Views: 3902

Answers (1)

lucuma
lucuma

Reputation: 18339

$image.each(function() {
   if($(this).attr("alt")) {
       // The image has an attribute do your thing
        var caption = this.alt;
        var link = $(this).attr('data');
        $(this).after('<div class="caption"><a href="'+ link +'" target="blank">'+ caption +'</a></div>');

    }     
});

There is a similar question here: jQuery hasAttr checking to see if there is an attribute on an element

That suggests an alternate way to make the check however I'm not sure the longer code is required.

var attr = $(this).attr('name');

// For some browsers, `attr` is undefined; for others,
// `attr` is false.  Check for both.
if (typeof attr !== 'undefined' && attr !== false) {
    // ...
}

Upvotes: 3

Related Questions