简体   繁体   中英

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!

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.

You can store an array of GIF URLs, and then cycle through them each time. You do this by changing the src of the iframe .

https://jsfiddle.net/iONinja/p1w406yn/7/

<script>
var gifs = ["https://giphy.com/embed/8vQSQ3cNXuDGo", "https://giphy.com/embed/JIX9t2j0ZTN9S", "https://giphy.com/embed/vFKqnCdLPNOKc"];
var n = 0;

function revealDiv() {
    document.getElementById("gifDIV").style.display = "block";
    document.getElementById("gifIFRAME").src = gifs[n];
    n++;
    if (n >= gifs.length) {
        n = 0;
    }
}
</script>

<button class="yes" type="button" onclick="revealDiv()">YES!</button>
<div id="gifDIV"><iframe id="gifIFRAME" src="" width="480" height="480" frameBorder="0" class="giphy-embed" allowFullScreen></iframe></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM