Rey Rajesh
Rey Rajesh

Reputation: 500

slideshow in html using javascript.. image changes but not displayed properly

i tried this code.. but when the image changes it is not displayed properly.. alt image(a small broken image is displayed)..

i tried putting var step=1; before the function as global variable.. But still it does not work.. I even tried document.images.slide.src = "images/pentagg.jpg";

<head>
<script type="text/javascript">
    var image1 = new Image()
    image1.src = "images/pentagg.jpg"
    var image2 = new Image()
    image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
    <script type="text/javascript">
            function slideit()
            {
                var step=1;
                document.images.slide.src = eval("image"+step+".src")
                if(step<2)
                    step++
                else
                    step=1
                setTimeout("slideit()",2500)
            }
            slideit()
    </script>
</body>

Upvotes: 0

Views: 180

Answers (2)

Md Ashaduzzaman
Md Ashaduzzaman

Reputation: 4038

There's something wrong you did. You made the step variable available inside slideit() function only by declaring it as a local variable. So everytime the function is being called using setTimeOut a new step variable is created. That causes never to change your initial image.

And I prefer this as the appropriate way to call the slideit function using setTimeOut

setTimeout(function(){slideit()},2500);

That's it. Here's the full code :

HTML :

<img src="http://picpuddle.com/wp-content/uploads/2014/06/cute-cartoons-21.jpg" width="500" height="300" name="slide" />

javaScript :

var step=1;
var image1 = new Image();
image1.src = "http://picpuddle.com/wp-content/uploads/2014/06/cute-cartoons-21.jpg";
var image2 = new Image();
image2.src = "http://www.hdwallpapers-3d.com/wp-content/uploads/2014/03/Cartoon-6.jpg";

function slideit()
{
    //This looks better though
    //document.getElementsByName("slide")[0].src = eval("image"+step+".src");
    document.images.slide.src = eval("image"+step+".src");

    if(step<2)
        step++;
    else
        step=1;
    setTimeout(function(){slideit()},2500);
}
slideit();

jsFiddle

Upvotes: 2

AncientYouth
AncientYouth

Reputation: 481

you can't pass the image variable as an argument like that. it's taking a string called "image1.src".

try putting them in an array then getting the index with your step variable.

Upvotes: 1

Related Questions