Implement a delay for updating the style of a button by using the setTimeout function

Is it possible to create a button that, when clicked, changes color to green and then reverts back to its original style after 3 seconds?

I am able to change the button color using an onClick event in my script. However, I encounter scope errors when trying to implement a function that returns the button to its normal colors.

Javascript:

<script type="text/javascript>

function onClickDelayEvent () {
    function changeColor(elem) {
        elem.style.background = 'green';
        elem.style.color = 'white';
    }
    function revertColor(elem) {
        elem.style.background = '';
        elem.sytle.color = '';
    }
    setTimeout(revertColor,3000);
    }

</script>

HTML:

<button id="copyButton" onclick="onClickDelayEvent(this)">Copy</button>

The issue arises with the newColor function not executing and triggering an "elem" undefined error in the normalColor function.

If I simplify the code to only change the style once, it works perfectly. The challenge lies in reverting it back to its original state.

Answer №1

Is this what you were looking for?

I noticed a typo in your code: elem.sytle.color = ''; it should actually be style. You also need to call the newColor function on onClickDelayEvent.

<script type="text/javascript">

function onClickDelayEvent (elem) {
   
    function newColor(elem) {
        elem.style.background = 'green';
        elem.style.color = 'white';
    }
    function normalColor(elem) {
        elem.style.background = '';
        elem.style.color = 'black';
    }
    setTimeout(normalColor,3000,elem);
    newColor(elem);
    }

</script>

<button id="copyButton" onclick="onClickDelayEvent(this)">Copy</button>

Answer №2

Instead of using 3 functions, a simpler approach is to apply a CSS class on click and then remove it after a 3-second delay. This method is useful because removing a class reverts the element back to its original style without any extra steps!

By utilizing classes for styling changes, you can easily apply or remove multiple styles simultaneously, rather than dealing with individual ones.

Avoid inline HTML event attributes like onclick and use JavaScript event handlers instead. Here's why: here.

// Access the button element
var btn = document.getElementById("copyButton");

// Add event listener in JavaScript
btn.addEventListener("click", clickDelay);

function clickDelay(evt) {
    evt.target.classList.add("special");
    setTimeout(function(){
      evt.target.classList.remove("special");
    },3000);
}
/* Upon click, this class will be added
   and then removed after 3 seconds, restoring
   the button to its original appearance. */
.special { 
  background-color:green;
  color:white;
}
<button id="copyButton">Copy</button>

Answer №3

Perhaps you could pass a parameter to the onClickDelayEvent function and utilize it directly within the code... something in this fashion:

<script type="text/javascript">

function onClickDelayEvent (element) {
    function changeColor() {
        element.style.background = 'green';
        element.style.color = 'white';
    }
    function revertColor() {
        element.style.background = '';
        element.style.color = '';
    }
    setTimeout(revertColor, 3000);
}

</script>

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

Tips for displaying a restricted quantity of items in a list according to the number of li lines used

My approach involves using a bulleted list to display a limited number of items without a scrollbar in 'UL' upon page load. On clicking a 'more' button, I aim to reveal the remaining items with a scrollbar in UL. The following code acco ...

Utilizing the power of AngularJS with ng-class for dynamic styling and

I recently started learning AngularJs and I have a question about how angular handles the ng-class attribute. While working with external libraries for visualization, charts, etc., I often need to trigger the resize event: window.dispatchEvent(new Event( ...

Vue.js application failing to display images fetched from the server

When I'm running my Vue.js app locally, the images are loading fine from the "src/assets" folder. However, when I deploy the app to Firebase, the images are not displaying and I get a 404 error. What could be causing this issue? I have tried using: ...

What is the best way to create vertical spacing between Material UI Grid Paper components?

The spacing of the goal components is not as I would like it to be. This is how they currently appear. https://i.stack.imgur.com/jApzK.png So far, I have attempted setting the display of the Paper selector to flex. Additionally, I experimented with adjus ...

jQuery behaving erratically following deployment to the testing server

I am encountering an issue with jQuery in a user control that utilizes a Telerik RadGrid: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.js"></script> <script type="text/javascript"> ...

Guide on transferring a 200MB database to an HTML5 web page executed locally

In the process of creating a search tool for internal use within my organization, I have established a deployment strategy that involves: Storing an HTML5 web page on the file server. Keeping a 200MB JSON or JavaScript file in another location. Currentl ...

Transmitting the identification number of a post with the help of J

I am currently working on a while loop in PHP that fetches associated results from a query and displays them within a class identified by the user who created the post. My goal is to send the id of the class to PHP, similar to how I am sending the num vari ...

Error message displayed on PHP web page

I'm working on a page that will display "no query string" if $_REQUEST is null, and if not, it will show a page with the content saying "query string". Additionally, it should output the line "The query string is: var_dump($_REQUEST)". I've writt ...

Aligning list items with Bootstrap

I am struggling with aligning Sheet3 and Science vertically left in a list with checkboxes. Currently, Science goes below the checkbox and I need a solution to fix this alignment issue. https://i.sstatic.net/bxoBT.png Any guidance on how to adjust the al ...

Twitter Bootstrap 3 - Change column order for extra small screens

My Twitter Bootstrap layout consists of two columns structured like this: <div class="col-md-4 col-sm-6 col-xs-12"> <div class="post"> Content here </div> </div> <div class="col-md-8 col-sm-6 col-xs-12"> <di ...

Tips for displaying a digital keyboard when a webpage loads on iOS Safari

While developing a website, I noticed that the virtual keyboard fails to appear when an input field gains focus during the page load process. As per Apple's policy restrictions, this functionality is not allowed. However, I am interested in finding a ...

Sending back JSON arrays containing Date data types for Google Charts

One of my challenges involves using a 'Timelines' chart from Google Charts, which requires a JavaScript Date type when populating data. Here is my initial code snippet: var container = document.getElementById('divChart1'); var chart = ...

Is there a way to ensure that the div of my template spans 100% in width and height?

I'm attempting to make my div 100% in size but I am having trouble achieving it. Here is my code: <template> <div> <Navbar/> <Calendar/> </div> </template> <script setup> import Calendar from &apos ...

Is it possible to condense the coding of a vast array of objects into a more concise format?

Currently working on a personal project in react.js and aiming to write cleaner code. Is there a way to condense this code into just two lines or something similar? I attempted to create objects of arrays like const apps= {app_name:['Maps',&apo ...

The text area within the input group is misaligned with the input group button

Here is an example of how I'm using the input group feature with Bootstrap: <div class="input-group" style="padding-left: 20px;"> <input type="text" name="s" class="form-control input-sm"> <span class="input-group-btn"> ...

Calculate the frequency of tag_name occurrences on a webpage using Python and Selenium

Greetings! I am currently working with the following code snippet: for each in driver.find_elements_by_xpath(".//*[@id='ip_market" + market + "']/table/tbody") cell = each.find_elements_by_tag_name('td')[0] cell2 = each.find_el ...

Is there a way to verify the identity of two fields using an external script such as "signup.js"?

My current project involves working with Electron, and it consists of three essential files. The first file is index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="styles ...

Having trouble retrieving the toDataURL data from a dynamically loaded image source on the canvas

Currently, I am working on a project that involves a ul containing li elements with images sourced locally from the "/images" folder in the main directory. <section class="main"> <ul id="st-stack" class="st-stack-raw"> ...

Troubleshooting a problem with placeholder styling on Internet Explorer

Encountering a challenge while styling placeholders, particularly in Internet Explorer where the placeholder text color does not change as expected. Instead, it inherits the color of the input field. :-ms-input-placeholder { color: white; } input ...

The "Next" button fails to function after a replay has been completed

I created a small quiz app to practice my JS skills. Everything seems to be working fine, except for one issue - when I click on replay, the quiz box shows up but the 'Next' button stops functioning. There are no console errors and I'm strug ...