Home > Web Front-end > JS Tutorial > Personalizing Your Website with Random Text Displays

Personalizing Your Website with Random Text Displays

Mary-Kate Olsen
Release: 2024-12-05 13:06:10
Original
363 people have browsed it

Personalizing Your Website with Random Text Displays

The "Where to next?" section of my website includes a small story in the footer that helps visitors to explore semi-hidden pages and go on an adventure (inspired by Manuel). In it, I mention my favorite types of coffee, connecting to my page on Buy me a coffee. If you've paid close attention to this section, you might have noticed that the coffee types are randomly selected each time the page loads.

Here’s how I achieved that:

The HTML

The structure begins with this simple snippet:

I’m a huge <span>



<p>The <span> element with the id random-coffee serves as the placeholder for displaying the coffee name. By default, it shows "caffè latte" in case JavaScript is disabled or unavailable.

<h3>
  
  
  The JavaScript
</h3>

<p>To make the magic happen, I added the following JavaScript code:<br>
</p>

<pre class="brush:php;toolbar:false">const coffees = ["caffè latte", "cappuccino", "flat white", "cortado", "latte macchiato"];
const randomCoffee = document.getElementById("random-coffee");
randomCoffee.innerText = coffees[Math.floor(Math.random() * coffees.length)];
Copy after login

Here’s a breakdown of the script:

  1. Define the options:

    The first line creates a list called coffees, listing five types of coffee. You can customize this list to include your own favorites or even replace it with types of tea or other beverages.

  2. Locate the placeholder:

    The second line uses the function document.getElementById() to locate the element in the HTML by its unique id, random-coffee.

  3. Randomize the selection:

    The third line picks a random coffee type from the coffees array using the function Math.random() and updates the text content of the element with the selected coffee.

That’s It!

This simple setup dynamically displays a different coffee name each time the page is loaded. It adds a little bit of randomness and personality to my site.

And now, if you’ll excuse me, I’m off to enjoy a warm and cozy caffè latte!

The above is the detailed content of Personalizing Your Website with Random Text Displays. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template