Avoid displaying the identical div through consecutive random fade-ins and fade-outs

I'm trying to make a JavaScript function that selects a random div from a list of divs, displays it for a few seconds, fades it out, and repeats this process in a loop. The issue I'm facing is that sometimes the same div is selected consecutively. I want to avoid this by ensuring that all divs are processed in a random order before starting a new round. For example, div number 5 should not be shown immediately after being displayed.

Below is the current JavaScript code:

var myVar;

function showDiv() {
  var random = Math.floor(Math.random() * $('.notification').length);
  $('.notification').eq(random).prependTo('.container').fadeIn(200).delay(3000).fadeOut(200);
  createRandomInterval();
}

function createRandomInterval() {
  setTimeout(showDiv, 500 + Math.random() * 4000);
}
$(document).ready(function() {
  createRandomInterval();
});

You can view the complete fiddle here: https://jsfiddle.net/brapbg1h/

Answer №1

To optimize the process, I would suggest storing the previous result and reprocessing if it lands on the same one again.

Here is a sample implementation:

let previousResult = -1;

function retrieveRandom() {
  const result = Math.floor(Math.random() * $('.message').length);
  return result === previousResult ? retrieveRandom() : result;
}

function displayMessage() {
  let randomIndex = retrieveRandom();
  previousResult = randomIndex;
  $('.message').eq(randomIndex).prependTo('.box').fadeIn(200).delay(3000).fadeOut(200);
}

Answer №2

Store the value of random in a global variable called lastDiv. Compare random with lastDiv, and if they match, run the function again.

var lastDiv;

function showDiv() {
 
  var random = Math.floor(Math.random() * $('.notification').length);
  
  if(random == lastDiv) {
    console.log('random matches lastDiv, re-running.');
    return showDiv();
  }
  
  lastDiv = random;
  
  $('.notification').eq(random).prependTo('.container').fadeIn(200).delay(3000).fadeOut(200);
  createRandomInterval();
}

function createRandomInterval() {
  setTimeout(showDiv, 500 + Math.random() * 4000);
}
$(document).ready(function() {
  createRandomInterval();
});
.notification {
  width: 200px;
  height: 50px;
  background-color: yellow;
  border: 1px solid rgba(0, 0, 0, 0.2);
  margin-bottom: 5px;
  text-align: center;
  padding-top: 20px;
  display: none;
  /* initially hide to enable fadeIn() and fadeOut() effects */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="container">
  <div class="notification">1</div>
  <div class="notification">2</div>
  <div class="notification">3</div>
  <div class="notification">4</div>
</div>

Answer №3

Store the Previous Div in a Variable

To ensure that consecutive divs are not the same, you can save the number of the previous div in a variable. If this number matches the current selection, simply rerun the function within a do..while loop.

var randomNumber;

function displayDiv() {
    do {
        var randomNumber = Math.floor(Math.random() * $('.notification').length);
    } while(randomNumber == previousDivIndex);
  
    $('.notification').eq(randomNumber).prependTo('.container').fadeIn(200).delay(3000).fadeOut(200);
    createRandomInterval();

    var previousDivIndex = randomNumber;
}

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

Having trouble with a basic node.js server test - no results being shown

I am a beginner in the world of node.js and I'm curious about the most effective way to test this type of code. Currently, I have all the code in one file within a netbeans node.js project. Despite having no errors during compilation, I am not receivi ...

Creating a radial progress chart using Plotly JavaScript

I recently started working with the Plotly library and now I need to display a circular progress graph in Vuejs 2, like the one shown below. While Plotly is a comprehensive tool, I have not come across an example that matches this specific design using Ja ...

Learn the steps for showcasing user information in a tabular layout by utilizing session management with node.js, react.js, and SQL

This view page redirects users to their details Hello everyone, I am currently working on a project that includes two forms: login and user details. When a user logs in and fills out the details form, they should be redirected to a view page where they ca ...

Guide to vertically aligning text within a row using Bootstrap 5

I am currently struggling to achieve vertical alignment of text in the center of a row. Despite my efforts, I have not been successful in achieving the desired vertical alignment. What steps can be taken to ensure that the text is vertically centered with ...

Pause file uploads, display modal popup, then resume uploading

Is there a way to pause file uploading in order to display file requirements before proceeding? For example, when a user clicks on "upload file", I would like to show them a modal window with details about the file they need to upload. Once they click ok, ...

What happens when we add Cookies and JavaScript together? Let's find out with

Just diving into the world of jQuery and working on a cookie script conundrum. My cookieA currently holds no value - it's null. The goal is that every time a button is clicked, the value of cookieA should increase by 10. Click it again, and it should ...

Guide on adding a post type via the command line: Issue encountered - Anticipated POST console HTML error

Facing Error: EXPECTED POST in JQuery Ajax Call Encountering the same issue as mentioned in the provided link. The need is to switch from GET to POST, but direct alteration of ajax code is not feasible. It must be done dynamically using JavaScript through ...

Web page layout featuring fields set aside for completion with underlined formatting

As I work on an HTML document, I encounter a challenge with styling fields that need to be dynamically filled and underlined. Here is what I am aiming to achieve: "Applicant's Last Name:_________bar_____________ First Name:_________foo_____________" ...

Is it feasible to make Twitter's Typeahead plugin have an initial slide down or fade in effect?

Does anyone have an easy way to make the dropdown from Twitter's typeahead jQuery plugin initially slide down or fade in? I'm trying to animate the size of the dropdown menu when it adjusts, but even a simple fade or slide in would be fine. I pre ...

Incorporating new elements into a slideshow using jQuery post-load event

I'm currently utilizing the nivoSlider plugin to generate a slideshow effect on a webpage. Right now, as the page loads, a php script randomly selects 5 images to cycle through. The images to be used are contained within a div like this: <div id= ...

Unable to locate the JSON file in the req.body after sending it through an HTTP post request

I have been working on implementing a new feature in my application that involves passing a JSON file from an Angular frontend to a Node backend using Express. The initial code reference can be found at How do I write a JSON object to file via Node server? ...

Approval still pending, awaiting response

Encountering an issue with a POST request using React and Express, where the request gets stuck in the middleware. I am utilizing CRA for the front end and Express JS for the backend. Seeking advice on troubleshooting this problem. Backend server.js var ...

A challenge in web design: tackling cross-browser color discrepancies

I have implemented CSS code in an HTML page to define the color values of H1 and H2 elements. <style type="text/css"> img {border-style: none;} H1 {color: "#33CCFF"} H2 {color: "#33CCFF"} </style> While this setup works well on Internet Explo ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...

Is there a way to shift this modal to the right?

I am facing an issue with aligning a button modal to the right side. I attempted using bootstrap classes like : float:right, mt:20 Unfortunately, these did not have the desired effect. Below is my code snippet: <b-modal ref="my-modal" hide-fo ...

Loop through the array only if the property exists to avoid encountering the 'cannot iterate over undefined' error

Here's a code snippet that I'd like to simplify: if (this.props.fk_data) { if (this.props.fk_data.length > 0) { for (let fk_dataset of this.props.fk_data) { } } } I'm considering putting this.props.fk_data into st ...

Enhance the functionality of Javascript Promise.then by allowing the argument function to accept an extra parameter

In my code, I am currently utilizing ES6 Promise as shown below: const ctx = {} Promise.resolve() .then(() => doSomethingWith(ctx)) .then((retValue) => doSomethingElseWith(retValue, ctx)) I wish to achieve something like this: const ctx = {} u ...

How to prevent labels from overlapping textboxes when the labels are lengthy using CSS

I am having an issue with an asp control that renders as a text area. I have applied some CSS to style it, but I am facing a problem where a long label is overlapping the textbox. Is there any CSS I can add to push the textbox down if the label gets too lo ...

Is your preference selecting made a breeze by dragging the input field?

Looking to create a form that allows users to indicate their preference between Option A and Option B by dragging a slider. I know there must be a library out there that already does this, but I can't seem to figure out what it's called to searc ...

Botkit corner flaw

I'm having trouble updating a dependent package included in Botkit. When I run npm install on the package.json provided below, Npm alerts me that the hoek package is vulnerable. I attempted to resolve this by running npm audit fix but it did not wor ...