'Assigning string into the button every time page refreshes

this code successfully shuffles the phone numbers order every time pages refreshes. What I'm trying to do is create a Call us button that selects a phone number from the "var = arr" array and assign that to the button but when page refreshes assigned number from the button has to be changed so that way customer could call a different number every time.

$(document).ready(function() {
  function shuffle(array) {
    var currentIndex = array.length,
      temporaryValue, randomIndex;

    while (0 !== currentIndex) {

      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

    return array;
  }

  var arr = ['<div class="class1"><a href="tel:+17866331938"><p>+1 786 633 19 38</p></a></div>',
    '<div class="class2"><a href="tel:+17866331298"><p>+1 786 633 12 98</p></a></div>',
    '<div class="class3"><a href="tel:+17866331903"><p>+1 786 633 19 03</p></a></div>',
    '<div class="class4"><a href="tel:+17865741168"><p>+1 786 574 11 68</p></a></div>'
  ];
  arr = shuffle(arr);
  arr.map(function(k, v) {
    $(".div-wrap").append(k);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="div-wrap"></div>


Solution 1:[1]

  1. Your array should contain phone numbers, not elaborate HTML structures.
  2. forEach is a better method here. You don't need keys, and you don't need a new array.
  3. We'll simply remove whitespace characters for the href attribute values.
  4. Anchors should not contain paragraphs. While it may be allowed by HTML5 spec, it's an odd arrangement.
  5. You might not need jQuery. I love jQuery and used it heavily back during the dark ages of browser standards, but it's less and less necessary.

Key concepts:

document.addEventListener('DOMContentLoaded', function() {
  function shuffle(array) {
    var currentIndex = array.length,
      temporaryValue, randomIndex;

    while (0 !== currentIndex) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

    return array;
  }

  var arr = ['1 786 633 19 38', '1 786 633 12 98', '1 786 633 19 03', '1 786 574 11 68'];
  arr = shuffle(arr);

  arr.forEach(function(v) {
    const el = `<p><a href="tel:+${v.replace(/ /g,'')}">+${v}</a></p>`;
    document.querySelector(".div-wrap").insertAdjacentHTML('beforeend', el);
  });
});
<div class="div-wrap"></div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1