How do I use JQuery to delay an animation until the background image has loaded?












-1















I have an animation that fades in after around 1 second of the user clicking on the webpage. However, as the text that fades in is white, it requires the background image to be loaded already before this happens.



Given that some of my users may have a slow internet connection, I want to delay the animation until the background image has loaded?



Do you have any recommendations on how to do this?



I was thinking that it might be possible to create a JQuery script that only creates the animation class using the Document Ready function.



However, I have no knowledge in this, as my use of Javascript so far is very limited beyond online tutorials.



Could somebody please provide a quick JSfiddle as to how to only start the animation once the image loads?










share|improve this question























  • I would look into the imagesLoaded javascript plugin. It does have a section for background images

    – zgood
    May 15 '17 at 20:04


















-1















I have an animation that fades in after around 1 second of the user clicking on the webpage. However, as the text that fades in is white, it requires the background image to be loaded already before this happens.



Given that some of my users may have a slow internet connection, I want to delay the animation until the background image has loaded?



Do you have any recommendations on how to do this?



I was thinking that it might be possible to create a JQuery script that only creates the animation class using the Document Ready function.



However, I have no knowledge in this, as my use of Javascript so far is very limited beyond online tutorials.



Could somebody please provide a quick JSfiddle as to how to only start the animation once the image loads?










share|improve this question























  • I would look into the imagesLoaded javascript plugin. It does have a section for background images

    – zgood
    May 15 '17 at 20:04
















-1












-1








-1








I have an animation that fades in after around 1 second of the user clicking on the webpage. However, as the text that fades in is white, it requires the background image to be loaded already before this happens.



Given that some of my users may have a slow internet connection, I want to delay the animation until the background image has loaded?



Do you have any recommendations on how to do this?



I was thinking that it might be possible to create a JQuery script that only creates the animation class using the Document Ready function.



However, I have no knowledge in this, as my use of Javascript so far is very limited beyond online tutorials.



Could somebody please provide a quick JSfiddle as to how to only start the animation once the image loads?










share|improve this question














I have an animation that fades in after around 1 second of the user clicking on the webpage. However, as the text that fades in is white, it requires the background image to be loaded already before this happens.



Given that some of my users may have a slow internet connection, I want to delay the animation until the background image has loaded?



Do you have any recommendations on how to do this?



I was thinking that it might be possible to create a JQuery script that only creates the animation class using the Document Ready function.



However, I have no knowledge in this, as my use of Javascript so far is very limited beyond online tutorials.



Could somebody please provide a quick JSfiddle as to how to only start the animation once the image loads?







javascript jquery html css animation






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 15 '17 at 20:00









Anon1231123Anon1231123

82




82













  • I would look into the imagesLoaded javascript plugin. It does have a section for background images

    – zgood
    May 15 '17 at 20:04





















  • I would look into the imagesLoaded javascript plugin. It does have a section for background images

    – zgood
    May 15 '17 at 20:04



















I would look into the imagesLoaded javascript plugin. It does have a section for background images

– zgood
May 15 '17 at 20:04







I would look into the imagesLoaded javascript plugin. It does have a section for background images

– zgood
May 15 '17 at 20:04














4 Answers
4






active

oldest

votes


















1














If anyone is looking for a vanilla JavaScript solution for this problem, you can:




  1. Pause your CSS animation.

  2. Wait for the document to load (includes background images).

  3. Start your CSS animation.


For example:



CSS



.element {
animation-play-state: paused;
}


JS



function startAnimation() { 
document.querySelector('.element').style.animationPlayState = 'running';
}
window.addEventListener('load', startAnimation);





share|improve this answer































    0














    Shure, simply wait for the image to load, then add the click handler:



     $('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {//wait for the page load
    $(this).remove(); // prevent memory leaks as @benweet suggested

    $('body').css('background-image', 'url(http://picture.de/image.png)');//assign the bg image, bg is now ready:
    $(window).on("click",alert);//assign the eventlistener
    });


    Major part taken from How can I check if a background image is loaded?






    share|improve this answer

































      0














      The general concept here would be to create an image in js, add an onload function, then set the src of the image to whatever the image is that you want to load first. Then put whatever your animation does inside of the onload function.






      var img = new Image();
      img.onload = function() {
      document.getElementById('div').classList.add('fadein');
      }
      img.src = "http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg";

      div {
      height: 100vh;
      background-image: url('http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg');
      background-size: cover;
      opacity: 0;
      transition: opacity .5s;
      }

      .fadein {
      opacity: 1;
      }

      <div id="div"></div>








      share|improve this answer































        0

















        var image = new Image();
        image.onload = function() {
        $('body').append('<img class="bg-img" src="' + image.src + '" </img>');
        $('.bg-img').fadeTo(1000, 1);
        }

        image.onerror = function() {
        console.error("Sorry! Cannot load image");
        }
        image.src = "http://placehold.it/800x500";

        .bg-img{
        width: 100vw;
        height: auto;
        opacity: 0;
        }

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>








        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%2f43987829%2fhow-do-i-use-jquery-to-delay-an-animation-until-the-background-image-has-loaded%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          If anyone is looking for a vanilla JavaScript solution for this problem, you can:




          1. Pause your CSS animation.

          2. Wait for the document to load (includes background images).

          3. Start your CSS animation.


          For example:



          CSS



          .element {
          animation-play-state: paused;
          }


          JS



          function startAnimation() { 
          document.querySelector('.element').style.animationPlayState = 'running';
          }
          window.addEventListener('load', startAnimation);





          share|improve this answer




























            1














            If anyone is looking for a vanilla JavaScript solution for this problem, you can:




            1. Pause your CSS animation.

            2. Wait for the document to load (includes background images).

            3. Start your CSS animation.


            For example:



            CSS



            .element {
            animation-play-state: paused;
            }


            JS



            function startAnimation() { 
            document.querySelector('.element').style.animationPlayState = 'running';
            }
            window.addEventListener('load', startAnimation);





            share|improve this answer


























              1












              1








              1







              If anyone is looking for a vanilla JavaScript solution for this problem, you can:




              1. Pause your CSS animation.

              2. Wait for the document to load (includes background images).

              3. Start your CSS animation.


              For example:



              CSS



              .element {
              animation-play-state: paused;
              }


              JS



              function startAnimation() { 
              document.querySelector('.element').style.animationPlayState = 'running';
              }
              window.addEventListener('load', startAnimation);





              share|improve this answer













              If anyone is looking for a vanilla JavaScript solution for this problem, you can:




              1. Pause your CSS animation.

              2. Wait for the document to load (includes background images).

              3. Start your CSS animation.


              For example:



              CSS



              .element {
              animation-play-state: paused;
              }


              JS



              function startAnimation() { 
              document.querySelector('.element').style.animationPlayState = 'running';
              }
              window.addEventListener('load', startAnimation);






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 31 '18 at 18:47









              jsrathjsrath

              111




              111

























                  0














                  Shure, simply wait for the image to load, then add the click handler:



                   $('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {//wait for the page load
                  $(this).remove(); // prevent memory leaks as @benweet suggested

                  $('body').css('background-image', 'url(http://picture.de/image.png)');//assign the bg image, bg is now ready:
                  $(window).on("click",alert);//assign the eventlistener
                  });


                  Major part taken from How can I check if a background image is loaded?






                  share|improve this answer






























                    0














                    Shure, simply wait for the image to load, then add the click handler:



                     $('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {//wait for the page load
                    $(this).remove(); // prevent memory leaks as @benweet suggested

                    $('body').css('background-image', 'url(http://picture.de/image.png)');//assign the bg image, bg is now ready:
                    $(window).on("click",alert);//assign the eventlistener
                    });


                    Major part taken from How can I check if a background image is loaded?






                    share|improve this answer




























                      0












                      0








                      0







                      Shure, simply wait for the image to load, then add the click handler:



                       $('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {//wait for the page load
                      $(this).remove(); // prevent memory leaks as @benweet suggested

                      $('body').css('background-image', 'url(http://picture.de/image.png)');//assign the bg image, bg is now ready:
                      $(window).on("click",alert);//assign the eventlistener
                      });


                      Major part taken from How can I check if a background image is loaded?






                      share|improve this answer















                      Shure, simply wait for the image to load, then add the click handler:



                       $('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {//wait for the page load
                      $(this).remove(); // prevent memory leaks as @benweet suggested

                      $('body').css('background-image', 'url(http://picture.de/image.png)');//assign the bg image, bg is now ready:
                      $(window).on("click",alert);//assign the eventlistener
                      });


                      Major part taken from How can I check if a background image is loaded?







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited May 23 '17 at 12:34









                      Community

                      11




                      11










                      answered May 15 '17 at 20:05









                      Jonas WilmsJonas Wilms

                      58k43051




                      58k43051























                          0














                          The general concept here would be to create an image in js, add an onload function, then set the src of the image to whatever the image is that you want to load first. Then put whatever your animation does inside of the onload function.






                          var img = new Image();
                          img.onload = function() {
                          document.getElementById('div').classList.add('fadein');
                          }
                          img.src = "http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg";

                          div {
                          height: 100vh;
                          background-image: url('http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg');
                          background-size: cover;
                          opacity: 0;
                          transition: opacity .5s;
                          }

                          .fadein {
                          opacity: 1;
                          }

                          <div id="div"></div>








                          share|improve this answer




























                            0














                            The general concept here would be to create an image in js, add an onload function, then set the src of the image to whatever the image is that you want to load first. Then put whatever your animation does inside of the onload function.






                            var img = new Image();
                            img.onload = function() {
                            document.getElementById('div').classList.add('fadein');
                            }
                            img.src = "http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg";

                            div {
                            height: 100vh;
                            background-image: url('http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg');
                            background-size: cover;
                            opacity: 0;
                            transition: opacity .5s;
                            }

                            .fadein {
                            opacity: 1;
                            }

                            <div id="div"></div>








                            share|improve this answer


























                              0












                              0








                              0







                              The general concept here would be to create an image in js, add an onload function, then set the src of the image to whatever the image is that you want to load first. Then put whatever your animation does inside of the onload function.






                              var img = new Image();
                              img.onload = function() {
                              document.getElementById('div').classList.add('fadein');
                              }
                              img.src = "http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg";

                              div {
                              height: 100vh;
                              background-image: url('http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg');
                              background-size: cover;
                              opacity: 0;
                              transition: opacity .5s;
                              }

                              .fadein {
                              opacity: 1;
                              }

                              <div id="div"></div>








                              share|improve this answer













                              The general concept here would be to create an image in js, add an onload function, then set the src of the image to whatever the image is that you want to load first. Then put whatever your animation does inside of the onload function.






                              var img = new Image();
                              img.onload = function() {
                              document.getElementById('div').classList.add('fadein');
                              }
                              img.src = "http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg";

                              div {
                              height: 100vh;
                              background-image: url('http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg');
                              background-size: cover;
                              opacity: 0;
                              transition: opacity .5s;
                              }

                              .fadein {
                              opacity: 1;
                              }

                              <div id="div"></div>








                              var img = new Image();
                              img.onload = function() {
                              document.getElementById('div').classList.add('fadein');
                              }
                              img.src = "http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg";

                              div {
                              height: 100vh;
                              background-image: url('http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg');
                              background-size: cover;
                              opacity: 0;
                              transition: opacity .5s;
                              }

                              .fadein {
                              opacity: 1;
                              }

                              <div id="div"></div>





                              var img = new Image();
                              img.onload = function() {
                              document.getElementById('div').classList.add('fadein');
                              }
                              img.src = "http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg";

                              div {
                              height: 100vh;
                              background-image: url('http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg');
                              background-size: cover;
                              opacity: 0;
                              transition: opacity .5s;
                              }

                              .fadein {
                              opacity: 1;
                              }

                              <div id="div"></div>






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered May 15 '17 at 20:08









                              Michael CokerMichael Coker

                              42.9k52636




                              42.9k52636























                                  0

















                                  var image = new Image();
                                  image.onload = function() {
                                  $('body').append('<img class="bg-img" src="' + image.src + '" </img>');
                                  $('.bg-img').fadeTo(1000, 1);
                                  }

                                  image.onerror = function() {
                                  console.error("Sorry! Cannot load image");
                                  }
                                  image.src = "http://placehold.it/800x500";

                                  .bg-img{
                                  width: 100vw;
                                  height: auto;
                                  opacity: 0;
                                  }

                                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>








                                  share|improve this answer






























                                    0

















                                    var image = new Image();
                                    image.onload = function() {
                                    $('body').append('<img class="bg-img" src="' + image.src + '" </img>');
                                    $('.bg-img').fadeTo(1000, 1);
                                    }

                                    image.onerror = function() {
                                    console.error("Sorry! Cannot load image");
                                    }
                                    image.src = "http://placehold.it/800x500";

                                    .bg-img{
                                    width: 100vw;
                                    height: auto;
                                    opacity: 0;
                                    }

                                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>








                                    share|improve this answer




























                                      0












                                      0








                                      0










                                      var image = new Image();
                                      image.onload = function() {
                                      $('body').append('<img class="bg-img" src="' + image.src + '" </img>');
                                      $('.bg-img').fadeTo(1000, 1);
                                      }

                                      image.onerror = function() {
                                      console.error("Sorry! Cannot load image");
                                      }
                                      image.src = "http://placehold.it/800x500";

                                      .bg-img{
                                      width: 100vw;
                                      height: auto;
                                      opacity: 0;
                                      }

                                      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>








                                      share|improve this answer


















                                      var image = new Image();
                                      image.onload = function() {
                                      $('body').append('<img class="bg-img" src="' + image.src + '" </img>');
                                      $('.bg-img').fadeTo(1000, 1);
                                      }

                                      image.onerror = function() {
                                      console.error("Sorry! Cannot load image");
                                      }
                                      image.src = "http://placehold.it/800x500";

                                      .bg-img{
                                      width: 100vw;
                                      height: auto;
                                      opacity: 0;
                                      }

                                      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>








                                      var image = new Image();
                                      image.onload = function() {
                                      $('body').append('<img class="bg-img" src="' + image.src + '" </img>');
                                      $('.bg-img').fadeTo(1000, 1);
                                      }

                                      image.onerror = function() {
                                      console.error("Sorry! Cannot load image");
                                      }
                                      image.src = "http://placehold.it/800x500";

                                      .bg-img{
                                      width: 100vw;
                                      height: auto;
                                      opacity: 0;
                                      }

                                      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





                                      var image = new Image();
                                      image.onload = function() {
                                      $('body').append('<img class="bg-img" src="' + image.src + '" </img>');
                                      $('.bg-img').fadeTo(1000, 1);
                                      }

                                      image.onerror = function() {
                                      console.error("Sorry! Cannot load image");
                                      }
                                      image.src = "http://placehold.it/800x500";

                                      .bg-img{
                                      width: 100vw;
                                      height: auto;
                                      opacity: 0;
                                      }

                                      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited May 15 '17 at 20:20

























                                      answered May 15 '17 at 20:11









                                      Daniel HDaniel H

                                      8,60241234




                                      8,60241234






























                                          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.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43987829%2fhow-do-i-use-jquery-to-delay-an-animation-until-the-background-image-has-loaded%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

                                          Monofisismo

                                          Angular Downloading a file using contenturl with Basic Authentication

                                          Olmecas