Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide image when the src is unknown

I'm trying to hide images without the src in WordPress.

Following is the image code displaying on the front end

<img src="[custom-gallery-image-01]" class="galimage" height="300" width="580"/>

JS used to hide the image

<script type="text/javascript">
$(document).ready(function() {
   $(".galimage").each(function() {
        var atr = $(this).attr("src"); 
        if(atr == "") {
            $(this).addClass("hidegalimage");
        } else {
            $(this).removeClass("hidegalimage");
        }
    });
});
</script>

CSS

.hidegalimage {
display:none;
}

But I can still see the broken image icon & an image border. View JSFiddle. Can someone fix my issue or give me a suggestion how to hide the image?

Many thanks

like image 999
Anna Wellington Avatar asked Jan 02 '23 09:01

Anna Wellington


1 Answers

Much more elegant to use CSS instead, no Javascript required, assuming the bad srcs start with [ as in your HTML: are empty strings:

.galimage[src=""] {
  display:none;
}
<img src="https://www.gravatar.com/avatar/b3559198b8028bd3d8e82c00d16d2e10?s=32&d=identicon&r=PG&f=1" class="galimage" height="300" width="580"/>
<img src="" class="galimage" height="300" width="580"/>
<img src="https://www.gravatar.com/avatar/b3559198b8028bd3d8e82c00d16d2e10?s=32&d=identicon&r=PG&f=1" class="galimage" height="300" width="580"/>
like image 67
CertainPerformance Avatar answered Jan 11 '23 23:01

CertainPerformance