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

Focusing on a specific div element

I need help selecting the initial div block that contains the word "Target". <div class="box-content"> <div> <div>Target</div> <div>xxxx</div> <div>xxxx</div> <div>xxxx</div> ...

Troubles with Geocoding functionality on Google Maps integration within Wordpress

I have a challenge where I want to utilize the title of a Wordpress post (a specific location) as a visible marker on a Google map. The code provided by Google successfully displays the map without any markers: <script>function initialize() { va ...

sending a parameter in the reverse url using JavaScript

coding in javascript let address = '{% url candidate_resume "cnd_id" %}'; address = address.replace("cnd_id",id); document.getElementById('cell2').innerHTML= '<a href="' + address + '"> View Resume < ...

When using JQuery Validation on a small screen, error messages can cause the button to shift downwards

After successfully creating an email form with jquery validation error style that appears when there's an error, I encountered a problem. When the screen width is reduced or viewed on a small screen, the error message pushes down the button. I&apos ...

Can anyone explain why two of my SVG files are displaying as identical in my React project?

The issue seems to lie within the SVG code itself. I have two SVGs exported from Figma and imported into ReactJS as ReactComponents. However, an anomaly occurs where React recognizes both SVGs as identical despite having different SVG codes. This makes me ...

Adjusting Column Placement in Bootstrap Grid System

I am struggling to achieve a specific bootstrap grid system and could use some guidance. Here is the grid system I am trying to create: https://i.sstatic.net/fhEHU.jpg I have attempted to implement the grid system using the code provided in this JSFiddl ...

Executing multiple MSSQL queries in a Node.js environment

Currently, I am faced with the challenge of running multiple SQL queries. The issue lies in variables going out of scope due to the asynchronous nature of node.js. I am attempting to find a solution similar to the await keyword available in C#. To clarif ...

`Explore SQL data using modal window`

Hey there, I'm in a bit of a pickle with my code. As someone who's just dipping their toes into the world of AJAX and has a vague understanding of PHP, I find myself lost in trying to figure out where things went wrong. My challenge lies in fetc ...

Guide on refreshing threejs morph targets using blender GLTF shape keys

I have been working with a Blender file that contains multiple shape keys. By adjusting the slider in Blender, I am able to manipulate these shape keys. (screenshot): Currently, I am exporting the GLTF and then importing it into Three.js. Upon console.l ...

Deactivate the submission button when there are no search results in typeahead.js

How can I disable the submit button if there are no search results found? The form should not be submitted in this scenario. I am currently using typeahead.js for my code. $('.typeahead').typeahead(null, { name: 'suburb', disp ...

Utilizing Sass variables and customizing CSS styles within the main stylesheet

Hey there! I'm new to sass and I have a specific question about it. Do I need to link the scss file to a separate css file where I'm working, or can I write my styles directly in the same file? I tried using sass variables from Bootstrap 5.3.2, b ...

Tips for displaying a div briefly before loading the second page

Incorporating a div named ADD, I aim to successfully load a second page within the current one using ajaxload. The challenge lies in displaying a div for 4 seconds before loading the second page. How can this be achieved? Following the wait period, the sec ...

My PHP script is not functioning correctly with Ajax

I am currently working with HTML5, PHP, and JavaScript. My goal is to implement Ajax in order to display the sizes of a selected product when an option is chosen from #productoSeleccionado. However, I believe that there may be an issue with my code as the ...

What takes precedence in npm scripts - local dependencies or global ones?

When using npm scripts, the ./node_modules/.bin path is automatically added to your PATH. This means that by simply running npm test with the provided package.json, npm will utilize the local version of mocha located in ./node_modules/.bin. "scripts": { ...

What is the highest possible z-index value that can be applied in

Is there a specific limit to the CSS property z-index? Are there variations in accepted values among different browsers? How do browsers typically handle extreme z-index values? I recall reading about a potential maximum value for z-index somewhere, but I ...

Utilizing the Google Translate API within an ASP MVC framework to translate a div's content from English to Arabic

Currently, I am working on a small project that involves two divs: one for English and another for Arabic. Despite creating the project, I am encountering an issue with getting the translation from English to Arabic. Below is the code I have attempted, but ...

What is the counterpart of the JavaScript transport.responseText in jQuery's Ajax requests?

I'm currently in the process of converting my JavaScript Ajax request to jQuery's ajax. Here is an example of my existing JavaScript Ajax code: new Ajax.Request(url, { method: 'post', onSuccess: function(transport) { ...

Google Extension PHP Plugin

Is it feasible to integrate a PHP file into a Google Extension for Chrome? I've been exploring the idea of creating an extension and most resources only mention HTML, CSS, and JavaScript. Any guidance on using PHP in the extension would be highly valu ...

Dealing with full-width elements on mobile devices

I've got a pretty basic question here but can't seem to find a straightforward answer. I'm using Bootstrap to style a website and struggling with making it mobile-responsive. Following the given answer, I used this code to show a button ne ...

The width of the HTML select dropdown needs to be adjusted as it appears too large

I've been trying to find a solution to my issue, but I'm having trouble locating one. It could be because English is not my first language and maybe I'm not searching using the right terms. The problem I'm facing is with implementing t ...