Javascript image loop not working

I don’t know what to do, as I noob in javascript since I just started to learn today, so please go through.

I think I need to increase it when it spans, but I do not know how to do this, nor do I want to do any jquery.

<html>
    <head>
        <style type="text/css">
            div {
                height: 300px;
                width: 500px;
                margin: 0 auto;
                overflow: hidden;
            }
        </style>
    </head>
    <body>

        <div>
            <img id="image" src="html.png" alt="HTML">
        </div>

        <script language="javascript" type="text/javascript">

            var i = 1;

            function loop() {
                var i = i + 1;
                if (i == 3) {
                    i = 1;
                }
                if (i == 1) {
                    document.getElementById('image').src = "html.png";
                } else {
                    document.getElementById('image').src = "css3.png";
                }
            }
            var pictureloop = setInterval(loop(), 5000);

        </script>

    </body>
</html>
+3
source share
2 answers

You just need to try the following:

Just set the variable iin you loop()do not need to re-declare it once it is declared globally! and also remove ()from the methodsetInterval()

var i = 1;

function loop() {
    i = i + 1; // Change
    alert(i);
    if (i == 3) {
        i = 1;
    }
    if (i == 1) {
        document.getElementById('image').src = "html.png";
    } else {
        document.getElementById('image').src = "css3.png";
    }
}
setInterval(loop, 5000); //Change

Screenshot

0
source

You just started learning javascript

welcome;)

function loop(){
 i=++i==3?1:i;
 //i is : if i+1 is 3 then 1 else its i (the already i+1)

 document.getElementById('image').src=(i==1?'html':'css3')+'.png';
 //src is : if i is 1 then html else css3

}
var pictureloop=setInterval(loop,1000),i=1;
//set all vars you need separated by comma.

Demo

http://jsfiddle.net/9dZt6/1/

the right way

function loop(){
 i=!i;
 document.body.innerHTML=(i?'html':'css3')+'.png'
}
var pictureloop=setInterval(loop,1000),i=1;

Demo

http://jsfiddle.net/cRn6n/

another way: html5 css3

CSS

div{
 background:#000 url(html.png) no-repeat center center;
 background-size:contain;// cover,auto,100px 100px 
}
div.odd{
 background-image:url(css3.png);
}

Js

function toggle(){
 var div1=document.getElementsByTagName('div')[0];
 div1.classList.toggle('odd');
 timer=window.setTimeout(toggle,1e3);
}
var timer=window.setTimeout(toggle,1e3);

:

function toggle(){
 img.src=(img.src=='http://path/html.png'?'css3':'html')+'.png';
}
var img=document.getElementById('image'),
    timer=window.setInterval(toggle,1e3);

+1 jquery

fooobar.com/questions/1682/...

, .

0

All Articles