mardi 10 avril 2018

Different reloading on Javascript

I have 2 methods for randomizing. One is for an image, and the other is for an random string inside an array. The image method works without reloading the page. The string method always reloads the page and jumps to the top. The whole process doesn't work either if i change the href="#random" (#random does not exist) to something like href"#".

First the random string method which always reloads the page:

var myArray = ['1', '2', '3', '4'];
var rand = Math.floor(Math.random() * myArray.length);

function showrandom() {
  document.getElementById('random').innerHTML = myArray[rand];
}
showrandom();
<form name="imageForm">
  <table border=0>
    <tr>
      <td><br>
        <h1>
          <div id="random"></div>
        </h1>
      </td>
    </tr>
    <tr>
      <td>
        <br>
        <a onclick="showrandom();" class="btn btn--lg type--uppercase" href="">
          <span class="btn__text">Random Dice Roll</span>
      </td>
    </tr>
  </table>
</form>

Now the img method:

var imagesArray = ["img/dice-1.png", "img/dice-2.png", "img/dice-3.png", "img/dice-4.png", "img/dice-5.png", "img/dice-6.png"];

function displayImage() {
  var num = Math.floor(Math.random() * (imagesArray.length));
  document.canvas.src = imagesArray[num];
}
<form name="imageForm">
  <table border=0>
    <tr>
      <td>
        <img name="canvas" width="50%" height="auto" />
      </td>
    </tr>
    <tr>
      <td>
        <br>
        <a onclick="displayImage();" class="btn btn--lg type--uppercase" href="#random"><span class="btn__text">Random Dice Roll</span>
     </td>
    </tr>
  </table>
</form>



Aucun commentaire:

Enregistrer un commentaire