2

I can't find any javascript solution that is simple to integrate to my code. And i don't want to just copy paste i would like to understand.

I have a basic javascript function that changes the images every 3 seconds and i would like to make the images fade when transitioning to make it look a little bit nicer.

JS:

<script type = "text/javascript">
         function nextImage() {
              x = (x === imgArray.length - 1) ? 0 : x + 1;
             document.getElementById("img").src = imgArray[x];
          }

          function begintimer() {
              setInterval(nextImage, 3000);
          }

          var imgArray = [], x = -1;
          imgArray[0] = "images/test.jpg";
          imgArray[1] = "images/bg.jpg";
</script>

HTML:

<body onload = "begintimer()">
    <div id="section1">
        <img id="img" src="images/bg.jpg"/>
    </div>
</body>

Thanks for your help!

Crimson-Med
  • 219
  • 1
  • 4
  • 17
  • 2
    Check out this link: http://stackoverflow.com/questions/6121203/how-to-do-fade-in-and-fade-out-with-javascript-and-css – dane Mar 29 '16 at 18:33
  • 5
    Here's another that may be more relevant: http://stackoverflow.com/questions/23583245/add-transition-while-changing-img-src-with-javascript – aw04 Mar 29 '16 at 18:36
  • This one seems really interesting but if i happen to have three images i need update the hidden and current every change of image right? – Crimson-Med Mar 29 '16 at 18:53
  • Yep just off the top of my head that's probably how I'd handle it, use the current and next and keep track of the rest, so your solution would be slightly more complicated – aw04 Mar 29 '16 at 18:58
  • that should be ok however i have a problem my hidden image even if oppacity is 0; still leaves en empty blank space on my website. – Crimson-Med Mar 29 '16 at 19:06
  • notice in that answer they use absolute position, that will allow them to occupy the same space – aw04 Mar 29 '16 at 19:20
  • Yeah i did however when i use absolute when my image starts to fade it glitches to another spot for a quick moment :/ – Crimson-Med Mar 29 '16 at 19:23
  • I'm not sure what would cause that, but feel free to ask another question and link to it if the problem warrants it – aw04 Mar 29 '16 at 19:36

1 Answers1

2

If anyone comes across this, this is the simplest and most comprehensive version i ended up coding using jquery and javascript:

<script src="jquery.js"></script>
<script type = "text/javascript">
         function nextImage() {
            x = (x === imgArray.length - 1) ? 0 : x + 1;
            $("#img").fadeOut(400, function() {
                $("#img").attr("src",imgArray[x]);
            }).fadeIn(400);
         }

         function begintimer() {
            setInterval(nextImage, 5000);
         }

         var imgArray = [], x = -1;
         imgArray[0] = "images/test.jpg";
         imgArray[1] = "images/bg.jpg";
</script>
Crimson-Med
  • 219
  • 1
  • 4
  • 17