random order of buttons on refresh in vanilla js
- Published
- Reading time
- 1 min read
- Length
- 218 words
On this page
Random Order of Buttons on Refresh in Vanilla JS#
As a web developer, I have faced an issue where the order of buttons on a page is changing randomly on refresh. This occurs due to the asynchronous nature of JavaScript and can be resolved by using Vanilla JS.
Method 1:#
The first method to resolve this issue is by using the Math.random() function. This function generates a random number between 0 and 1, which can then be used to shuffle the buttons on the page.
const buttons = document.querySelectorAll('.button');
const parent = document.querySelector('.button-container');
parent.appendChild(buttons[0]);
for (let i = 1; i < buttons.length; i++) {
const randomIndex = Math.floor(Math.random() * (i + 1));
parent.insertBefore(buttons[i], buttons[randomIndex]);
}Method 2:#
The second method is by using the Fisher-Yates Shuffle Algorithm. This algorithm loops through the array and swaps the current element with a randomly selected element from the remaining elements in the array.
const buttons = document.querySelectorAll('.button');
const parent = document.querySelector('.button-container');
for (let i = buttons.length - 1; i > 0; i--) {
const randomIndex = Math.floor(Math.random() * (i + 1));
[buttons[i], buttons[randomIndex]] = [buttons[randomIndex], buttons[i]];
}
buttons.forEach(button => parent.appendChild(button));Both of these methods will randomly shuffle the order of the buttons on refresh and provide a better user experience.