0

So I built a fairly simple slideshow, but can't quite figure out how to incorporate the fade in / fade out effect. I've read that it's best to use JQuery, but some have suggested that standard JavaScript would also do the trick - in any case, I've tried several scripts, but none seem to work. If someone here could help, I'd be in their debt!

Here's my code:

<script type = "text/javascript">
    var Image = new Array("pics/21cents.png", "pics/22cents.png", "pics/23cents.png");
    var Image_Number = 0;
    var Image_Length = Image.length - 1;
    var x;
    function change_image(num) {
        Image_Number = Image_Number + num;
        if (Image_Number > Image_Length) {
            Image_Number = 0;
        }
        if (Image_Number < 0) {
            Image_Number = Image_Length;
        }
        document.slideshow1.src=Image[Image_Number];
        return false;
    }
    function auto() {
        x = setInterval("change_image(-1)", 5000);  
    }
    function stop() {
        clearInterval(x);
    }
    auto();
</script>
Guillaume Algis
  • 10,705
  • 6
  • 44
  • 72
  • 1
    Probably there isn't an easy way to do this without some libraray, see this question : [fade effect using javascript no jquery?](http://stackoverflow.com/questions/5104053/fade-effect-using-javascript-no-jquery). With jQuery you could really shorten the code. – gskema Feb 26 '14 at 19:35

1 Answers1

0

The easiest way to do this is by far by using jQuery. In addition to a handful of useful UI effects (e.g. slideDown(), fadeOut(), etc), you also get the ability to select and manipulate DOM elements with ease.

For example, if you were going to use jQuery it would be as easy as something like:

var $img = $("<img>").css({"display": "none"}).prop("src", "http://placehold.it/500x500");
$("div").html($img);
$("img").fadeIn();

Otherwise to get the fadeIn/Out effect you will have to set somesort of setInterval() loop, changing the opacity by a percentage at each iteration. E.G.:

setInterval(function() {
    var img = document.getElementById("image");

    var opacity = img.style.opacity;
    if(opacity !== 1) {
        img.style.opacity += 0.01;
    }
}, 100);
user2521439
  • 1,405
  • 2
  • 13
  • 19
  • Thanks man, I decided to use the JavaScript code you listed.....but how would you add this code to my existing JavaScript code for the slideshow? Would I open a separate script tag and paste it in there or would I paste that code inside the same JS tag up there? Thanks again! – user3357403 Feb 26 '14 at 21:09
  • Do you mean the jQuery code or the opacity thing? (ps if you like the answer you can accept it :) ) – user2521439 Feb 26 '14 at 21:11
  • The opacity thing! :) – user3357403 Feb 26 '14 at 21:35
  • The code I gave was just a simple example - have a look at http://stackoverflow.com/questions/5104053/fade-effect-using-javascript-no-jquery for more detailed answers – user2521439 Feb 26 '14 at 21:46