Nex Nex - 3 months ago 11
jQuery Question

Jquery button getting a random image from array

Playing with jquery and I need help with this part on codepen.

I commented the part I need help with and could someone explain how to get a random image to display on img after I click the button

My code:

$('#switch').on('click',function(){
//Help with this part
$('h1').html("I'm supposed to switch the picture but I can't do that");


I need #switch(button) to change the #duck(image) src to random src from the array I provided.

CodePen link

Answer

Your switch click handler should look like this:

$('#switch').on('click', function () {
  $('h1').html("I'm supposed to switch the picture but I can't do that"); //Help with this part 
  $(".content").find("img").attr("src", myArray[Math.floor(Math.random() * myArray.length -1)]);
});

Comments