Is there a way for me to programmatically remove a user-inputted paragraph in JavaScript after a delay of 2 seconds

Recently, I mastered the art of creating a to-do list using JavaScript. As a fun personal project, I decided to implement this knowledge in creating a "Share Your Secret" website. The concept is simple: users can share their secrets anonymously on the platform.

const mytext = document.getElementById('mytext');
const btn = document.getElementById('btn');
const items = document.getElementById('items');

btn.addEventListener('click', function(e){
  e.preventDefault();
  const paragraph = document.createElement('p');
  paragraph.classList.add("item");
  paragraph.innerText = mytext.value;
  items.appendChild(paragraph);
  mytext.value = '';
 
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  background-color: rgb(231, 237, 241);
}
main {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 10%;
  font-family: "Source Sans Pro", sans-serif;
}
h2 {
  color: rgb(71, 80, 102);
  font-size: 40px;
  margin-bottom: 30px;
}
.myform {
  display: flex;
  justify-content: center;
  align-items: center;
}
#btn {
  margin-left: 10px;
  width: 40px;
  height: 100px;
  white-space: pre-line;
  text-align: center;
  font-size: 15px;
  font-weight: 600;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  box-shadow: 2px 2px rgb(184, 182, 182);
  color: rgb(35, 70, 136);
}
#btn:active {
  color: rgb(48, 95, 182);
  box-shadow: 0 0 2px grey;
}

#mytext {
  background-color: aliceblue;
  border-radius: 10px;
  border: none;
  padding: 7px;
  box-shadow: 1px 1px rgb(200, 207, 212);
  outline: none;
}
.items {
  border-radius: 5px;
  font-family: cursive;
  color: rgb(61, 61, 60);
  width: 400px;
  display: flex;
  justify-content: center;
  margin-top: 10px;
  padding: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=MedievalSharp&display=swap" rel="stylesheet">
  <link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@200;300;400;600;700;900&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="./styles.css">
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE-edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
<main>
  <h2>Write Your Secret</h2>
  <div class="container">
    <form class="myform" action="">
      <textarea name="text" id="mytext" cols="30" rows="10" placeholder="Write Whatever You Wish"></textarea>
      <button id="btn">S
        h
        a
        r
        e</button>
    </form>
    <div class="items" id="items"></div>
  </div>
  
</main>

  <script src="./app.js"></script>
</body>
</html>

In the to-do app example, when a user enters something in the input box, their secret gets displayed on the screen. However, for my "Share Your Secret" website, I have a specific requirement - any shared secret should disappear automatically after 2 seconds. This adds a level of mystery and anonymity to the platform. Initially, I just want the secrets to vanish quickly, similar to how ink vanishes in the Harry Potter movies from Tom Riddle's diary. The visual effect is secondary; the primary goal is to make the secrets disappear after 2 seconds.

Answer №1

By simply inserting the following code snippet:

setTimeout(() => paragraph.classList.add("hidden"), 2000)

You can achieve your desired effect by adding the "hidden" class after a 2-second delay. The class hidden can be customized to hide elements based on your preferences, including setting visibility to hidden, or implementing transition effects like the one described below:

.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 2s, opacity 2s linear;
}

If you opt for a transition as demonstrated above, you can incorporate the following line to remove the element once the transition is complete:

paragraph.addEventListener('transitionend',() => paragraph.remove())

See the live example provided below for a better understanding.

const mytext = document.getElementById('mytext');
const btn = document.getElementById('btn');
const items = document.getElementById('items');

btn.addEventListener('click', function(e){
  e.preventDefault();
  const paragraph = document.createElement('p');
  paragraph.classList.add("item");
  paragraph.innerText = mytext.value;
  items.appendChild(paragraph);
  mytext.value = '';

  paragraph.addEventListener('transitionend',() => paragraph.remove())
  setTimeout(() => paragraph.classList.add("hidden"), 2000)
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  background-color: rgb(231, 237, 241);
}
main {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 10%%;
  font-family: "Source Sans Pro", sans-serif;
}
h2 {
  color: rgb(71, 80, 102);
  font-size: 40px;
  margin-bottom: 30px;
}
.myform {
  display: flex;
  justify-content: center;
  align-items: center;
}
#btn {
  margin-left: 10px;
  width: 40px;
  height: 100px;
  white-space: pre-line;
  text-align: center;
  font-size: 15px;
  font-weight: 600;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  box-shadow: 2px 2px rgb(184, 182, 182);
  color: rgb(35, 70, 136);
}
#btn:active {
  color: rgb(48, 95, 182);
  box-shadow: 0 0 2px grey;
}

#mytext {
  background-color: aliceblue;
  border-radius: 10px;
  border: none;
  padding: 7px;
  box-shadow: 1px 1px rgb(200, 207, 212);
  outline: none;
}
.items {
  border-radius: 5px;
  font-family: cursive;
  color: rgb(61, 61, 60);
  width: 400px;
  display: flex;
  justify-content: center;
  margin-top: 10px;
  padding: 5px;
}

.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 2s, opacity 2s linear;
}
<main>
  <h2>Write Your Secret</h2>
  <div class="container">
    <form class="myform" action="">
      <textarea name="text" id="mytext" cols="30" rows="10" placeholder="Write Whatever You Wish"></textarea>
      <button id="btn">S
        h
        a
        r
        e</button>
    </form>
    <div class="items" id="items"></div>
  </div>

</main>

Answer №2

 const button = document.getElementById('button');
 const list = document.getElementById('list');

 const cleanInput = () => {
    setInterval(function(){textInput.value = ''; }, 2000);
 }

button.addEventListener('click', function(event){
  event.preventDefault();
  const listItem = document.createElement('p');
  listItem.classList.add("item");
  listItem.innerText = textInput.value;
  list.appendChild(listItem);
  textInput.value = ''; 
});

cleanInput()

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

Provide spacing on the sides for a background position

Is there a way to evenly space my background image with 10px margins on all sides instead of just the left side? Currently, it's only working on the left side. .login-page { display: flex; flex-direction: column; background: url("../src/As ...

Repositioning singular particles within a Three.JS particle array

Having an issue with my Three.js project. I've been working on a particle system and trying to animate particles as the frames are rendered. However, I'm running into a problem where the particles aren't moving at all. The code snippet I use ...

In what way is the background-color of WindowInfoBackground utilized?

I attempted to implement background-color : WindowInfoBackground;. The property background-color : WindowInfoBackground; allows for the assignment of the system color to the background-color attribute. Despite using this particular value, the backgroun ...

Is there a way to adjust the width of my editor file in vscode to prevent the need for horizontal scrolling when reading a paragraph to the end?

My lorem ipsum text in vscode is displaying as one long line, forcing me to scroll horizontally instead of seeing it formatted into paragraphs. https://i.stack.imgur.com/LIja8.png Is there a way to adjust the width of the editor box to prevent the need f ...

What is the best way to align images to the right while also centering them in relation to each other?

Here is the current code snippet: <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <div class="row"> <div class="col-sm bg-primary"> One ...

Ways to prevent the need for multiple if/else statements and repetitious function instances

Check out this code snippet in Javascript: https://pastebin.com/zgJdYhzN. The purpose of the code is to fade in text when scrolling reaches a specific point. While it does work, I want to optimize it for multiple pages without creating separate instances ...

Only the box that I click on will receive the applied color

I am facing an issue with applying colors to the label colorCheckBox, each with a unique data-id that is derived from the variable colorBoxId, which is globally accessible using colorBoxId = $(this).closest('tr').data('id');. The proble ...

successive ajax requests

I am facing a challenge where I need to execute two separate ajax calls sequentially. The second call relies on the result of the first call for its data. Despite my efforts, I haven't been able to achieve the desired outcome. Here's what I have ...

What is the method used by Bootstrap to create a darker page background behind a modal?

I am struggling to understand how Bootstrap darkens the background of a page when a modal is displayed. Even though a class is added to the body tag (modal-open), the effect on the background isn't clear to me. Learn more about Bootstrap modals here ...

Implementing translation text into a PHP database

<!doctype html> <html> <head> <meta charset="utf-8"> <title>Translate and Save Text</title> </head> <body> <form action="" method="post" name="theform"> <table width="693" border="1" style="table-l ...

Performing various JavaScript functions within a single hyperlink

I've implemented the Tab Content Script by dynamicdrive.com on my website. The script creates tabbed navigation, and I find it to be quite useful. Currently, I am trying to figure out how to make a single link select two tabs at once. Essentially, I ...

What specific bower package is required for implementing the locationProvider functionality in AngularJS?

I've been attempting to remove the hash tag from my URL in AngularJS. After some research, I discovered that I need to use $locationProvider, but I'm unsure which dependency is required to make this work. This is my Angular code: angular.module ...

Searching for hidden elements within a div using a filter option

An accordion is located inside a div and a search box has been added to the div with the intention of serving as a search filter. Some accordion elements are visible within the div while others are hidden. The problem arises when trying to make the filter ...

The iteration of an ajax POST handler, looping endlessly

Attempting to implement a basic ajax submit handler for modifying a form as part of a lesson on CSRF vulnerabilities, but encountering an issue with the page looping. Below is the code snippet being worked on, inspired by http://api.jquery.com/jQuery.post/ ...

Experiencing difficulties installing the MEAN stack

I've been attempting to set up the MEAN stack by following a tutorial on Bossable website. I'm using Webstorm and MongoDB for this installation. Unfortunately, I'm facing some issues and encountering errors. Every time I try to connect to l ...

Utilizing logical operators to assign values to variables in Typescript

export class SearchResult { id: string; constructor(obj?: any) { this.id = obj && obj.id || null; } } Can someone explain to me the meaning of obj && obj.id || null? I'm confused by this syntax. ...

JavaScript causes iPad and iPhone browsers to crash while loading images

I'm currently working on constructing an image gallery in Safari that mirrors the iPad photo app. Everything is functioning smoothly, but once I exceed around 6MB of images either by adding them to the DOM or creating new Image objects, the loading of ...

Vue.js - Testing components with intricate child components

Imagine we have a simple Bootstrap powered HTML form within a custom Vue component named MyForm.vue <template> <form> <div class="form-group"> <label for="email">Email address</label> <input type="email" ...

Is there a way to organize a list of arrays within a loop based on a specific index within each array in JavaScript?

Greetings, I am currently facing an issue with sorting a specific object of arrays. The structure is as follows: Allow me to provide a clearer example - I am receiving a string from an AJAX call formatted like this: "name|price|blah|blah@name|price|blah| ...

`How to Merge Angular Route Parameters?`

In the Angular Material Docs application, path parameters are combined in the following manner: // Combine params from all of the path into a single object. this.params = combineLatest( this._route.pathFromRoot.map(route => route.params) ...