How to addClass () in RANDOM for an element in jQuery?

html / css:

<style>
div.myWords p { display: hidden; }
p.show { display: block; }
</style>

<div class="myWords">

<p>Hello</p>
<p>Hola</p>
<p>Bonjour</p>

</div><!-- myWords -->

How can I add a show class to a single element <p>in random order when a document is ready?

In other words, every time a page loads, 1 p-tag should be visible, and this tag should be chosen arbitrarily.

+3
source share
1 answer

Try the following:

$(document).ready(function() {
    var paras = $('div.myWords p');
    var rand = Math.floor(Math.random() * paras.length);
    paras.eq(rand).addClass('show');
});

If you are trying to change display: noneto display: block, you can omit the class showfrom your CSS and show it using only jQuery, for example:

$(document).ready(function() {
    var paras = $('div.myWords p');
    var rand = Math.floor(Math.random() * paras.length);
    paras.eq(rand).show();
});

By the way, you need to change your CSS in order to redefine the work. Change display: hidden;to display: none;and add a class div.myWordsto the second rule:

div.myWords p { display: none; }
div.myWords p.show { display: block; }
+8
source

Source: https://habr.com/ru/post/1794204/


All Articles