Home > database >  How to stop jQuery from fading on nested div's?
How to stop jQuery from fading on nested div's?

Time:09-16

var images = ["https://dummyimage.com/600x400/c4c4c4/0011ff.jpg&text=Image 1", "https://dummyimage.com/600x400/c4c4c4/ff0000.jpg&text=Image 2", "https://dummyimage.com/600x400/c4c4c4/fffb00.jpg&text=Image 3"];
$(function () {
    var i = 0;
    $("#dvImage").css("background-image", "url("   images[i]   ")");
    setInterval(function () {
        i  ;
        if (i == images.length) {
            i = 0;
        }
        $("#dvImage").fadeOut("slow", function () {
            $(this).css("background-image", "url("   images[i]   ")");
            $(this).fadeIn("slow");
        });
    }, 2000);
});
p {padding: 75px 15px 15px 15px;text-align: center;}
#dvImage {background-size:cover;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dvImage" style="width: 600px;height: 400px;">
  <div id="text">
    <p>How do I get this text to stop fading?</p>
  </div>
</div>

I'm trying to create a background image rotator, that changes images and fades between each image. I've almost got it, but on the site that I'm using it, has a nested image and text, which is also fading. I only want it to fade the background images and not any of the nested div's.

I created an example here with a nested div (and paragraph tag with text).

https://jsfiddle.net/bobthegoat2001/3hrgua82/6/

Does anyone know how I could fix this? Any help would be great. Thanks!

<p style="display:none">I guess Stack Overflow wanted some code, so I just put some random here. The jsfiddle will make more since.</p>

CodePudding user response:

You can use position absolute and then set z-index to -1 but you need to move nested div's out of your div #dvImage

var images = ["https://dummyimage.com/600x400/c4c4c4/0011ff.jpg&text=Image 1", "https://dummyimage.com/600x400/c4c4c4/ff0000.jpg&text=Image 2", "https://dummyimage.com/600x400/c4c4c4/fffb00.jpg&text=Image 3"];
$(function () {
    var i = 0;
    $("#dvImage").css("background-image", "url("   images[i]   ")");
    setInterval(function () {
        i  ;
        if (i == images.length) {
            i = 0;
        }
        $("#dvImage").fadeOut("slow", function () {
            $(this).css("background-image", "url("   images[i]   ")");
            $(this).fadeIn("slow");
        });
    }, 2000);
});
p {padding: 75px 15px 15px 15px;text-align: center;}
#dvImage {position:absolute; z-index:-1;width:600px; height:400px; background-size:cover;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dvImage"></div>
<div id="text">
  <p>How do I get this text to stop fading?</p>
</div>

  • Related