Hamz4h_ Hamz4h_ - 3 months ago 22
jQuery Question

Lazyload plugin against a background-image div is causing the content contained within the div to flicker when loading the image

I have a small but annoying issue. I'm using the Lazyload plugin for JQuery (Mika Tuupola - here) and I'm having an issue whereby using the fadeIn effect on a div background-image attribute causes the inner content to flicker when the image finally loads. It essentially reloads the content when the image loads. How do I avoid this?

My html extract:

<div class="wrap" id="wrap">
<div class="bg-image" data-original="images/image_1.jpg">
<h1>Some title here</h1>
</div>
<div class="bg-image" data-original="images/image_1.jpg">
<h1>Some other title here</h1>
</div>
<div class="bg-image" data-original="images/image_1.jpg">
<h1>another title here</h1>
</div>
</div>


My JS usage of Lazyload is against the container element because I have the structure above repeated several times (loading the same image):

$("div.bg-image").lazyload({
container: $("#wrap"),
threshold: 200,
effect: "fadeIn"
});


For the most part it works well but the flicker is off putting somewhat. Hopefully that's enough detail, I'll see if I can get a a sample fiddle going (you may have to bear with me on that ...)

Answer

I'm the creator of another lazy load plugin for jQuery. You can't solve the problem this way. The problem is, that, when the outer div fades, the content will always will fade too. There is nothing you can do to prevent this.

A possible solution is to put the background in another div in the back of the content boxes. So it will be visible as background, but it not really is. So there is an extra element for the background, which can be faded alone. Then the content will not fade too.

Here is a quick example of what I mean:

$(".bg").lazy({
  threshold  : 0,
  effect     : "fadeIn",
  effectTime : 500
});
.wrap > div {
  width: 500px;
  height: 250px;
  position: relative;
}
.bg {
  width: 500px;
  height: 250px;
  position: absolute;
  z-index: -1;
}
h1 {
  text-align: center;
  line-height: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.lazy/1.7.3/jquery.lazy.min.js"></script>

<div class="wrap" id="wrap">
  <div>
    <div class="bg" data-src="http://67.media.tumblr.com/tumblr_leicnv2Kv71qeei4to1_500.png"></div>
    <h1>Some title here</h1>
  </div>
  <div>
    <div class="bg" data-src="http://freedesignfile.com/upload/2016/04/Sakura-with-blue-sky-vector-background-07.jpg"></div>
    <h1>Some other title here</h1>
  </div>
  <div>
    <div class="bg" data-src="http://66.media.tumblr.com/300e98d0e86e92d4f7004bc8aff29ecb/tumblr_inline_muxx1wTxbF1s0gyrx.jpg"></div>
    <h1>another title here</h1>
  </div>
</div>