Vexasoe
Vexasoe

Reputation: 23

How do I change image every 2 second using Jquery

Ok, so basically i'm trying to create my own portfolio website, and i want these image "text" to be changed every 2 second...

How can i do that using my following code?

Jquery

        $("document").ready(function(){
            $("a").on("mouseover", function(event){
                event.preventDefault();

                var selection =$(this).html();
                var imgfolder ="images/";
                var new_image;

                switch(selection){
                    case "C#" :
                        new_image = image + "C#-Programmer.png";
                        break;
                    case "Java" :
                        new_image = image + "JAVA-Programmer.png";
                        break;
                    case "HTML" :
                        new_image = image + "HTML-Programmer.png";
                        break;
                    case "DMD" :
                        new_image = image + "Digital-Media-Designer.png";
                        break;
                    case "network" :
                        new_image = image + "Network-Engineer.png";
                        break;
                    default:
                        new_image =  + "UX-Designer.png";
                        break;
                }
                $("img").attr("src", new_image);
            });
            $("#hide").on("click",function(){
                $("img").fadeOut(1000,function(){
                    alert("fadeout completed")
                });
            });
            $("#show").on("click",function(){
                $("img").fadeIn(1000);
            });


        });

This is my html code

<img src="image/UX-Designer.png" alt="c#"/>

Upvotes: 2

Views: 2092

Answers (1)

Matt Greenberg
Matt Greenberg

Reputation: 2330

As @smdsgn said, use setInterval to create a timer based event. I would also recommend using an array of image locations and iterating through them that way. This doesn't seem the like the best use for a switch statement.

var images = [
	"images/img1.jpg",
  "iamges/img2.jpg",
  "images/img3.jpg"
]
var current = 0;
setInterval(function(){
			
  $('#flip').attr('src', images[current]);
  current = (current < images.length - 1)? current + 1: 0;

},1000); /*1000 = 1 sec*/
#flip{
  width: 100px;
  height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="flip" src="">

Upvotes: 3

Related Questions