Incorporate Javascript to smoothly transition a div into view, display it for a specified duration, gradually fade it out, and ultimately delete

I am excited to experiment with toast notifications by creating them dynamically. Each toast has a unique id number and I increment a counter every time a new one is created.

The current functionality includes the toast sliding down, staying visible for 3 seconds, and then automatically getting removed from the screen.

var thisToast = this.toastCounter - 1; 
    $(document).find("#toast_" + thisToast).slideDown(500); 
    setTimeout(function() {
      $(document).find("#toast_" + thisToast).remove(); 
    }, 3000);

My goal now is to enhance the toast behavior by making it fade in, stay on display for a specified duration (X seconds), fade out gracefully, and then self-destruct.

An important requirement is that when multiple toast messages are generated, each new one should be positioned below its predecessor for clear visibility.

If you require a comprehensive view of my code implementation, here it is:

CreateToast(isValid) { 
    var toastMessage;
    var foreColor;
    var backgroundColorIconDiv
    var backgroundColorContentDiv;
    var borderColor;

    if (!isValid) {
      toastMessage = "Failure";
      foreColor = "#ff0000";
      backgroundColorIconDiv = "#ff8080";
      backgroundColorContentDiv = "#ff471a";
      borderColor = "#800000";
    } else {
      toastMessage = "Success";
      foreColor = "#2fb62f";
      backgroundColorIconDiv = "#71da71";
      backgroundColorContentDiv = "#00e673";
      borderColor = "#00802b";
    }

    this.CreateWrapper(toastMessage, foreColor, borderColor, backgroundColorIconDiv, backgroundColorContentDiv); 

    this.toastCounter++; 

    var thisToast = this.toastCounter - 1;
    $(document).find("#toast_" + thisToast).slideDown(500);
    setTimeout(function() {
      $(document).find("#toast_" + thisToast).remove();
    }, 3000);
  }

  CreateWrapper(toastMessage, foreColor, borderColor, backgroundColorIconDiv, backgroundColorContentDiv) { 
    var wrapperDiv = document.createElement("div");
    wrapperDiv.id = "toast_" + this.toastCounter;
    wrapperDiv.style.display = "none";
    wrapperDiv.style.margin = "0 auto";
    wrapperDiv.style.width = "200px";
    wrapperDiv.style.height = "50px";
    wrapperDiv.style.border = "2px solid " + borderColor;
    wrapperDiv.style.borderRadius = "10px";
    document.body.appendChild(wrapperDiv);

    this.CreateIconDiv(wrapperDiv, backgroundColorIconDiv);
    this.CreateContentDiv(wrapperDiv, toastMessage, foreColor, backgroundColorContentDiv);
  }

  CreateIconDiv(parentDiv, backgroundColor) { 
    var iconDiv = document.createElement("div");
    iconDiv.style.textAlign = "center";
    iconDiv.style.width = "20%";
    iconDiv.style.cssFloat = "left";
    iconDiv.style.backgroundColor = backgroundColor;
    parentDiv.appendChild(iconDiv);
  }

  CreateContentDiv(parentDiv, toastMessage, foreColor, backgroundColor) { 
    var contentDiv = document.createElement("div");
    contentDiv.style.textAlign = "center";
    contentDiv.style.width = "80%";
    contentDiv.style.cssFloat = "right";
    contentDiv.style.color = foreColor;
    contentDiv.style.backgroundColor = backgroundColor;
    contentDiv.style.fontWeight = "bold";
    contentDiv.style.fontSize = "20px";
    contentDiv.innerHTML = toastMessage;
    parentDiv.appendChild(contentDiv);
  }

Your assistance with this would be greatly appreciated :)

Answer №1

If you wish to achieve a specific result, you can utilize the delay function from jQuery along with the callback of the fadeOut function in the following manner:

$("#toast_" + thisToast)
    .fadeIn(500)                  // fading in (500 ms)
    .delay(3000)                  // 3 seconds delay
    .fadeOut(500, function() {    // fade out effect for 500 ms and then remove the element
        $(this).remove();
    });

Example:

function launch() {
  $("#element").fadeIn(500)
    .delay(3000)
    .fadeOut(500, function() {
      $(this).remove();
    });
}
#element {
  background-color: blue;
  width: 120px;
  height: 60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="launch();">Begin</button>
<div id="element" style="display:none;"></div>

Answer №2

setTimeout(() => {
  $('.test').slideDown();
  
  setTimeout(() => {
    $('.test').slideUp().remove();
  }, 3000);
}, 1000);
.test {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">slide down, stay a while, slide up, remove</div>

Answer №3

I recommend utilizing the lightweight and straightforward ToastMaker library, which is a mere 1KB in size.

$('#mybutton').click(()=>{ToastMaker("This is a toast notification!")});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" type="text/css" href="https://unpkg.com/toastmaker/dist/toastmaker.min.css">

<script type="text/javascript" src="https://unpkg.com/toastmaker/dist/toastmaker.min.js"></script>


<button id="mybutton">Show Toast</button>

Visit this page to explore more examples featuring beautifully styled toast messages

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

Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column: receiptsByDate: function(){ let byDate = _.groupBy(t ...

I have noticed that the baseline of a Span element has shifted after updating my Chrome browser to a version that begins with

Once I updated to chrome Version 108.0.5359.94 (Official Build) (64-bit) from 107.0.5304.87 (Official Build) (64-bit), the behavior of the span element changed drastically. It shifted its baseline when multiple spans were stacked on top of each other. Exp ...

Show whether the day is even or odd with the JavaScript getDay object

I'm currently working on a task where I need to show the text "Even Day" if the day of the month is 2, 4, 6..., and "Odd Day" for days such as 1, 3, 5, and so on. I attempted to achieve this by setting up an array linked to the getDay object, but unfo ...

Tips for checking the validity of PHP variable names, such as $as['abc'], within an HTML textbox

Can anyone assist me with validating a user input PHP variable name such as $as_cap['abc'] during insertion? I need to verify if the format of the variable name is correct or incorrect. Currently, I am using eregi("^[a-z0-9_.'-]{1,50}$") ...

What advantages come from caching the document object for improved performance?

Usually, I cache DOM objects used in a script. However, recently I found myself having to reference the document object within a jQuery wrapper. I started questioning whether caching $(document) is necessary since there's only one document object per ...

Incorporate Security Measures into the Form

I am in the process of setting up a form that requires users to enter a specific password provided by me. The user must input "Password123" into the form before they can submit it to my email. If the password is incorrect, the site will redirect to an erro ...

Semi-Transparent Photo Slideshow

Currently, I am in the process of developing a Pokedex-like feature for a project that I am working on. The functionality is working as expected, but there is one particular feature that I would like to implement. My goal is to display only certain element ...

Unable to locate or modify an item within an array

I have a unique way of organizing my collection, with an array inside. Here's how it looks: const postsSchema = mongoose.Schema({ posts: {type: Array}, }) Now, I want to search for a specific document within this collection. I attempted the follo ...

Challenges faced during the implementation of a personalized transport system in Sentry

Struggling to set up a custom transport for my react app within a UWP container. The fetch API in the UWP environment isn't cooperating with sending events to Sentry, which I discovered after a lengthy debugging session. It appears that the fetch API ...

Ways to style specific dates on a datepicker?

Is there a way to customize the appearance of the first and last selected days in my ui datepicker for booking, similar to the design shown in the image linked below? https://i.sstatic.net/bKnRS.jpg var dateFormat = "DD/MM/YY", ...

The issue arises when the jQuery onchange event stops functioning properly after the initial ajax call

Trying to switch from a frame to a div is causing some issues. After the initial AJAX jQuery call, the onchange event doesn't seem to work. However, it works fine in the frame. When I first load my page and click on the menu, everything seems good. I ...

Utilization of Bootstrap's .container class in various scenarios

As I delve into Bootstrap, the usage of the .container class is provoking some confusion. Most tutorials suggest a structure like this: -.container --.row ---.col- ---.col- However, I came across a different approach in a W3schools example: W3Schools - ...

Ways to address memory leakage issues in Angular

Is there a way to manually optimize the Garbage Collector by forcefully pushing variables into it? For example, if we have a root or global level variable in an Angular component that is no longer needed when switching to another page, how can we ensure it ...

Tips for condensing text using ellipsis and Angular-FlexLayout

I am working on a flex row setup that includes three nested flex rows. Within the second row, I need to display a title that should not be shortened, and a text that should be truncated. Additionally, the first and last row must maintain a fixed width with ...

Storing dropdown values in variables using AJAX and JQuery

In my code snippet, I have the following:- <script> $("#country").on("change", function(){ var selected = $(this).val(); $("#results").html("<div class='alert-box success'><span><img src='images/ ...

The design of the Bootstrap alert button is not working properly as it fails to close when clicked on

While experimenting with Bootstrap, I encountered an issue with the bootstrap alert button that seems to be malfunctioning. I simply copied the code from Bootstrap's official website: https://i.sstatic.net/DRLIg.png However, upon testing it on my pag ...

Is there a similar function to $.ajax for React.js and Angular.js?

Can you guide me on how to send data using both React and Angular? Is there a similar function to $.ajax in React and Angular frameworks? I am looking for a post function that works like the one shown below in both React and Angular: $.ajax{ url:"test.p ...

Is there a way to remove specific mesh elements from a scene in Unity?

When I create multiple mesh objects with the same name, I encounter difficulties in selecting and removing them all from the scene. Despite attempting to traverse the function, I have not been successful in addressing the issue. event.preventDefault(); ...

Can the information from a form be automatically submitted to the server upon selection?

<div class="modal-body modal-body-step-2"> <form action="prenotazioni.php" method="post"> <div class="input-group"> <input type="radio" name="spettacolo" value="Lo Schiaccianoci">Lo Schiaccianoci<br> ...

Use Protractor to simulate Loss Connection by clearing LocalStorage in a Spec

Currently, I am utilizing the code window.localStorage.removeItem("name of localStorage variable you want to remove"); to eliminate two distinct localStorage Keys within a particular specification, and it is successfully removing them. Afterwards, I proce ...