What is the best way to display an alert when the button is clicked repeatedly?

Is it possible to keep displaying the alert every time we click the button, rather than just once after clicking it?

I currently have an alert set to trigger when a button is clicked, but it disappears after 3 seconds. How can I make it show up again with each button click?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ex1">
  <button id="alert-trigger" data-dismiss="alert" class="btnClick">
    Trigger Alert
  </button>

  <div id="example" class="alert" role="alert"></div>

  <script type="text/template" id="alert-template">
    <p>
      <span lang="da">Merhaba</span>,
      hello,
      <span lang="ja">Hallo</span>
    </p>
  </script>
  <script type="text/javascript">
    $(document).ready(function() {
      window.setTimeout(function() {
        $(".alert").fadeTo(1000, 0).slideUp(1000, function() {
          $(this).remove();
        });
      }, 3000);
    });
  </script>
</div>

Answer №1

At this time, you have not assigned any click event to the <button>. If you are searching for a solution, here is one way you can achieve it:

 $(document).ready(function() {
    //First hide the alert :
      $("#example").hide();
      
    // then bind the click :
    $("#alert-trigger").on("click", function () {
      
      $("#example").fadeIn(); // Shows the alert
      
      window.setTimeout(function() {
        $("#example").fadeOut(); // hides it again
      }, 3000);
      
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ex1">
  <button id="alert-trigger" data-dismiss="alert" class="btnClick">
    Trigger Alert
  </button>

  <div id="example" class="alert" role="alert">I'm an ALERT !</div>
  
</div>

Answer №2

Utilizing vanilla JavaScript, begin by setting the default opacity of the #example element to 0. When the #alert-trigger button is clicked, change the opacity to 1 and then use the setTimeout() method to revert it back to 0 after a second.

For jQuery, start by hiding the #example element by default. Simply apply the fadeIn() method to fade it in upon click, followed by utilizing both the setTimeout() method and the fadeOut() method to fade out the element after a specified time interval.


Below are practical examples of my explanations through the following Code Snippets:


Implementing Pure JavaScript Method:

/* JavaScript */

const btn = document.getElementById("alert-trigger");
const box = document.getElementById("example");

btn.addEventListener("click", function(){
box.style.opacity = 1;
  setTimeout(function(){box.style.opacity = 0}, 1000);
});
/* CSS */

body {text-align: center;}#alert-trigger{background-color: green; padding: 5px; color: #FFF;}

#example {background-color: grey;padding: 10px;margin: 10px 0px;
  opacity:0; /* initial opacity value set to 0 */
  transition: all 1s; /* will fade the element instead of hiding/showing the element instantly */
}
<!-- HTML -->

<button id="alert-trigger">Trigger Alert</button>

<div id="example" >
  <h2>Box Content Here:</h2>
  
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus quia dolore cumque aliquid eaque nisi, eos praesentium delectus tempore quidem? Iure tenetur cupiditate, laborum, saepe aut alias voluptatem impedit molestias.</p>
</div>

Using jQuery Technique:

/* JavaScript */

$("#alert-trigger").on("click", function(){
$("#example").fadeIn(); // fade in the example div
  
  setTimeout(function(){
  $("#example").fadeOut(); // fade out the example div
  }, 1000);
})
/* CSS */

#example {display:none;} /* initially hide it by default */
<!-- HTML -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="alert-trigger">Trigger Alert</button>

<div id="example" >
  <h2>Box Content Here:</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus quia dolore cumque aliquid eaque nisi, eos praesentium delectus tempore quidem? Iure tenetur cupiditate, laborum, saepe aut alias voluptatem impedit molestias.</p>
</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

Enhancing AngularJS view rendering using ngshow

Currently, I am working on a view where ng-show is used to display a select DOM object when certain conditions are met, and an input DOM for all other scenarios. However, I have noticed that there is a significant delay in the disappearance of the input bo ...

Troubleshooting: Else block not functioning as expected within a React JS map function

I have a notification feature that makes an API call every 10 seconds to display an alert based on the response. However, I'm encountering an issue where the div is not being rendered properly. The div should be displayed based on certain conditions w ...

What is the most effective method for synchronizing data with HTML5 video playback?

I am currently developing a program that retrieves data from an android application and plays it back on a web browser. The android app allows users to record videos while logging data every 100ms, such as GPS location, speed, and accelerometer readings, i ...

What is the proper method for setting initial values for scope upon loading the view using AngularJS and ngInit?

For the last few weeks, I've been immersing myself in AngularJS, studying large-scale applications to gain insights into real-world development practices. One common pattern I observed is the use of ng-init="init()" when loading a view - essentially c ...

How can I link an HTML anchor to a calendar?

Is there a way to create a universal link that generates a calendar event using HTML? For example, we can create an email link with <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff9e9b9b8d9a8c8cbf9a879e928f9 ...

When checking for errors with console.log(errors) in Ajax, it may return undefined due to server-side

I'm looking for a way to alert the user about validation errors coming from PHP. I am currently using Laravel 5.3 to build the form and Ajax to retrieve error messages. Below is my JavaScript code: $.ajax({ url: '/artistPost', typ ...

The correct method for creating an external JSON file

As I browse through numerous JSON tutorials online, including those on STO, I find myself in a state of confusion when it comes to determining the right approach for writing an external JSON file. I have come across various examples such as: (although Ad ...

Using Angular, I am passing a controller variable as a parameter to a custom filter in the HTML `ng-repeat`. This parameter will be populated within a function so that

At the moment, my setup includes a controller, a filter file, and some HTML. Currently, I am using ng-repeat in the HTML with custom filters that I have created based on the filter being used. For example: ng-repeat="p in persons = (person | toArray | fil ...

Restrict Vue Router access to specific pages only

Once a user has logged in for the first time, they are directed to the CreateProfile page where they can enter their profile information. I want to restrict access to this page so that if the user manually types the URL into their browser (e.g. www.myproje ...

Tips for modifying environment variables for development and production stages

I am looking to deploy a React app along with a Node server on Heroku. It seems that using create-react-app should allow me to determine if I'm in development or production by using process.env.NODE_ENV. However, I always seem to get "development" ev ...

Obtain information stored locally when an internet connection is established

I'm currently facing an issue with my Local Storage data retrieval process in Vuejs while being online. My ToDo app setup consists of Vuejs, Laravel, and MySQL. When the internet connection is available, I store data in localStorage. The ToDo app has ...

Unable to utilize routes in Express.JS when integrated with nginx

After setting up nginx in front of Express.JS, everything seemed to be running smoothly. However, I encountered an issue when trying to access website.com/users, which resulted in a 404 Not Found error. It appears that accessing website.com works fine, but ...

Router Express, parsing the body, and submitting a POST request

I have been experimenting with express.Router to organize my routes and testing post requests using Postman. I noticed that when I make a post request to /test without using router body-parser, everything works fine and I can view the body content. However ...

What is preventing me from installing socket.io?

I keep seeing an error in the console, what could be causing this? npm ERR! code 1 npm ERR! path E:\full-stack\proshop-2\socket\node_modules\utf-8-validate npm ERR! command failed npm ERR! command C:\WINDOWS\system32&bso ...

Ways to set the initial value of an input[range] in Angular2 when the value exceeds 100

After encountering a similar issue with AngularJS, I posted a question on StackOverflow titled How to initialize the value of an input[range] using AngularJS when value is over 100. As I dive into learning Angular2, I am curious if it handles initializatio ...

Unable to apply border-radius to a specific HTML table

I am facing an issue where the border-radius is not being displayed on a specific HTML table. I am having difficulty in applying rounded corners to the entire table so that the table edges have a 30px curve. Here is an example of what I am looking for: I ...

Click the button to automatically insert the current time

Hello, I am new to scripting and seeking some guidance. I have a code that retrieves the current time and sends it to a MySQL database when a button is clicked. <form action="includes/data_input.inc.php" method="POST"> <!-- button - Start ...

Methods for determining the disparity in days between two dates and the ratio of days yet to come

Within my React project, I am in need of a functionality that calculates the number of days remaining between two specific dates. Essentially, I want to determine how many days are left from today until the expiration date, and then calculate the percentag ...

Accessing the next and previous elements using jQuery

Aug: <input type="text" value="100000" name="targetMonth_8" id="targetMonth_8" class="targetMonth" disabled> Sep: <input type="text" value="100000" name="targetMonth_9" id="targetMonth_9" class="targetMonth" disabled> Oct: <input type="text" ...

prompting the JavaScript hangman game to identify the letters in the "selected word"

Currently, I am on a mission to teach myself Javascript and have taken on the challenge of creating a simple hangman game. This type of project is commonly used in interviews or tests, so it seemed like a great opportunity for practice. My approach involve ...