Disappear element after a brief moment

What is the best way to temporarily hide an element and then have it reappear after a second?


var targetElement = document.getElementById("myElement");

targetElement.onclick = function() {
   this.style.display = "none";

   setTimeout(function(){
      targetElement.style.display = "block";
   }, 1000);
}

I am successfully hiding the element, but it's not reappearing as expected. Can anyone point out what might be wrong with my code?

Answer №1

When using setTimeout, make sure to include the delay as the second argument if you need the code to wait for a specific amount of time before executing (this is assuming you forgot to pass the time argument prior to editing the question).

 setTimeout(function() {
      obj.style.display = "block";
   }, 1000); //1000 milliseconds = 1 second

It's also important to take note of the small o in out.

Answer №2

Ensure to update the code from setTimeOut to setTimeout and provide a time in milliseconds for the delay if needed:

The setTimeout() function allows you to schedule a function or code to be executed after a specified delay.

Optional Delay The time, in milliseconds (thousandths of a second), that the timer should wait before executing the designated function or code. If this parameter is left out, a default value of 0 is applied, triggering an "immediate" execution or as soon as possible. Keep in mind that even in these cases, the actual delay may end up being longer than anticipated; please refer to Reasons for delays longer than specified below for more information.

More on setTimeout()

   var obj = document.getElementById("myId");
    
    obj.onclick = function() {
       this.style.display = "none"
       
       setTimeout(function() {
          obj.style.display = "block";
       }, 1000);
    }
<div id="myId">Test</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

What is the best way to implement an AppBar that fades in and out when scrolling within a div?

I'm trying to implement a Scrollable AppBar that hides on scroll down and reappears when scrolling up. Check out this image for reference To achieve this functionality, I am following the guidelines provided by Material-UI documentation export defa ...

What is the proper way to retrieve the correct value in JavaScript?

I'm currently working on an Angular program but I'm having trouble returning the correct value: function facilityChecked(facility, search) { var result; search.filter( function (v) { var rtn = (v["facility_Item"]["te ...

What steps do I need to take in order to integrate an mpg video onto my

I am in need of embedding mpg (dvd compliant mpeg2) movie files onto my webpage. Unfortunately, I do not have the ability to convert these videos into any other format. This webpage is solely for personal use, so any solution would be greatly appreciated. ...

Determining the depth difference of nodes between two elements using JQuery

Is there a simple method to calculate the node depth difference between 2 elements? Example : <div id="1"> <div id="2"></div> <div id="3"> <div id="4"></div> </div> </div> <div id="5"></d ...

Strategies for preserving context throughout an Ajax request

In my project, I am looking to implement an Ajax call that will update a specific child element within the DOM based on the element clicked. Here is an example of the HTML structure: <div class="divClass"> <p class="pClass1">1</p> &l ...

Spin and shift image of a ball using Html 5

Now the image will be moved without rotating. I have implemented moving functionalities, but it only supports IE10. Here is the script I am using: var ball = new Image; window.onload = function () { var c = document.getElementsByTagName('canvas&apos ...

CSS unable to modify the color of the switch in HTML code

I've been struggling to change the color of the Switch to yellow when it's turned on. Despite my attempts, I haven't been successful in doing so. Is it even possible to achieve this color change? <Switch size="small& ...

Styling the CSS to give each grid element a unique height

I am working on a grid layout with three columns where the height adjusts to accommodate all text content. .main .contentWrapper { height:60%; margin-top:5%; display:grid; grid-template-columns:1fr 1fr 1fr; grid-gap:10px; /*grid-te ...

After 30 to 80 touches, the movement starts to lag and an error appears in the console

Error Details: [Intervention] A touchend event cancellation attempt was ignored due to cancelable=false, likely because scrolling is in progress and cannot be stopped. preventDefault @ jquery.min.js:2 (anonymous) @ number_grid_game.php:239 each @ ...

The "npm start" command encountered an issue: script "start" is

I'm encountering an issue when attempting to run my node application using the npm start command in Visual Studio Code. Any assistance would be greatly appreciated! Here is the content of my package.json file: { "name": "bloggin-site ...

Troubleshooting video streaming loading issues caused by 404 errors in URL paths with videojs

I've been successfully using the video.js library to stream live video. Everything was going well until after a while, the URL started throwing a 404 error during streaming, causing the entire player to get stuck on loading. Now I'm looking for a ...

JavaScript causing values to disappear when the page refreshes

When a user hovers over ImageButtons, I use Javascript to change the ImageUrl. However, on submitting the form, the updated ImageUrl property is not reflected in the code behind. Similarly, I also dynamically update a span tag using Javascript, but its alt ...

JavaScript: Converting an array of strings into an array of objects with proper formatting

After scanning barcodes, I have an array of strings that currently contains the following data: var array = ['NEW', '1111', 'serial1', 'serial2, 'NEW', '2222', 'serial3', 'serial4'] ...

Switch from HTML symbol to Java symbol

Is it possible to change an HTML symbol into a Java symbol? For instance, if I have &#xe000, is there a way to obtain the Java char representation like \ue000? What steps should I take to achieve this conversion? ...

Navigating a single page application with the convenience of the back button using AJAX

I have developed a website that is designed to function without keeping any browser history, aside from the main page. This was primarily done for security reasons to ensure that the server and browser state always remain in sync. Is there a method by whi ...

What is the best method for transferring data from PHP to Python?

I am currently running a Python application that requires receiving and processing data. I have a PHP server that is able to access this data. I am looking for a way to send JSON data from PHP to my Python application. Is there another method aside from ru ...

Exploring JS Pattern Matching across Two Distinct Data Sources

In my database, I have two tables (and more can be added in the future) with rows structured like this: <table> <tr> <th>name</th> <th>salary</th> </tr> <tr> <td>a</td> &l ...

Leveraging fullcalendar.io alongside JSONP

I'm currently in the process of integrating public holidays into my FullCalendar application. You can check out FullCalendar here. var actionUrl = @Html.Raw(Json.Encode(@Url.Action("Calendar", "Lecture"))); $('#fullcalendar').ful ...

Having trouble accessing portlet resource URL from JavaScript in Liferay 6.2

I have been working with Liferay Portal 6.2 CE GA3 and I am facing an issue where I need to execute a custom portlet resource method from another portlet's JSP file. Below is the code snippet I am currently using. <a href ="#" onclick="myfunctio ...

Unable to retrieve information using the post method in Express framework

After creating a basic code to fetch data from the client, I am facing an issue where req.body.firstname is showing as undefined. Here is the code snippet: const express = require('express'); const app = express(); const body ...