Jonas
Jonas

Reputation: 85

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

The 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 the class "show" to a single <p> element at a time at random on document ready?

In other words, every time the page is loaded 1 p tag should be visible and this p tag should be chosen at random.

Upvotes: 3

Views: 2497

Answers (1)

BoltClock
BoltClock

Reputation: 723678

Try this:

$(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: none to display: block, you can omit the show class from your CSS and show it using only jQuery, like this:

$(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 so that overrides work. Change display: hidden; to display: none;, and add the div.myWords class to your second rule:

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

Upvotes: 8

Related Questions