Search code examples
javascriptjqueryhtmlcssfade

Add/Remove Class Fade Not Working


I'm new to development so please go easy on me :)

I've started to create a body background slider on my eCommerce platform which I hope will eventually be able to toggle through a selection of body background images (not made it that far yet).

I've managed to create a page that toggles body background images with "Previous" and "Next" buttons by removing and adding classes but the crossfading doesn't work, please see below:

https://zoeyplayground-com.zoeysite.com/lookbook

Here is my code:

HTML

<script>
    jQuery(document).ready(function() {
        jQuery(".next").click(function() {
            jQuery("body").removeClass("bodybackground1").fadeOut('slow');
            jQuery("body").addClass("bodybackground2").fadeIn('slow');
        });
    });
</script>

<script>
    jQuery(document).ready(function() {
        jQuery(".back").click(function() {
            jQuery("body").removeClass("bodybackground2").fadeOut('slow');
            jQuery("body").addClass("bodybackground1").fadeIn('slow');
        });
    });
</script>

<div id="toggle" width="100%">
<img src="/media/import/back.png" class="back">
<img src="/media/import/next.png" class="next">
</div>

CSS

.bodybackground1 { 
    background: url('/media/import/background1.jpg') no-repeat center center fixed;
    background-size: cover;
    overflow: hidden;
    transition: all 0.5s;
}

.bodybackground2 {
    background: url('/media/import/background2.jpg') no-repeat center center fixed;
    background-size: cover;
    overflow: hidden;
    transition: all 0.5s;
}

#toggle img {
    margin-top: 400px;
    display: inline;
}

#toggle .next {
    float: right;
}

#toggle img:hover {
    cursor: pointer;
    opacity: 0.8;
}

Would anybody be able to please explain why the fade isn't working? Any guidance or advice is appreciated. Thank you very much.


Solution

  • You are almost there. transition: all 0.5s; on your .bodybackground* classes should take care of the fade effect. There is just 1 problem, your transition property is being overwritten by this #pix-fe code.

    #pix-fe {
    ...
    transition: opacity .2s ease;
    ...
    }
    

    You should check on it. A quick fix would be to do the following in your css:

    #pix-fe.bodybackground1 { 
        background: url('/media/import/background1.jpg') no-repeat center center fixed;
        background-size: cover;
        overflow: hidden;
        transition: all 0.5s;
    }
    
    #pix-fe.bodybackground2 {
        background: url('/media/import/background2.jpg') no-repeat center center fixed;
        background-size: cover;
        overflow: hidden;
        transition: all 0.5s;
    }