What's the best way to trigger an alert popup after calling another function?

Here are some HTML codes I've been working with:

<button id="hide" onclick="hide()">Hide</button>
<p id="pb">This paragraph has minimal content.</p>

My goal is to have the paragraph hide first when the button is clicked, followed by an alert() popup. Despite my efforts and extensive searching, I haven't been able to achieve the desired outcome. Below are my initial CSS and JS codes:

CSS:

.hide {
   display: none;
}

JS

 var button = document.getElementById("hide");
 var p = document.getElementById("pb"); 
 function hide(){
   p.classList.add("hide");             
   alert("The paragraph is now hidden!");
 }

In the current setup, the alert popup appears before the paragraph hides. This sequence is not what I intended. Your help would be greatly appreciated!

Answer №1

The browser is currently busy running the JavaScript function, delaying the immediate change in the DOM until it is free to repaint the display.

When an alert pops up, it blocks all other actions, forcing the browser to wait for it to be dismissed before proceeding.

To avoid this issue, you can encapsulate the code within a setTimeout.

p.classList.add("hide");             
setTimeout(alert.bind(null, "The paragraph has disappeared!"));

Answer №2

Implement the following code snippet

<script type="text/javascript>
    function hide() {
        $("#pb").hide("slow", function () {
            alert("The paragraph has been hidden!");
        });
    }
</script>

Answer №3

Utilizing Jquery hide event explore More .Specify a delay or opt for fast animation.

No need for external CSS to hide elements.

function hide() {
        $("#pb").hide(function () {
            alert("The paragraph has disappeared!");
        });
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="hide" onclick="hide()">Hide</button>

<p id="pb">This is a paragraph with minimal content.</p>

Answer №4

If you're facing this problem, one solution is to utilize setTimeout(). You can initiate by concealing your paragraph and then employing setTimeout alongside the alert message.

<html>
    <head>
        <script>
            function hide(){
                document.getElementById("pb").style.display = 'none';   
                setTimeout(function(){ alert("The paragraph disappeared!"); }, 3000);          
            }
        </script>
    </head>
    <body>
        <button id="hide" onclick="hide();">Hide</button>
        <p id="pb">This paragraph contains only a few words.</p>
    </body>
</html>

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

Is there a way I can utilize a for-loop and if statement in JavaScript to present the information accurately within the table?

My current task involves fetching data via AJAX and then using a for-loop and if-statement to determine which goods belong in each shopping cart. Once identified, I need to display these goods in separate tables corresponding to each customer. Although the ...

Choose specific columns from distinct tables and arrange them accordingly

I am facing a challenge with my MySQL database as it contains multiple tables with similar columns, and I want to import this data into a Google spreadsheet. For instance: table1 has id, name, page, and other specific columns. table2 also includes id, n ...

Executing JavaScript functions within static files in Django

I can't figure out why I'm unable to invoke a javascript function when clicking my Bootstrap button in a Django project. In my directory, I have set up the static folder as "main/static/main/js/script.js". While I can successfully load the stati ...

Is Immutable state considered a key functional aspect in the ReactJs framework?

One key aspect of an imperative program is the emphasis on state and its modifications. When it comes to ReactJs, there is a push for more functional programming styles, such as using purity and higher-order functions. I'm curious to explore whether ...

Is there a way to delay loading 'div' until a few seconds after the 'body' has been fully loaded?

Is there a way to delay the appearance of the "text-container" div after the image is displayed? I have attempted to achieve this using JavaScript with the following code: <script> window.onload = function(){ var timer = setTimeout("showText()",700 ...

Using Vue to change select box data separately

I have a functional select box that is currently sending the selected value to a method when the change event occurs. However, I am wondering about something: Let's say I also want to send the cat_id value at the time of selection (to create an objec ...

Using AJAX for uploading files upon a change event rather than upon submission

Below is the code I have been using to implement an iframe for ajax file upload without refreshing the page upon form submission. The current code works as expected. window.onload=init; function init() { document.getElementById('form').onsubmi ...

A guide on effectively utilizing the Map datatype in JavaScript

Recently, I've started delving into the world of es6 Map due to its unique features, but I have some reservations regarding pure operations. For example, when removing properties from objects, I usually use the following function: function cloneOmit ...

Developing a unique bundle with tailored elements

I am interested in developing a custom Material UI component and making it available as a standalone package within my company's private NPM repository. Specifically, I have customized the Date Picker to create a Date Range Picker since Material UI d ...

The Pino error log appears to be clear of any errors, despite the error object carrying important

After making an AXIOS request, I have implemented a small error handling function that is called as shown below: try { ... } catch (error) { handleAxiosError(error); } The actual error handling function looks like this: function handleAxiosError(er ...

Using the ref callback to access getBoundingClientRect values in React Components

I'm having some trouble extracting data using the getBoundingClientRect() method from a set of animated div elements. The issue I'm facing is that the refCallback function is returning empty DOMRect objects. If you're interested, feel free t ...

On the initial page load, Magento is failing to load the CSS properly

I've been tinkering with the Magento website over at For some reason, the CSS on the Home page doesn't load initially, but it loads fine when you click on any other link like Products or Gallery. Any ideas why this might be happening? Thanks in ...

Find similarities and differences between two CSV files

Dealing with 2 large files, both exceeding 1 million rows: The first file contains only an md5 hash The second file contains pairs of md5 and email addresses My task is to compare these two files and if the md5 hashes match, write the corresponding emai ...

Using React router to handle multiple hierarchical parameters

Having a documentation component in my app, I want the URLs to appear as follows: url: myapp.com/docs url: myapp.com/docs/document-1 url: myapp.com/docs/category-1/document-2 url; myapp.com/docs/category-1/category-2/document-2 The challenge lies in set ...

The Javascript function call from the <img src="myFunction()"> is malfunctioning

I am looking to dynamically pass the URL of an image using a JavaScript function. <head> <script> function myFunction() { var str1 = "somepictureurl.png"; return str1; } </script> </head> <body> <img src="myFu ...

Python tutorial: Executing onclick values with a click

I'm currently working on writing some Selenium Python code and I have a question. The website I am testing has multiple time slots available, and I am attempting to simulate a mouse click specifically geared towards the 8:30-11:30 timeslot. Below is ...

The persistent space between the navbar and the index page remains despite the suggested fixes provided

There appears to be a discrepancy between the navigation bar and the rest of the page. Despite my efforts to adjust margins, I haven't been able to resolve it. The system is prompting me for more details before posting this question, but I'm unsu ...

Trouble arises with Pagination feature of Mui Data Table

Currently, I am working on a project that involves retrieving data from the CoinMarketCap API and presenting it in an MUI Data Table (specifically a StickyHeader Data Table). However, I have been encountering difficulties with changing the color of the tex ...

`user implemented object comparison within a set in unity (es6)`

I am facing an issue where I need to handle multiple values and ensure that only unique ones are used. With the use of node js and access to harmony collections through the --harmony flag, I have considered using a Set as a potential solution. What I am s ...

What is the best way to utilize CSS to center an element in relation to the scroll bar?

For a group project, I successfully centered a div on a webpage. However, I ran into an issue where the website's contents are centered taking the scroll bar width into consideration. This means that the web page contents adjust to be centered without ...