Search code examples
javascriptjquerycssfadeinopacity

Change opacity of random image (toggle)


I have looked for an answer for about 2 hours without any success: How do you make an animation that change the opacity of images in a grid randomly with a slow fadein ?


Solution

  • It's not the most elegant code since I did it in like 5 minutes, but you may be able to get the idea and improve it:

    jQuery

    $(function(){
    setInterval(function(){
        var i = Math.floor(Math.random() * 10) + 1;
    
        $("[data-highlight=1]").attr("data-highlight", "0").animate({
            opacity: 0.2
        }, 1000);
    
        $("#photo-" + i).attr("data-highlight", "1").animate({
            opacity: 1
        }, 1000);
    }, 3000);
    });
    

    CSS

    .photo {
        width: 150px;
        height: 150px;
        background-color: #F00;
        font-size: 2em;
        color: #FFF;
        float: left;
        opacity: 0.2;
    }
    

    HTML

    <div class="photo" id="photo-1" data-highlight="0">DIV</div>
    <div class="photo" id="photo-2" data-highlight="0">DIV</div>
    <div class="photo" id="photo-3" data-highlight="0">DIV</div>
    <div class="photo" id="photo-4" data-highlight="0">DIV</div>
    <div class="photo" id="photo-5" data-highlight="0">DIV</div>
    <div class="photo" id="photo-6" data-highlight="0">DIV</div>
    <div class="photo" id="photo-7" data-highlight="0">DIV</div>
    <div class="photo" id="photo-8" data-highlight="0">DIV</div>
    <div class="photo" id="photo-9" data-highlight="0">DIV</div>
    <div class="photo" id="photo-10" data-highlight="0">DIV</div>
    

    Here is a demo: https://jsfiddle.net/ymu3ghgk/