A button for switching pictures?

My end goal here is to switch gifs (not pictures - and a multitude of them (not just 2)) by clicking a button, can anyone help?

HTML:

        <button id = "button">Click Me!</button>

        <img src = "#">
$(document).ready(function(){

    let arr = ["https://images.unsplash.com/photo-1534043464124-3be32fe000c9?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=25fb0992bdb86b7fbef53ead58c7b7cd&auto=format&fit=crop&w=950&q=80", "https://images.unsplash.com/photo-1534162967756-a412cc66c624?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=69dd3295b9d2406824447c5cd74bc032&auto=format&fit=crop&w=1957&q=80"]

    $("#button").click(function() {
        $("img").fadeOut(function() {
            for (let i = 0; i < arr.length; i++) {
                $(this).attr('src', arr[i]).fadeIn();
            }
        });
    });

});

What if you reversed the logic so that you have this:

for (let i = 0; i < arr.length; i++) {
  //fade out img
  //change src to new value in array
  //fade in new value;
  //put some kind of delay timer here so it doesn't happen too fast
}

Edit: I assumed above that one button click results in the array of images being shown. If you meant that each button click shows a different image, then the logic would be different.

Yes, I want to click the button and have a different source pop up. Preferably in order and maybe not randomized.

Ah ok, then in that case, try looking at my random quote generator javascript code here:

It essentially does the exact same logic you need but with text.

I tried with this:

$(document).ready(function(){

    function getGif() {
        let arr = ["https://images.unsplash.com/photo-1534043464124-3be32fe000c9?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=25fb0992bdb86b7fbef53ead58c7b7cd&auto=format&fit=crop&w=950&q=80", "https://images.unsplash.com/photo-1534162967756-a412cc66c624?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=69dd3295b9d2406824447c5cd74bc032&auto=format&fit=crop&w=1957&q=80"]
        let randomNum = Math.floor((Math.random()*arr.length));
        let randomGif = arr[randomNum];

        $("img").src(randomGif);
    }

    $(".button").on("click", function() {
        getGif();
    });

});

But nothing worked. I also made the random quote machine but don’t really want it being randomized.

hi!
Actually my machine is only randomized for the first quote only. I store the current quote number in the session storage and that way it is remembered between clicks.

If you have a codepen with your code , I can take a closer look at the log to see what is happening…

here’s my code (from the codepen I shared earlier)

$(document).ready(function () {
  let currQnum = parseInt(sessionStorage.getItem('currentQuote'));
  console.log("currQnum at start = "+ currQnum);
  if (!sessionStorage.getItem('currentQuote')) {

    console.log("Pretend first load and random quote needed");
    currQnum = randFirstQuote(quoteArr);
    sessionStorage.setItem('currentQuote', currQnum);
    $("#author").text(quoteArr[currQnum].author);
    $("#text").text('<span id="leftQ">"</span>'+quoteArr[currQnum].quote+'<span id="rightQ">"</span>');
  $("a").attr('href',tweetIt(quoteArr[currQnum].quote,quoteArr[currQnum].author));
  console.log(tweetIt(quoteArr[currQnum].quote,quoteArr[currQnum].author));
  } 

  $("button").click(function() {
    currQnum += 1;
    if ( currQnum >= quoteArr.length ) {
      currQnum = 0;
    }
    sessionStorage.setItem('currentQuote', currQnum);
    $("a").attr('href',tweetIt(quoteArr[currQnum].quote,quoteArr[currQnum].author));
    console.log(tweetIt(quoteArr[currQnum].quote,quoteArr[currQnum].author));  
    console.log("currentQuote exists and before increment is "+       sessionStorage.getItem('currentQuote'));

    $("#centerBox").fadeOut(2000, "linear");
    $("#quote-box").fadeOut(1800, "linear");
    
    $("#author").fadeOut(1800, "linear", function() {
      $("#author").text(quoteArr[sessionStorage.getItem('currentQuote')].author);
      $("#author").fadeIn(1800, "linear");
    });
    $("#text").fadeOut(1800,"linear",function() {
   
      $("#text").html( '<span id="leftQ">"</span>'+quoteArr[sessionStorage.getItem('currentQuote')].quote+'<span id="rightQ">"</span>');
      $("#text").fadeIn(1800,"linear");
    });
    
    $("#centerBox").fadeIn(1600, "linear");
    $("#quote-box").fadeIn(1400, "linear");

  });
});

https://codepen.io/rstorms/pen/GBLKww

Just loop back to the first one. I want first gif, second gif, third, fourth, etc., then 1, 2, 3, 4.

Will work on this on a whiteboard in a couple hours. Thank you as always.

Hi again,

try this:

$(document).ready(function(){

    let arr = ["https://images.unsplash.com/photo-1534043464124-3be32fe000c9?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=25fb0992bdb86b7fbef53ead58c7b7cd&auto=format&fit=crop&w=950&q=80", "https://images.unsplash.com/photo-1534162967756-a412cc66c624?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=69dd3295b9d2406824447c5cd74bc032&auto=format&fit=crop&w=1957&q=80"];
  let i = -1;
    $("#button").click(function() {
       i++;
        $("img").fadeOut(function() {
            
              console.log("i is="+ i);
              $(this).attr('src', arr[i]).fadeIn();
              if ( i == arr.length ) {
                  i = 0;
              }
         });
    });

});

It is a nice looking solution, thank you! I don’t understand i =i % arr.length;

This will still work if I add more pictures to the array?

I’m pretty bad with modulo. :confused: How is 3 / 4 = 3?

Nevermind I get it.

What I don’t understand is if you are at the last picture and the remainder is 0, isn’t that the zeroth index of the array and therefore the first and not the last picture? Just a little confused how this works.

As long as you count from 0, it is not a problem.

Please elaborate on what you mean by that.

If you want to cycle through 3 elements… The expression is n % 3 This results a cycle of 0 1 2 0 1 2.... This already lines up well with how array indexing, which counts from 0. So, if you decide to call your 1st element the 0th element, then everything is fine, which does not apply in this case. So, the solution will remain correct.

However, if you decided to count from 1, you will be off by one all the time. If you want to count from 1, then you need to introduce an offset.

I am counting from zero. I thank Randell for his solution and I’m using it.

Another question, I have another image in the slew of things that I don’t want to be jumbled into this function. Instead of calling $(‘img’)…is there a class I can call that set of images by?

I guess calling $(’.class’)

Any idea how to get rid of the image src button or empty box before I click the button?