Getting creative with jQuery: Adding a random class using addClass()

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 -->

Is there a way to dynamically add the "show" class to a single <p> element each time the document is loaded, chosen randomly?

In simpler terms, when the page loads, one paragraph should be visible and this paragraph should be selected at random.

Answer №1

Give this a try:

$(document).ready(function() {
    var paragraphs = $('div.myWords p');
    var index = Math.floor(Math.random() * paragraphs.length);
    paragraphs.eq(index).addClass('display');
});

If your goal is to switch from display: none to display: block, you can skip using the display class in your CSS and simply reveal it with jQuery, like so:

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

Additionally, ensure your CSS properly overrides. Adjust display: hidden; to display: none;, and include the div.myWords class in your second rule:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to showcase the values linked to their corresponding ids in a table?

With the query below, I am joining two tables using the order_id and displaying all the values from the user_orders table. My goal is to only display the order_Id rows that match the order_manager table, as shown in the image below. public functio ...

Adding a unique field to a specifically tailored post type

I'm dealing with a plugin-generated component that showcases articles from a custom post type, each with the class post-id. Unfortunately, I can't modify the plugin's files in the child theme to make changes, so I have to create a custom fun ...

Retrieving HTML content using CURL

Could really use some help with my curl issue: I'm using CURL to connect to a page, then redirecting myself to another page that's only accessible when logged in. How can I retrieve the HTML code from this page? I can see the page displayed, but ...

How to align buttons in the center of a Bootstrap grid column using Angular's *ngFor directive

I have been trying to center some buttons using the bootstrap 4 grid system within a column with a green border. Despite using justify-content-center, I have not been successful so far. <div class="row" style="border:1px solid red;"& ...

Using CSS to set the display property to table-cell and converting it to a

I needed a SideMenu that would match the length of the content, but for some reason, using display:table-cell caused it to display:block in both Firefox and Chrome. What could be the reason behind this inconsistency? .back-branded { background: #900; ...

The JavaScript-set value in a form field is not being transmitted to the PHP script within the $_POST array

Struggling to pass a JavaScript value to a .php script, and then on to a .txt script. It works fine with regular numbers, but when trying with the variable it fails, leaving the .txt file blank. Despite extensive research online, I can't seem to get i ...

How to use jQuery to iterate through a C# serialized List<string>

I am working on a webmethod that reads the first line of a CSV file to extract the column titles and then stores each item in a list to be returned to an ajax call. Below is the code snippet for this functionality: [WebMethod] public static string getAvai ...

Struggling to get the knockout js remove function to function properly within a nested table structure

I've been encountering issues while trying to eliminate the formulation elements with the 'Delete comp' link. I can't seem to figure out why it's not functioning as expected. Moreover, the 'Add another composition' link o ...

Tips for implementing and utilizing onclick functions in EJS

My goal is to develop a trivia game with interactive features. I aim to enable users to click on an answer, which will trigger a border effect and increase the points variable. Below is the layout of the entire page: <% include ../partials/boilerp ...

Altering the dimensions of Bootstrap's default navbar for a more compact look

Currently, I am attempting to modify the size of Twitter Bootstrap's standard navbar to a smaller dimension. My goal is to have the Brand/logo on the left side, menu options in the center, and social media icons on the right side within the navbar. U ...

Place the text below the adaptable div

Could anyone offer guidance on how to properly align text underneath responsive images within divs? The issue I'm facing is that the divs adjust smoothly based on the viewport size, but the text below them doesn't stay centered as intended. Whi ...

Using a background image in the navigation menu with CSS

Looking to create a horizontal menu with a responsive background image. Struggling with the issue of the 'ul' menu being misaligned with the background image when in full-screen mode. Attempted to use separate 'div' containers for the ...

Displaying MySQL results in a vertical sequence

I've stored the data in my database as follows: Football ART-NR-1337 Price: 5$ Basketball ART-NR-1333 Price: 10$ Now, I am working on a .php file that displays the articles like this: Football Basketball ART-NR-1337 ART-NR-1333 Price: 5$ ...

Leveraging Angular directives in pure HTML within jQuery

After receiving an AJAX response, I am dynamically generating HTML code. Here is an example of what I am doing: var html = ''; html = '<div ng-click="deleteRecord($event)">delete</delete>'; $('.main).append(html); Ho ...

"Displaying events on fullcalendar using data retrieved from a PHP server with a

After creating my first RESTful PHP server, specially designed for responding to fullcalendar events callback, I encountered a strange issue. Even though the output from my server matches the string produced by the json-events.php file in the fullcalendar ...

The issue with JQuery's JSON.stringify function not functioning as expected

Hi everyone, I'm currently working on a project involving a nested menu and I need to update it via API whenever the client moves an item. To achieve this, I am using a jQuery plugin called . The plugin includes an onDrop method as shown in the code s ...

Tips for retrieving the count from HTML using JavaScript:

I need to determine the count of list items in an unordered list within dir-pagination-controls. How can I achieve this using JavaScript? <dir-pagination-controls min-size="1" direction-links="true" boundary-links="true" class="pull-right ng-isolate- ...

Applying ngClass to handle positive and negative numbers and adjust color in Ionic/Capacitor

I have data from my API that includes price and percentage data. I want to display negative numbers in red, and zero or positive numbers in green. After exploring Angular documentation, I found that ngStyle and ngClass can be used for this purpose. I chose ...

Keeping the header fixed on a sticky div (tocbot)

While working on my website, I decided to implement a Table of Contents section using tocbot. However, I encountered an issue where the Title I added above the table doesn't stay fixed when scrolling. https://i.stack.imgur.com/vCm1K.gif Here's ...

When reopening the modal in Bootstrap V5 with jQuery, the close event may not trigger as expected

When trying to implement special functionality in my modal close event using sweetalert2, I encountered an issue where the close event does not trigger again after closing the modal for the first time. Check out a live example here: https://codepen.io/th ...