Say I had the following array: [x, y, z]
If I wanted to shuffle that array and display each element one by one (without repeating) on each button click, how would I write that function with Javascript to populate the paragraph? Also, would you recommend writing the code inline or on a separate sheet and then imbedding it? Thank you in advance.
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title> Title </title>
</head>
<body>
<script src="javascript.js"></script>
<div>
<p></p>
</div>
<div>
<button onclick="displayElement()">Start</button>
</div>
</body>
</html>
You need a shuffling function (I got one) and some structure around it for the button click that will reveal the shuffle.
var arr = ['x', 'y', 'z']
var button = document.querySelector(".my-button");
var reset = document.querySelector(".my-reset");
var shuffled = shuffle(arr)
var index = 0;
button.addEventListener('click', function() {
if (index < shuffled.length) {
console.log(shuffled[index]);
index++
}
})
reset.addEventListener('click', function() {
shuffled = shuffle(arr)
index = 0;
})
function shuffle(str_or_arr) {
var a = typeof str_or_arr == 'string' ? str_or_arr.split('') : str_or_arr
var n = a.length;
for (var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return typeof str_or_arr == 'string' ? a.join('') : a;
}
<button class="my-button">next</button>
<button class="my-reset">reset</button>