Search code examples
javascripthtmlbuttonanimated-gif

How can I make my button call a rotation of GIFs?


I have a button on a little page I built that reveals a DIV with a gif in it. Someone suggested it should call a new gif each time the button is clicked. I've hunted around for how to do this, but haven't been able to find a solution. How can I make it rotate through a selection of gif URLs each time the button is clicked again?

This is the code I currently have for the one gif:

HTML

<button class="yes" type="button" onclick="revealDiv()">YES!</button> <div id="gifDIV"> <iframe src="https://giphy.com/embed/OSWRJKmwUEOD6" width="480" height="270" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="https://giphy.com/gifs/excited-dance-party-OSWRJKmwUEOD6"></a></p> </div>

JAVASCRIPT

<script>
function revealDiv() {
document.getElementById('gifDIV').style.display = "block";
}

Any ideas on the best way to do this? I'm very new to this and this is the first time I've used JS so bear that in mind. Thanks!


Solution

  • First you should create an array of links.

    var ArrayGIF = ['https://media3.giphy.com/media/WNcbaCHN0mxsdJ2YXm/giphy.gif', 'https://media2.giphy.com/media/l3diOZVkXQ04BONB6/giphy.gif', 'https://media1.giphy.com/media/3o7bu0fTb50rSXgWsw/giphy.gif', 'https://media0.giphy.com/media/XKJ52vGno1REavaO5j/giphy.gif'];
    

    Everytime the button gets clicked, you generate a random number, that is between zero and the length of your array.

    var randomNumber = Math.floor(Math.random() * ArrayGIF.length);
    

    Finally you set the img src:

    document.getElementById('gif').src = ArrayGIF[randomNumber];
    

    Here is the final result: https://jsfiddle.net/kq0o2Lyc/12/

    I changed your code a litte bit, its no longer using a iframe to display the gif.