html - JavaScript button that generates objects in order -


i created button in js generates gifs randomly, change making them appear in order , repeat.

window.onload = () => {      const factsarr = [  	{  	image:'https://media.giphy.com/media/p6lx0t2mzypdc/giphy.gif',  	},  	{  	image:'https://media.giphy.com/media/uwdvkl2xn1evi/giphy.gif',  	},    {  	image:'https://media.giphy.com/media/1nkuav308cbws/giphy.gif',  	}      ];                document.getelementbyid('generate-btn').addeventlistener('click', () => {        const idx = math.floor(math.random() * factsarr.length);        document.getelementbyid('image').setattribute('src', factsarr[idx].image)      })          }
<button id="generate-btn">amazing fact button</button>  <img id="image"></img>

in snippet below, used global currimage variable increases on each click , resets when reaching image array size. image taken array's currimage index.

   // init variable   var currimage = 0;    window.onload = () => {      const factsarr = [  	{ image:'https://media.giphy.com/media/p6lx0t2mzypdc/giphy.gif'},  	{ image:'https://media.giphy.com/media/uwdvkl2xn1evi/giphy.gif'},          { image:'https://media.giphy.com/media/1nkuav308cbws/giphy.gif'}      ];            document.getelementbyid('generate-btn').addeventlistener('click', () =>       {          document.getelementbyid('image').setattribute('src', factsarr[currimage].image);            // increment variable on each click          currimage++;            //reset variable when reaches image array size          if (currimage == factsarr.length)             currimage = 0;      })          }
<button id="generate-btn">amazing fact button</button>  <img id="image"></img>


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -