+ 1

How to assign an element a random class on scroll

I am trying to make a site that has contents with a slide in effects on scroll but my code keeps giving me problems. I could give it one particular class on scroll but I thought why not give it a different class when I reload the site. So I stored the various classes in an array and used Math.random to give the elements a random class. But the result from my code is that it assigns all the classes stored in the array into the elements. How do I make so that only one is assigned? Here is the code I wrote: var num; var classes = ['fadeInRightBig', 'fadeInLeftBig']; function rand() { num = Math.floor(Math.random() * 2); return num; } $(window).scroll(function () { $('.anima') .each(function () { var elempos = $(this).offset().top; var winTop = $(window).scrollTop(); if (elempos <winTop + 600) { $(this) .addClass(classes [rand()]); } }); Please help });

28th Apr 2022, 7:53 AM
Joel Amaefula🇳🇬
Joel Amaefula🇳🇬 - avatar
1 ответ
0
try first to remove previous class and then add new
4th May 2023, 10:51 AM
nprNikita
nprNikita - avatar