A button for switching pictures?

A button for switching pictures?
0

#1

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();
            }
        });
    });

});


#2

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.


#3

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


#4

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.


#5

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.


#6

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");

  });
});

#7

#8

On any click of the button, your img fadeOut callback function is going to loop very quickly through and only really show the last image in the array. You do not want a for loop. You want to keep track of which image your are currently on (via array index?) and on click, reference the next image in the array. What do you want to happen if all images have been shown (the array has been traversed) when you click on the button?


#9

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


#10

You would need to check if your tracking variable (the current index of the photo in the array) is at the end. If it is, reset this variable back to 0.


#11

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


#12

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;
              }
         });
    });

});


#13

If @hbar1st’s does not work for you, then try:

$(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 = 0;
  $('#button').click(function() {
    $('img').fadeOut(function() {
      $(this).attr('src', arr[i++]).fadeIn();
        i = i % arr.length;
    });
  });
});

#14

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


#16

Reassigns the remainder of i divided by arr.length back to i.

Assuming arr.length is 2:

if i = 0, then 0 / 2 so remainder is 0
if i = 1, then 1 / 2 so remainder is 1
if i = 2, then 2 /2 so remainder is 0


#17

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


#18

Yes, let’s say you had 4 pictures, so arr.length is 4.

if i = 0, then 0 / 4 so remainder is 0
if i = 1, then 1 / 4 so remainder is 1
if i = 2, then 2 /4 so remainder is 2
if i = 3, then 3 /4 so remainder is 3
if i = 4, then 4 /4 so remainder is 0


#19

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

Nevermind I get it.


#20

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.


#21

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