javascript - Need this if/else Statement to function with a click action from a button -


admittedly i'm new javascript , assume trying simple having lot of trouble figuring out how make function work click of button instead of page load/reload.

<script type="text/javascript">      <!--      var ic = 9; // number of alternative images      var xoxo = new array(ic); // array hold filenames        xoxo[0] = "images/staminup.png"      xoxo[1] = "images/doubletap.png"      xoxo[2] = "images/qucikrevive.png"      xoxo[3] = "images/electriccherry.png"      xoxo[4] = "images/juggernog.png"      xoxo[5] = "images/speedcola.png"      xoxo[6] = "images/mulekick.png"      xoxo[7] = "images/widowswine.png"      xoxo[8] = "images/deadshot.png"        function pickrandom() {          if (math.random)              return [math.floor(math.random() * xoxo.length)];          else {              var = new date();              return (now.gettime() / 1000) % xoxo.length;          }      }      // write out img tag, using randomly-chosen image name.      var choice = pickrandom(ic);      // -->            </script>
<html>  <head>    </head>  <body>  <p id="perk"></p>  <script>document.getelementbyid("perk").innerhtml = ('<img src= "'+xoxo[choice]+'">')</script>  </body>   </html> 

so create button id this:

<button id="changeimage">change image</button> 

now add event listener triggered if clicks on button. event listener invoke function, suggest swap image change own function.

    function changeimage() {        document.getelementbyid("perk").innerhtml = ('<img src= "'+xoxo[pickrandom(ic)]+'">');     } 

this function call in beginning once:

changeimage(); 

and function pass parameter event listener:

document.getelementbyid("changeimage").addeventlistener('click', changeimage); 

check out fiddle: https://jsfiddle.net/u0jw8u11/


Comments