I'm manipulating a classlist on a div with JS, adding a class with a random number e.g. target--random-number-2
.
I essentially want to 'reset' or 'reset' the classlist the next time the function is called, to re-add another class with a random number, so that I don't end up with multiple classes such as target--random-number-1 target--random-number-2 target--random-number-3
. What's the best way to do this?
Here's my clumsy attempt (which doesn't work):
function random_class_number(){
// if we've changed the target...
if (document.querySelector('#target').classList.contains('target-has-random-number')) {
// restore the previous classlist
document.querySelector('#target').classList = stored_classlist;
} else {
// if we haven't yet changed the target, store the classlist
var stored_classlist = document.querySelector('#target').classList;
}
const random_number = Math.floor((Math.random() * 3) + 1);
document.querySelector('#target').classList.add('target--random-number-' + random_number);
document.querySelector('#target').classList.add('target-has-random-number');
}
P.s. I'm trying to move away from jQuery, so no jQuery answers please.
Aucun commentaire:
Enregistrer un commentaire