Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display random parts of a page on refresh?

If I were to have a block of html coding that is stylized via css such as this:

<title>Test Title 1</title>
<p>Test Paragraph 1<p>
<a href="test link1">test link 1</a>
<title>Test Title 2</title>
<p>Test Paragraph 2<p>
<a href="test link2">test link 2</a>
<title>Test Title 3</title>
<p>Test Paragraph 3<p>
<a href="test link3">test link 3</a>

I want to be able to display a set of parts randomly together, (i.e. title 1, paragraph 1 and link 1 only). Then if I refresh it randomly shows 1, 2 or 3. But they need to stay together, like parts of 1 cannot show with part of 3 and so on.

I know this is simple, but I can't figure out how to get them to show randomly together. Thanks in advance!

like image 954
user3537151 Avatar asked Dec 13 '25 01:12

user3537151


1 Answers

The first step is to group all related parts together. See the HTML below. Note that title tags were replaced with heading tags. The title should be in the header of the page.

<section>
    <h2>Test Title 1</h2>
    <p>Test Paragraph 1</p>
    <a href="test link1">test link 1</a>
</section>
<section>
    <h2>Test Title 2</h2>
    <p>Test Paragraph 2</p>
    <a href="test link2">test link 2</a>
</section>
<section>
    <h2>Test Title 3</h2>
    <p>Test Paragraph 3</p>
    <a href="test link3">test link 3</a>
</section>

Then, in CSS you need to hide them:

section {
    display: none;
}

And, here's jQuery stuff:

$("section").eq(Math.floor(Math.random() * 3)).css("display", "block");

Here's jsfiddle: http://jsfiddle.net/Aej52/

like image 97
DRD Avatar answered Dec 15 '25 14:12

DRD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!