Choose an element at random

I am trying to figure out how to select all div elements with the same class of "dot" under a parent div in JavaScript. Here is an example structure:

<div id="dots">
   <div class="dot"> . </div>
   <div class="dot"> . </div>
   <div class="dot"> . </div>
   ...
   <div class="dot"> . </div>
</div>

My goal is to apply a certain class to a random element with the class "dot" every 5 seconds using JavaScript. Can someone help me with this?

randomElement.addClass('someClass');

Answer №1

To start, you will need to first select all the dots, then during each periodic activation cycle, remove the previously set class and assign it again to a random element within the specified range of 0 to dots count - 1.

Here is a demonstration:

var $dots = $('#dots .dot');

function activate() {
    $dots.removeClass('active')
         .eq([Math.floor(Math.random()*$dots.length)])
         .addClass('active');
setTimeout(activate, 1000);
}

activate();
#dots .dot {
    display: inline-block;
    height: 50px;
    width: 50px;
    background: coral;
    border-radius: 50%;
    opacity: 0.2;
    transition: opacity .3s ease;
}
#dots .dot.active {opacity: 1;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="dots">
   <div class="dot"></div>
   <div class="dot"></div>
   <div class="dot"></div>
   <div class="dot"></div>
   <div class="dot"></div>
</div>

Answer №2

What do you think of this solution?

function applyStyleToRandomDot() {
    var dotElements = document.getElementsByClassName('dot');
    var totalDots = dotElements.length;
    var randomIndex = Math.floor(Math.random() * totalDots) + 1;
    var randomDot = dotElements[randomIndex];
    randomDot.classList.add('newStyle');
}

setInterval(function(){
    applyStyleToRandomDot();
},5000);

Answer №3

Here is another unique approach that is straightforward to grasp.

DEMO

var numberOfDots = $(".dot").length;
setInterval(function () {
    $(".dot").removeClass("someClass");
    var x = Math.floor((Math.random() * numberOfDots) + 1);
    $(".dot:nth-child(" + x + ")").addClass("someClass");
}, 5000);
.someClass
{
    background:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="dots">
    <div class="dot">.</div>
    <div class="dot">.</div>
    <div class="dot">.</div>...
    <div class="dot">.</div>
</div>

Answer №4

Outlined below is an iteration across all elements:

  1. Iterate through each element
  2. Assign a class to random elements
  3. Remove those elements from the iteration list

var elements = document.getElementsByClassName("dot");


setInterval(function() {
  var random = Math.floor(Math.random() * elements.length);
  elements[random].className += " extra";
  delete elements[random];
}, 1000);
//change 1000 to 5000. This is the interval speed in milisec.
.extra {
  font-size: 200%;
  background-color: cornflowerblue;
  width: 50px;
}
<div class="container">
  <div class="dot">Test</div>
  <div class="dot">Test</div>
  <div class="dot">Test</div>
  <div class="dot">Test</div>
</div>

Answer №5

I believe the solution below should meet your needs:

window.randomNumber = 0;
setInterval(function(){
    if(randomNumber) $(".dot:eq("+ randomNumber +")").toggleClass("randomcss");
    window.randomNumber = Math.floor((Math.random() * $(".dot").length) + 1);
$(".dot:eq("+ randomNumber +")").toggleClass("randomcss");
},1000);
.randomcss {
    background : yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dots">
   <div class="dot"> . </div>
   <div class="dot"> . </div>
   <div class="dot"> . </div>
   <div class="dot"> . </div>
     <div class="dot"> . </div>
   <div class="dot"> . </div>
   <div class="dot"> . </div>
     <div class="dot"> . </div>
   <div class="dot"> . </div>
   <div class="dot"> . </div>
     <div class="dot"> . </div>
   <div class="dot"> . </div>
   <div class="dot"> . </div>
</div>

http://jsfiddle.net/kishoresahas/7qgvru5p/

Answer №6

Here's an alternative approach:

function changeColor(){
  var randomNum = getRandomNumber(0, $(".dot:not(.newStyle)").length -1);
  $($(".dot:not(.newStyle)")[randomNum]).addClass('newStyle');
}

function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


setInterval(function(){
    changeColor();
},3000);
.newStyle{background-color:green;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dot">apple</div>
<div class="dot">orange</div>
<div class="dot">banana</div>
<div class="dot">grape</div>
<div class="dot">mango</div>
<div class="dot">peach</div>

Answer №7

When working with jQuery, you may want to attempt the code snippet below:

selectedItems = jQuery("ul li").get().sort(function(){ 
  return Math.round(Math.random())-0.5
}).slice(0,10)

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

Important notice: It is not possible to assign refs to function components. Any attempt to do so will result in failure. If you intended to assign a ref, consider

My console is showing a warning when I use the nextJs Link component. Can someone assist me in resolving this issue and providing an explanation? Here is the message from the console: https://i.stack.imgur.com/jY4FA.png Below is a snippet of my code: im ...

Copy and paste content from Outlook, Word, or any Office software directly into the embedded browser

Our application is performing well, but there is an issue with some users copying text to Word before pasting it into the app. The HTML gets parsed out somewhat correctly, but it often includes tags from outlook or word that our XHTML engine doesn't r ...

What is the best way to eliminate duplicate values from an Array in ReactJS?

Hi there, I'm new to JavaScript and React. I need some help with a project I found on the React blog. I want to try solving it in my own way. This is the content of todoList.js: const todoList = [ {category: 'Sporting Goods', price: &a ...

Tips for avoiding background-image zoom on mobile browsers when stacking elements vertically:

Within my ReactJS application, I have implemented a feature where elements are added vertically from top to bottom when the "Post" button is clicked. https://i.sstatic.net/KwPYV.jpg These elements display correctly on both mobile and desktop browsers. Ho ...

Is it important that the end date does not exceed the start date?

In my request, the end date cannot be later than the start date. For example, if the start date is 24/4/2017 and the end date is 23/4/2017, the search function should be disabled for the calendar date 23/4/2017. Only dates from 24/4/2017 onwards should be ...

What is the best way to switch between light and dark themes with the ability to locally store the current theme?

Being new to the realm of react, I have been delving into the implementation of new features using Material-UI. One particular feature I am working on involves toggling between light and dark themes, with the current theme being stored locally within the b ...

Master the Art of Crafting Unique URLs

I am developing a web page that requires me to call two queries, each requiring an ID. However, I'm unsure of the best way to pass these IDs in the URL. For instance, one query is for books and the other is for authors. Currently, I have considered tw ...

The functionality of display flex is not functioning as expected outside of the CodePen

I attempted to create a responsive two-column layout on Codepen with success. The layout is quite simple, featuring a YouTube video and some text. However, when I tried to transfer this to my website, it failed to work... Here is the code – hoping someo ...

The element fails to receive the class when it is being clicked

Currently, I am in the process of developing a Joomla website and I am working on implementing an accordion feature for the category descriptions based on the placement of H3 headings in the WYSIWYG editor. Here is the basic function I have so far (althou ...

Basic application - angular has not been declared

I'm currently diving into the realm of javascript and angularjs, following along with the tutorials on . After setting up a basic IntelliJ javascript project, I created two essential files: index.html <!DOCTYPE html> <html lang="en"> ...

Prevent ui-select from being highlighted when clicked

here's a dilemma : (all in angular 1) I'm using a ui-select like this : https://i.stack.imgur.com/RzH2u.png Here's the code snippet : <div class="formZone-group"> <div class="mandatory-fl"> <div class="man ...

The process of rendering a form eliminates the classes that were previously added by J

I am in the process of redesigning a web application and need to incorporate responsive design into the existing UI. My plan is to include col-* classes on specific html elements, such as tables: function addColstoTableCells() { $('table tr.form ...

Using Nextjs Image as the Background for Layout

I have a question regarding implementing a common background image for all pages in my app. Currently, I have the main page.js code that displays an image as the background using Next Image component. However, I would like this background to be present thr ...

Location of Ajax callback function

I encountered an issue with a callback function that was placed within $(document).ready. The callback function wasn't functioning as expected. Surprisingly, when I moved it outside of $(document).ready, the code started working flawlessly. I am puzzl ...

Adjust CSS classes as user scrolls using skrollr

I am currently facing an issue with the prinzhorn/skrollr plugin when trying to use removeClass/addClass on scroll function. I have attempted to find a solution but unfortunately, nothing has worked for me. <li class="tab col s3"><a data-800="@cl ...

Tips for dynamically displaying a Material UI dialog with smooth fade effects

I am currently developing a basic application that lists users. Whenever I click on a user, I want to display a dialog box with specific information about that user. I have attempted to achieve this using Material UI's Dialog component in different wa ...

Checking connectivity in an Ionic application

Within my Ionic application, I am faced with the task of executing specific actions depending on whether the user is currently connected to the internet or not. I plan on utilizing the $cordovaNetwork plugin to determine the connectivity status within the ...

Using Python's Beautiful Soup library to retrieve text from h1 and id tags

I've been attempting to retrieve the text from an HTML id called "itemSummaryPrice," but I'm having trouble figuring it out. html = "" <div id="itemSummaryContainer" class="content"> <div id=&quo ...

What is the best method for checking for JavaScript errors when using Selenium WebDriver in conjunction with NodeJS?

When it comes to coding in JavaScript, not Java, my focus is on running a specific website like foo.com. I typically set it up as follows: var webdriver = require("selenium-webdriver"); By = webdriver.By, until = webdriver.until; var chrome = req ...

How to access and retrieve selected checkbox values using jQuery

<form id="myform"> <input type='checkbox' name='foo[]' value='1'> <input type='checkbox' name='foo[]' checked='true' value='2' > <input type='checkbox' ...