hjb-web design hjb-web design - 6 months ago 9
Javascript Question

Display array item once(on click)

Here is what i am trying to do..


  1. On button click a random array item is displayed.

  2. The array item can only be display once.



Currently i have set the code up as:


  1. On click random array item is displayed.

  2. Button click continues to loop through with no end.

  3. Button click displays the item multiple times.



Here is a link to the code http://codepen.io/fun/pen/aNedGQ?editors=1010

Help would be appreciated! =)

Below is the code, the same as the link above.

HTML

<div id ='display'> </div>
<div class ='button'>Next item</div>


JS

var items = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Randomly on click display each item
// Only display each item once
// Stop when all items have been displayed

// Display to screen
var display = function(info) {
var x = document.getElementById('display');
x.innerHTML = info;
}
// Create random number
var random = Math.floor(Math.random() * items.length);
// Click handler
$('.button').on('click', function() {
// Display random arr items to screen
display(items[random]);
// Next item to be random
random = (random + Math.floor(Math.random() * items.length)) % items.length;
});

Answer

You can display random item and then remove it from array

var items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$('.button').click(function() {
  var rand = items[Math.floor(Math.random() * items.length)];
  $('#display').text(rand);
  items.splice(items.indexOf(rand), 1);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='button'>Next item</div>
<div id='display'></div>