Seeking a way to display a random div at a 1% rate without generating additional div elements

Searching for an answer to display only one div with a rate of 1/100. Currently, I am utilizing the following JavaScript:

var random = Math.floor(Math.random() * $('.item').length);
$('.item').hide().eq(random).show();

This method works well as long as I have 100 divs with the .item class, but it results in cluttered code.

Answer №1

If you're looking to display a div randomly each time the page is refreshed, here's how you can achieve it:

JavaScript (jQuery):

$(document).ready(function(e) {

    var randomNumber = Math.floor(Math.random() * 100) + 1 ;
    $(".item_" + randomNumber).show();

});

HTML:

<div class="item_1" style="display:none;">This div will be displayed randomly</div>

Link to jsFiddle example

The div with class "item_1" will be shown when the random number generated is 1. I hope this solution works for you.

Answer №2

Have you considered using this approach instead?

// Generate a random number between 1 and 100
var randomNumber = (Math.random() * 100) + 1;
// Select the element to display
var selectedElement = $('.item');
// Display the element only when the random number is 1
if(randomNumber == 1) selectedElement.show(); 

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

I'm a beginner when it comes to Android WebView and incorporating JavaScript into my projects

Struggling to make my Android app work with JavaScript, even though I've enabled it. Despite all the research I've done suggesting it should work, it's not. Any assistance would be greatly appreciated. Below is my Java code: protected ...

Tips for altering the currently active tab in a separate window using a browser extension?

I'm currently working on developing a Firefox Extension and I'm facing a challenge. I'm trying to navigate to a specific browser tab in a different window. After reading through the Firefox Browser Extensions API documentation, I learned tha ...

A guide on transferring variables to sessions instead of passing them through the URL in PHP

<a class='okok' id='$file' href='" . $_SERVER['PHP_SELF'] . "?file=" . $file . "'>$file</a> The given code snippet represents a hyperlink that passes the filename to the 'file' variable, which ...

Angularjs directive: independent scope and encapsulated elements

Why aren't the contained/child elements rendering when using an isolated scope? I suspect that the parent is not rendered yet. I tried adding a $timeout, but still no luck. If I remove the isolated scope by commenting out scope: {}, it works. How c ...

Most effective method for converting a table of data to TypeScript

Searching for an effective method to map a table of enum (or interface) data to the correct location. https://i.sstatic.net/5hF2q.png For instance, Smoke Sensor - Push Button can only be linked to SS - PI SYMBOL and Smoke Sensor - PushButton can only be ...

Sending a post request in AngularJS using the $resource API

As a beginner in angularjs, I am working on creating a login form that connects to a REST API URL when the user submits the form. http://XXX/XXX/index.php/report/login/format/json Using PostMan REST client to configure the URL works fine! However, when ...

Steps for creating a dynamic progress bar with inverted text style using only CSS

I am working on creating a dynamic progress bar with inverted text color using only CSS. To see examples of what I am trying to achieve, you can refer to the following links. Inverted Colors CSS progress bar CSS Progress Bars https://i.sstatic.net/VSs5 ...

Angular promise not accurately retrieving data from JSON API

Last Updated: 02/12/2015 After reading through the comments, I discovered that the issue stemmed from an Angular module modifying the object. By using toJSON, I was able to pinpoint the problem. I recently encountered a perplexing issue. I have a service ...

Querying the height of an image element using jQuery and dynamically adding padding if necessary

I've got a Bootstrap carousel displaying images with different heights, and I'm looking to vertically center these images. My approach involves determining the image height, subtracting it from a fixed height value, and if the result is less than ...

Unable to locate the specified parameters and keyword arguments for the 'ratio' function in reverse

An exception was encountered while attempting to render: django.urls.exceptions.NoReverseMatch: Reverse for 'ratio' with arguments '('',)' not found. 1 pattern(s) tried: ['dashboards/ratio'] This is the views.py co ...

React: When mapping an array of state objects, not all states are displayed

I'm encountering an odd problem while using React. I'm currently developing a budget tracking app that includes a total budget, a form to add new expenses, and displaying those expenses with their costs below. The cost of the new expense will als ...

How to leverage onpopstate in Vuejs without relying on vue-router

I am currently utilizing vue.js in conjunction with laravel, specifically incorporating a vue component within a laravel blade file. My aim is to trigger a page reload upon pressing the back navigation button to return to the previous page. The code I have ...

Unable to trigger onActivated in Quasar (Vue 3) component

I can't seem to get the onActivated function in Vue 3 to trigger, even though I've implemented it before successfully. It's puzzling me as nothing seems to be happening. Currently, I'm using Vue version 3.0.0. Here is a snippet of my co ...

Recursively mirroring the contents of a webpage following the execution of JavaScript code

My goal is to recursively mirror a webpage, meaning I want to retrieve all pages within that webpage. Since all the webpages are located in subfolders of one main folder, I thought I could easily accomplish this using wget: wget --mirror --recursive --pag ...

What could be causing the dysfunction of the jQuery class adding function?

I'm new to using jQuery and I'm trying to add a class to the 'a' tag when the 'li' tag is clicked. However, it doesn't seem to be working as expected. $('.nav-item').click( function() { $(".nav-item a").re ...

Establishing connections to numerous databases using ArangoDB

I am currently developing a product that involves the dynamic creation of a new database for each project, as new teams will be creating new projects based on their specific needs. The backend of the product is built using Node.js, Express.js, TypeScript, ...

Encountering an issue with React Router v6 where calling `history.push('/')` results in an error of "undefined (reading 'pathname')" - the URL changes, but the page remains unchanged

Having an issue altering the page within a Redux Thunk action creator to redirect the user back to the homepage after form submission Although the URL changes when the action creator is triggered, the page itself remains the same Unable to utilize Browse ...

What is the process for changing the color of a button upon clicking with bootstrap?

Is there a way to specifically change the color of a button in Bootstrap when it is clicked? I have multiple buttons and only want the one that is clicked to change its color. Any help would be appreciated. Thanks! ...

What is the best way to reference an Angular constant within a Gulp configuration file?

Is it possible to retrieve an Angular constant within a Gulp file? For example: angular.module('app').constant('env', { url: 'http://localhost:1337/' }); What is the method for accessing this constant inside a function ...

Interested in using jQuery to trigger the f12 key press?

In my current project, I have successfully disabled the f12 and right click using jQuery. Here is the code snippet: $(document).keydown(function(event){ if(event.keyCode==123){ return false; } else if(event.ctrlKey && event.shiftKey && ...