Search code examples
javascriptcssbackground-imageonerror

CSS or Javascript - display fallback text if background image not loaded


How can I display text instead of logo, if the logo graphic file isn't loaded or missing? I have div with background PNG image:

<div class="iHaveBgImage">
this text should be displayed if bg image is not loaded
</div>

.iHaveBgImage { background-image: url('img.png') }

It doesn't have to be pure CSS, Javascript solution is allowed. I was thinking of onerror event, but it works with images, not elements that have image backgrounds.

EDIT: I was told this has been answered before, but there is another situation. I didn't say one can alter DOM, only apply CSS and JS. Second, in that other solution is sugested I should use title attribute and I tried it and it doesn't display text, only hovers it.


Solution

  • Try it this way:

    HTML

    <div class="iHaveBgImage">
      <p>this text should be displayed if bg image is not loaded</p>
    </div>
    

    CSS

    .iHaveBgImage { background-image:
    url('https://s31.postimg.org/yqv51r5xn/6936671_hd_wallpapers_for_ipad.jpg');
    color:red;
    }
    
    .iHaveBgImage > p {
      position: relative;
      z-index: -1;
    }
    

    Works perfectly https://jsfiddle.net/s0gt2eng/