JS changing source image with animation












1














I have a problem with looped fade-in/fade-out image source changing in JS and CSS and using SetTimeout() callback.
The problem is, that the sequence is working strange: sometimes the image changes before the transition starts, sometimes it works fine, and sometimes in the other way.



Here is my JS:



const animationTime = 5000;
const transitionTime = 500;

function nextImage() {

let img = document.getElementById('img1');
img.classList.remove('hidden');
setTimeout(function () {
img.classList.add('hidden');
},animationTime-transitionTime);
img.src=randomize();
setTimeout(nextImage, animationTime);
}




  • randomize() function just gets a random image path from array.


Here is HTML:



<div class="some-class">
<img class="some-image" id="img1" src="1.png">
</div>


And here is CSS:



.some-image {

transition: opacity 0.5s linear;
-webkit-transition: opacity 0.5s linear;
-o-transition: opacity 0.5s linear;
-moz-transition: opacity 0.5s linear;
-moz-border-radius: 15px;
}

.hidden {
opacity: 0;
}


Upd.
So I have edited CSS file:



.some-image {
width: 370px;
height: 190px;
animation: fade-out;
animation-duration: 1s;
}

.hidden {
animation: fade-out;
animation-duration: 1s;
}

@keyframes fade-in {
from {opacity: 0;}
to {opacity: 1;}
}

@keyframes fade-out {
from {opacity: 1}
to {opacity: 0}
}


And JS-file:



function nextImage() {

let img = document.getElementById('img1');
img.classList.remove('hidden');
setTimeout(function () {
img.classList.add('hidden');
},animationTime-1000);
img.src=randomize();

}
setTimeout(nextImage, animationTime);
}


And, somehow, it works perfectly on a local machine, but on a dedicated website animation sometimes fades-in before the image source changed.










share|improve this question
























  • Can you provide working fiddle which expose problem? jsfiddle.net
    – Kamil Kiełczewski
    Nov 20 '18 at 9:27


















1














I have a problem with looped fade-in/fade-out image source changing in JS and CSS and using SetTimeout() callback.
The problem is, that the sequence is working strange: sometimes the image changes before the transition starts, sometimes it works fine, and sometimes in the other way.



Here is my JS:



const animationTime = 5000;
const transitionTime = 500;

function nextImage() {

let img = document.getElementById('img1');
img.classList.remove('hidden');
setTimeout(function () {
img.classList.add('hidden');
},animationTime-transitionTime);
img.src=randomize();
setTimeout(nextImage, animationTime);
}




  • randomize() function just gets a random image path from array.


Here is HTML:



<div class="some-class">
<img class="some-image" id="img1" src="1.png">
</div>


And here is CSS:



.some-image {

transition: opacity 0.5s linear;
-webkit-transition: opacity 0.5s linear;
-o-transition: opacity 0.5s linear;
-moz-transition: opacity 0.5s linear;
-moz-border-radius: 15px;
}

.hidden {
opacity: 0;
}


Upd.
So I have edited CSS file:



.some-image {
width: 370px;
height: 190px;
animation: fade-out;
animation-duration: 1s;
}

.hidden {
animation: fade-out;
animation-duration: 1s;
}

@keyframes fade-in {
from {opacity: 0;}
to {opacity: 1;}
}

@keyframes fade-out {
from {opacity: 1}
to {opacity: 0}
}


And JS-file:



function nextImage() {

let img = document.getElementById('img1');
img.classList.remove('hidden');
setTimeout(function () {
img.classList.add('hidden');
},animationTime-1000);
img.src=randomize();

}
setTimeout(nextImage, animationTime);
}


And, somehow, it works perfectly on a local machine, but on a dedicated website animation sometimes fades-in before the image source changed.










share|improve this question
























  • Can you provide working fiddle which expose problem? jsfiddle.net
    – Kamil Kiełczewski
    Nov 20 '18 at 9:27
















1












1








1







I have a problem with looped fade-in/fade-out image source changing in JS and CSS and using SetTimeout() callback.
The problem is, that the sequence is working strange: sometimes the image changes before the transition starts, sometimes it works fine, and sometimes in the other way.



Here is my JS:



const animationTime = 5000;
const transitionTime = 500;

function nextImage() {

let img = document.getElementById('img1');
img.classList.remove('hidden');
setTimeout(function () {
img.classList.add('hidden');
},animationTime-transitionTime);
img.src=randomize();
setTimeout(nextImage, animationTime);
}




  • randomize() function just gets a random image path from array.


Here is HTML:



<div class="some-class">
<img class="some-image" id="img1" src="1.png">
</div>


And here is CSS:



.some-image {

transition: opacity 0.5s linear;
-webkit-transition: opacity 0.5s linear;
-o-transition: opacity 0.5s linear;
-moz-transition: opacity 0.5s linear;
-moz-border-radius: 15px;
}

.hidden {
opacity: 0;
}


Upd.
So I have edited CSS file:



.some-image {
width: 370px;
height: 190px;
animation: fade-out;
animation-duration: 1s;
}

.hidden {
animation: fade-out;
animation-duration: 1s;
}

@keyframes fade-in {
from {opacity: 0;}
to {opacity: 1;}
}

@keyframes fade-out {
from {opacity: 1}
to {opacity: 0}
}


And JS-file:



function nextImage() {

let img = document.getElementById('img1');
img.classList.remove('hidden');
setTimeout(function () {
img.classList.add('hidden');
},animationTime-1000);
img.src=randomize();

}
setTimeout(nextImage, animationTime);
}


And, somehow, it works perfectly on a local machine, but on a dedicated website animation sometimes fades-in before the image source changed.










share|improve this question















I have a problem with looped fade-in/fade-out image source changing in JS and CSS and using SetTimeout() callback.
The problem is, that the sequence is working strange: sometimes the image changes before the transition starts, sometimes it works fine, and sometimes in the other way.



Here is my JS:



const animationTime = 5000;
const transitionTime = 500;

function nextImage() {

let img = document.getElementById('img1');
img.classList.remove('hidden');
setTimeout(function () {
img.classList.add('hidden');
},animationTime-transitionTime);
img.src=randomize();
setTimeout(nextImage, animationTime);
}




  • randomize() function just gets a random image path from array.


Here is HTML:



<div class="some-class">
<img class="some-image" id="img1" src="1.png">
</div>


And here is CSS:



.some-image {

transition: opacity 0.5s linear;
-webkit-transition: opacity 0.5s linear;
-o-transition: opacity 0.5s linear;
-moz-transition: opacity 0.5s linear;
-moz-border-radius: 15px;
}

.hidden {
opacity: 0;
}


Upd.
So I have edited CSS file:



.some-image {
width: 370px;
height: 190px;
animation: fade-out;
animation-duration: 1s;
}

.hidden {
animation: fade-out;
animation-duration: 1s;
}

@keyframes fade-in {
from {opacity: 0;}
to {opacity: 1;}
}

@keyframes fade-out {
from {opacity: 1}
to {opacity: 0}
}


And JS-file:



function nextImage() {

let img = document.getElementById('img1');
img.classList.remove('hidden');
setTimeout(function () {
img.classList.add('hidden');
},animationTime-1000);
img.src=randomize();

}
setTimeout(nextImage, animationTime);
}


And, somehow, it works perfectly on a local machine, but on a dedicated website animation sometimes fades-in before the image source changed.







javascript html css css-transitions settimeout






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 10:44

























asked Nov 20 '18 at 9:24









Dzybaty

133




133












  • Can you provide working fiddle which expose problem? jsfiddle.net
    – Kamil Kiełczewski
    Nov 20 '18 at 9:27




















  • Can you provide working fiddle which expose problem? jsfiddle.net
    – Kamil Kiełczewski
    Nov 20 '18 at 9:27


















Can you provide working fiddle which expose problem? jsfiddle.net
– Kamil Kiełczewski
Nov 20 '18 at 9:27






Can you provide working fiddle which expose problem? jsfiddle.net
– Kamil Kiełczewski
Nov 20 '18 at 9:27














2 Answers
2






active

oldest

votes


















1














You should try using css animations instead. You can easily implement the above with it, and it will save you the trouble of handling animations in your code.






share|improve this answer





















  • I have updated the topic. Still works strange.
    – Dzybaty
    Nov 20 '18 at 10:03





















0














I think the problem is about timing. The setTimeout function didn't guarantee to execute exactly time as argument set. So there is a possibility that you change the src of image before/after it add/remove hidden class. These delay is rarely happens that might be the reason why it works on your machine.



So this problem can solve by every time you change the image you must have to make sure the image is completely hide.



const nextImage = function () {
let img = document.querySelector('img')

img.classList.add('hidden')

setTimeout(() => {
img.style.visibility = 'hidden'
img.src = randomImage()

// skip to next frame, may be this not necessary to use setTimeout
setTimeout(() => {
img.style.visibility = ''
img.classList.remove('hidden')
}, 10)
}, animationDuration)

setTimeout(nextImage, intervalDuration + animationDuration)
}


The new cycle will be: fade image out, wait for animation then change image (with set visibility to hidden) and then fade in. And loop.



With this approach. If setTimeout is early execute before the image has completely fade out the visibility will be set hidden. If it's delayed, the image will be hide a bit longer.



Live example here. In that code I add a little bit noise with random time to test.



Unfortunately, After I spent an hour to see my answer is right I still feel it's not perfect anyway and it will be worse if you image is large. I would recommend you try two or more img tags instead.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389833%2fjs-changing-source-image-with-animation%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You should try using css animations instead. You can easily implement the above with it, and it will save you the trouble of handling animations in your code.






    share|improve this answer





















    • I have updated the topic. Still works strange.
      – Dzybaty
      Nov 20 '18 at 10:03


















    1














    You should try using css animations instead. You can easily implement the above with it, and it will save you the trouble of handling animations in your code.






    share|improve this answer





















    • I have updated the topic. Still works strange.
      – Dzybaty
      Nov 20 '18 at 10:03
















    1












    1








    1






    You should try using css animations instead. You can easily implement the above with it, and it will save you the trouble of handling animations in your code.






    share|improve this answer












    You should try using css animations instead. You can easily implement the above with it, and it will save you the trouble of handling animations in your code.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 20 '18 at 9:30









    Gilad Bar

    633314




    633314












    • I have updated the topic. Still works strange.
      – Dzybaty
      Nov 20 '18 at 10:03




















    • I have updated the topic. Still works strange.
      – Dzybaty
      Nov 20 '18 at 10:03


















    I have updated the topic. Still works strange.
    – Dzybaty
    Nov 20 '18 at 10:03






    I have updated the topic. Still works strange.
    – Dzybaty
    Nov 20 '18 at 10:03















    0














    I think the problem is about timing. The setTimeout function didn't guarantee to execute exactly time as argument set. So there is a possibility that you change the src of image before/after it add/remove hidden class. These delay is rarely happens that might be the reason why it works on your machine.



    So this problem can solve by every time you change the image you must have to make sure the image is completely hide.



    const nextImage = function () {
    let img = document.querySelector('img')

    img.classList.add('hidden')

    setTimeout(() => {
    img.style.visibility = 'hidden'
    img.src = randomImage()

    // skip to next frame, may be this not necessary to use setTimeout
    setTimeout(() => {
    img.style.visibility = ''
    img.classList.remove('hidden')
    }, 10)
    }, animationDuration)

    setTimeout(nextImage, intervalDuration + animationDuration)
    }


    The new cycle will be: fade image out, wait for animation then change image (with set visibility to hidden) and then fade in. And loop.



    With this approach. If setTimeout is early execute before the image has completely fade out the visibility will be set hidden. If it's delayed, the image will be hide a bit longer.



    Live example here. In that code I add a little bit noise with random time to test.



    Unfortunately, After I spent an hour to see my answer is right I still feel it's not perfect anyway and it will be worse if you image is large. I would recommend you try two or more img tags instead.






    share|improve this answer


























      0














      I think the problem is about timing. The setTimeout function didn't guarantee to execute exactly time as argument set. So there is a possibility that you change the src of image before/after it add/remove hidden class. These delay is rarely happens that might be the reason why it works on your machine.



      So this problem can solve by every time you change the image you must have to make sure the image is completely hide.



      const nextImage = function () {
      let img = document.querySelector('img')

      img.classList.add('hidden')

      setTimeout(() => {
      img.style.visibility = 'hidden'
      img.src = randomImage()

      // skip to next frame, may be this not necessary to use setTimeout
      setTimeout(() => {
      img.style.visibility = ''
      img.classList.remove('hidden')
      }, 10)
      }, animationDuration)

      setTimeout(nextImage, intervalDuration + animationDuration)
      }


      The new cycle will be: fade image out, wait for animation then change image (with set visibility to hidden) and then fade in. And loop.



      With this approach. If setTimeout is early execute before the image has completely fade out the visibility will be set hidden. If it's delayed, the image will be hide a bit longer.



      Live example here. In that code I add a little bit noise with random time to test.



      Unfortunately, After I spent an hour to see my answer is right I still feel it's not perfect anyway and it will be worse if you image is large. I would recommend you try two or more img tags instead.






      share|improve this answer
























        0












        0








        0






        I think the problem is about timing. The setTimeout function didn't guarantee to execute exactly time as argument set. So there is a possibility that you change the src of image before/after it add/remove hidden class. These delay is rarely happens that might be the reason why it works on your machine.



        So this problem can solve by every time you change the image you must have to make sure the image is completely hide.



        const nextImage = function () {
        let img = document.querySelector('img')

        img.classList.add('hidden')

        setTimeout(() => {
        img.style.visibility = 'hidden'
        img.src = randomImage()

        // skip to next frame, may be this not necessary to use setTimeout
        setTimeout(() => {
        img.style.visibility = ''
        img.classList.remove('hidden')
        }, 10)
        }, animationDuration)

        setTimeout(nextImage, intervalDuration + animationDuration)
        }


        The new cycle will be: fade image out, wait for animation then change image (with set visibility to hidden) and then fade in. And loop.



        With this approach. If setTimeout is early execute before the image has completely fade out the visibility will be set hidden. If it's delayed, the image will be hide a bit longer.



        Live example here. In that code I add a little bit noise with random time to test.



        Unfortunately, After I spent an hour to see my answer is right I still feel it's not perfect anyway and it will be worse if you image is large. I would recommend you try two or more img tags instead.






        share|improve this answer












        I think the problem is about timing. The setTimeout function didn't guarantee to execute exactly time as argument set. So there is a possibility that you change the src of image before/after it add/remove hidden class. These delay is rarely happens that might be the reason why it works on your machine.



        So this problem can solve by every time you change the image you must have to make sure the image is completely hide.



        const nextImage = function () {
        let img = document.querySelector('img')

        img.classList.add('hidden')

        setTimeout(() => {
        img.style.visibility = 'hidden'
        img.src = randomImage()

        // skip to next frame, may be this not necessary to use setTimeout
        setTimeout(() => {
        img.style.visibility = ''
        img.classList.remove('hidden')
        }, 10)
        }, animationDuration)

        setTimeout(nextImage, intervalDuration + animationDuration)
        }


        The new cycle will be: fade image out, wait for animation then change image (with set visibility to hidden) and then fade in. And loop.



        With this approach. If setTimeout is early execute before the image has completely fade out the visibility will be set hidden. If it's delayed, the image will be hide a bit longer.



        Live example here. In that code I add a little bit noise with random time to test.



        Unfortunately, After I spent an hour to see my answer is right I still feel it's not perfect anyway and it will be worse if you image is large. I would recommend you try two or more img tags instead.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 5:13









        User 28

        669513




        669513






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389833%2fjs-changing-source-image-with-animation%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            If I really need a card on my start hand, how many mulligans make sense? [duplicate]

            Alcedinidae

            Can an atomic nucleus contain both particles and antiparticles? [duplicate]