Gradually appear/disappear div element with a delay added

Storing divs in an array and deleting them after appending is my current method.

Now, I'm looking to incorporate a fade-in and fade-out effect on each div with a delay.

Check out this code snippet :

var arr = $(".notification");

function display(){
    let rand = Math.floor(Math.random() * arr.length)
    $("#result").append(arr.eq(rand))
    arr = arr.not(":eq("+rand+")")
    if(arr.length>0) createRandomInterval();
}



function createRandomInterval() {
    setTimeout(display, 500 + Math.random() * 4000);
}
createRandomInterval()
.notification {
  background-color: red;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  width: 200px;
  margin-bottom: 10px;
}

.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hidden">
  <div class="notification">object 1</div>
  <div class="notification">object 2</div>
  <div class="notification">object 3</div>
  <div class="notification">object 4</div>
</div>
<div id="result"></div>

I attempted to include

.fadeIn(400).delay(3000).fadeOut(400);

in my function, but all divs fade in and out simultaneously.

My goal is for each div, upon appending, to fade in and then fade out after 3 seconds.

Here's my fiddle without the animation: https://jsfiddle.net/0ydo3kvd/

Answer №1

To begin with, you must hide your .notification in the result div by setting it to display: none. After adding each one to the result div, simply change the display to flex and then apply a chain of fade, delay, and fadeOut effects.

Check out the functional code snippet below:

var arr = $(".notification");

function display(){
    let rand = Math.floor(Math.random() * arr.length)
    let notfi = arr.eq(rand);
    $("#result").append(notfi);
    notfi.css("display","flex").fadeIn(400).delay(3000).fadeOut(400);
    arr = arr.not(":eq("+rand+")")
    
    if(arr.length>0) createRandomInterval();
}

function createRandomInterval() {
    setTimeout(display, 500 + Math.random() * 4000);
}
createRandomInterval()
.notification {
  background-color: red;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  width: 200px;
  margin-bottom: 10px;
}

.hidden {
  display: none;
}

#result .notification {
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hidden">
  <div class="notification">object 1</div>
  <div class="notification">object 2</div>
  <div class="notification">object 3</div>
  <div class="notification">object 4</div>
</div>
<div id="result"></div>

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

Using Ajax to return a Post type in c# mvc 4 instead of a value

Hey there, I seem to be encountering an issue that I could use some help with. $.ajax({ type: "POST", url: "/controller/CreateList", contentType: "application/json; charset=utf-8", traditional: true, ...

Ensure that the height of the content in JQuery Mobile is set to 100

I'm currently working on an app using JQuery Mobile. Check out this link for my HTML code. There's a full-screen <iframe> within my page. Even though I've specified width:100%; height:100%; border:0% for the iframe, it ends up being ...

Numpad functionality in JQuery malfunctioning post-ajax request

Using the jQuery numpad plugin has been flawless until after an AJAX call. I have tried various functions like on('click') and others, but unfortunately, none of them worked as expected. Apologies for my poor English! You can find the extension l ...

Dealing with JSON Stringify and parsing errors in AJAX

I've been troubleshooting this issue for hours, trying various suggestions found online, but I'm still encountering a problem. Whenever I encode function parameters using JSON.stringify and send them to my PHP handler through AJAX, I receive a pa ...

What is the best way to simulate global variables that are declared in a separate file?

dataConfiguration.js var userData = { URIs: { APIURI: "C" }, EncryptedToken: "D" }; configSetup.js config.set({ basePath: '', files:['dataConfiguration.js' ], ..... UserComponentDetails: .....some i ...

Retrieving Angular URL Parameters Containing Slashes

I'm currently in the process of developing a single page angular application. This app retrieves a token from the URL and then sends it to an API. At the moment, my URL structure is as follows: www.example.com/?token=3d2b9bc55a85b641ce867edaac8a9791 ...

Using jQuery to make an element follow you as you scroll down a page inside a div

I've made some progress on my code: HTML <div id="header"></div> <div id="content"> <div class="sidebar-wrapper"></div> </div> <div class="session-wrapper"></div> <div id="footer"></div> ...

Do not procrastinate when updating the navbar elements while navigating through pages

This specific NextJS code is designed to alter the color of the Navbar elements once scrolling reaches 950px from the top or when navigating to a different page that includes the Navbar. Strangely, there seems to be a delay in updating the Navbar colors wh ...

Transferring information from template to associated component

Is it possible to transfer data from a template to a component without the need for an event trigger like a button or form submission? For instance, in the code snippet provided, how can we pass the 'item' from the 'items' array to the ...

What sets apart jQuery.ajax's dataType="json" from using JSON.parse() for parsing JSON data?

What is the difference between using dataType='json' and parsing response with JSON.parse(response) in jQuery Ajax? $.ajax({ url: path, type: 'POST', dataType: 'json', data: { block ...

Creating a prompt within a while loop

Issue with the code is that it should only progress if the user inputs "rock", "paper" or "scissors". However, after re-entering any input the second time, it still moves on despite passing the condition in the while loop. For instance, entering "asdf" p ...

Automatically resetting the Redux toolkit store when navigating between pages in Next.js

I am a new Next user who has been using Redux with React for a while. However, I encountered many challenges when trying to integrate Redux with Next. I have decided to move on from this solution. store.js import { configureStore } from '@reduxjs/to ...

The displayed database results will appear in the opposite order of what was originally assigned for both inline and block elements

I have a database with information that I am trying to display using a while loop. My goal is to show the results in this format... Firstname Lastname - Firstname Lastname - Firstname Lastname player1 ---------------player1-----------------------pla ...

If the input is unmounted in react-hook-form, the values from the first form may disappear

My form is divided into two parts: the first part collects firstName, lastName, and profilePhoto, while the second part collects email, password, confirmPassword, etc. However, when the user fills out the first part of the form and clicks "next", the val ...

Create a PHP file with various functions and access them using jquery.post or jquery.get in a separate JavaScript file

Is there a way to call multiple PHP functions from my JavaScript file using Jquery.post? Typically, we use Jquery.post to call a PHP file and pass various values as post data. function new_user(auth_type, tr_id, user_name, email) { $.post("bookmark.p ...

`Is it common to use defined variables from `.env` files in Next.js applications?`

Next.js allows us to utilize environment variable files such as .env.development and .env.production for configuring the application. These files can be filled with necessary environment variables like: NEXT_PUBLIC_API_ENDPOINT="https://some.api.url/a ...

Error 500 in WordPress Child Theme due to AJAX Internal Issue

I have encountered an issue with my Ajax code in the Js/Jq block (/buscador/menuLateral/menu-libros.php): $.ajax({ url: '<?= get_stylesheet_directory_uri(); ?>' + '/buscador/buscador-functions.php', type: 'POST' ...

What is the best method to send a HTTP request (specifically for scraping) to an Angular2 website?

I am attempting to utilize a node server to extract data from an angular2 application. However, the issue I am encountering is that the response I receive is just the index.js file, which essentially represents the "loading..." section of the webpage. My ...

Adding rows to a database can be done by utilizing a dynamic form that consists of both repeatable and unique fields

Here is my follow-up post addressing the issue I previously encountered. Initially, I erroneously used mysql instead of mysqli, but I have now made the necessary updates based on recommendations. I have a form that contains variable sets of fields (rangin ...

What is the method to individually determine "true" or "false" using .map() in coding

I am faced with an array of data that needs to be manipulated individually, but it should still function as a cohesive unit. Can you assist me in achieving this? function OrganizeFollow() { const [followStatus, setFollowStatus] = useState([]); co ...