In this blog post you’ll learn how to get random array items on a click of a button using JavaScript.
JavaScript Method Used:
Math.floor()
Math.random()
Get Random Array Items On a Click.
First we’ll create the design using HTML and CSS.
We design one button and one another element to show the output
HTML
<!DOCTYPE html>
<html lang="en">
<!-- maketechstuff.com -->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Random Item From Array On Click In JavaScript. | Maketechstuff.com</title>
<style>
.container{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% , -50%);
width: 400px;
text-align: center;
}
.output{
font-size: 30px;
font-weight: bold;
}
button{
font-size: 30px;
padding: 10px 30px;
margin: 20px 0px;
border: none;
background-color: blue;
color: #fff;
border-radius: 5px;
cursor: pointer;
transition: 0.2s;
}
button:active{
transform: scale(0.95);
}
</style>
</head>
<body>
<div class="container">
<div class="output"></div>
<button class="button">Click Here</button>
</div>
</body>
</html>
The design is ready. Now let’s add functionality to get the random item from an array on a click of button using JavaScript.
- First we define the variable for the button and for the output element to show the output. And also create one array with the name fruit_array containing fruit names as items.
- Then we add click event Listeners to the button that calls a function.
- In that function first we generate the random number according to fruit_array length and store that random number in a variable named random_number. This random number we’ll use as an index value to array (fruit_array). By doing this we get the random item from the array.
- After generating the random number, we extract the array item based on the generated random number (use random number as an index value) and store it inside the output element (the element in which we want to show the array item in the web page).
See below code:
JavaScript
let button = document.querySelector(".button");
let output = document.querySelector(".output");
let fruits_array = ["Mango", "Banana", "Apple", "Pineapple", "Pomogranate", "Guava", "Grapes", "Orange"];
button.addEventListener("click", get_random_array_item);
function get_random_array_item() {
// Generating random new between and including 8 (which is fruit_array length). We'll use it as a index to the fruit array to extract the item.
let random_number = Math.floor(Math.random() * fruits_array.length);
// Extracting the item from the array according to random index (random_number), and storing inside the element to show on a webpage.
output.innerHTML = fruits_array[random_number];
}
So that's how you can get the random item of an array on a button click using JavaScript. If you have any query or suggestion feel free to write in the comment section.
Share your thoughts.