The functionality of the button in my script is limited to a single use

Below is a simple code snippet that I wrote:

  • HTML & CSS:
<!DOCTYPE html>
<html>
    <head>
        <title> JavaScript Console </title>
        <style>
            button { text-align:center;
                     width:200px;
                     height:30px;
                     font-size:17px;
                     font-family:courier new;
                     border:solid 2px black;
                     font-weight: bold;
                     background-color:lightblue; 
                     cursor:pointer;
                     border-radius: 20px;
                     transition: 0.5s; 
                    }

            button:hover {
                          transform: scale(1.2, 1.2);
                          font-size:19px;
                          background-color: cyan;
                    }
        </style>
    </head>
    <body style="text-align:center">
        <fieldset>
        <legend style="text-align:center;margin-bottom: -20px"><h1 id="h1" style="text-align:center;">JavaScript tests on console</h1></legend>
        <p style="color:green;"> Have fun coding !</p>
        <br/> 
        <div style="text-align: center;"><button id="btn" onClick="buttonHandler()" >Show time</button></div>
        <p id="time" style="color:blue;"></p>
        <p id="tick" style="color:red;"></p>
        <p></p>
    </fieldset>
        <script src="./test.js"></script>
    </body>
</html>
  • JavaScript:
console.log('Console is working fine !'); 

/**********************************************************************/
var x = 60;
function tick() {
    var date = new Date();
    document.getElementById("time").innerHTML = date;
    x--;
    document.getElementById('tick').innerHTML = `The time will be hidden after ${x} seconds`;

}

function clearAll(id) {
    window.clearInterval(id);
    document.getElementById('time').style.display = "none";
    document.getElementById('tick').style.display = "none";
}

function buttonHandler(e) {
    var id = window.setInterval(tick,1000);

    setTimeout(()=> clearAll(id),60000);

}

/**********************************************************************/

The issue I'm facing is that the 'Show time' button only works for the first click and doesn't work again after that.

I believe the problem lies with the setInterval() method which runs only once, but I'm not sure how to resolve it.

Could someone provide guidance on how to fix this issue?

Answer №1

You may notice that the element is hidden at the end of the timer within the clearAll function:

document.getElementById('time').style.display = "none";
document.getElementById('tick').style.display = "none";

To make them visible again, you need to display them once more upon clicking.

If the button is clicked multiple times, the tick function will be executed repeatedly, causing the timer to decrement faster.

I have added a safeguard to prevent running the function multiple times and resetting the timer.

console.log('The console is functioning correctly!'); 

/**********************************************************************/
var x = 60;
var isRunning = false;

function tick() {
    var date = new Date();
    document.getElementById("time").innerHTML = date;
    x--;
    document.getElementById('tick').innerHTML = `The time will disappear in ${x} seconds`;
}

function clearAll(id) {
    window.clearInterval(id);
    document.getElementById('time').style.display = "none";
    document.getElementById('tick').style.display = "none";
    isRunning = false;
}

function buttonHandler(e) {
    if (isRunning === false) { // To avoid multiple clicks triggering tick function
        isRunning = true;
        x = 60; // Reset timer
        document.getElementById('time').style.display = "block"; // Make visible again
        document.getElementById('tick').style.display = "block"; // Make visible again
        var id = window.setInterval(tick,1000);

        setTimeout(()=> clearAll(id),60000);
    }
}

/**********************************************************************/
<!DOCTYPE html>
<html>
    <head>
        <title> JavaScript Console </title>
        <style>
            button { text-align:center;
                     width:200px;
                     height:30px;
                     font-size:17px;
                     font-family:courier new;
                     border:solid 2px black;
                     font-weight: bold;
                     background-color:lightblue; 
                     cursor:pointer;
                     border-radius: 20px;
                     transition: 0.5s; 
                    }

            button:hover {
                          transform: scale(1.2, 1.2);
                          font-size:19px;
                          background-color: cyan;
                    }
        </style>
    </head>
    <body style="text-align:center">
        <fieldset>
        <legend style="text-align:center;margin-bottom: -20px"><h1 id="h1" style="text-align:center;">JavaScript Console Tests</h1></legend>
        <p style="color:green;"> Enjoy coding!</p>
        <br/> 
        <div style="text-align: center;"><button id="btn" onClick="buttonHandler()" >Show Time</button></div>
        <p id="time" style="color:blue;"></p>
        <p id="tick" style="color:red;"></p>
        <p></p>
    </fieldset>
        <script src="./test.js"></script>
    </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

How to trigger an update of the useEffect() hook when a button is clicked

I am working with a functional component that contains a button and uses the "useEffect()" hook. My goal is to trigger a re-render of the component, updating the useEffect() hook when the button is clicked. const Emp_list = (props) => { useEffect(() ...

What is the reason behind jQuery's .html("abc") only providing temporary insertion?

I have come across an issue with an HTML button that triggers a function. Whenever the button is clicked, a div is inserted but it only appears for a brief moment before disappearing both visually and in the HTML tree. function openBox () { $( '#0&a ...

Problem with jQuery's .prepend method being called twice on list items

Looking to enhance the appearance of a list by adding some icons before the anchor links within each list item. <ul class="submenu-children"> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> ...

Launching a React project using the terminal - my step-by-step process

I'm attempting to initiate a new react-app utilizing the command npx create-react-app <app name> as shown below: npx create-react-app new-app However, after downloading, it seems to be stuck. It's not progressing at all. I've even rei ...

Showcasing Portfolio Work in a User-Friendly Mobile Design

Currently revamping my portfolio website and looking for ways to optimize the display of my personal projects. I have a card-like interface in place that works well on desktop but only shows one project at a time on mobile devices. Seeking solutions to imp ...

Creating a unique, random output while maintaining a log of previous results

While working on a recent project, I found myself in need of a custom Javascript function that could generate random numbers within a specified range without any repetitions until all possibilities were exhausted. Since such a function didn't already ...

When utilizing array.push() with ng-repeat, it appears that separate scopes are not generated for each item

I'm currently working on an Angular View that includes the following code snippet: <div ng-repeat="item in items track by $index"> <input ng-model="item.name"/> </div> Within the controller, I utilize a service to retrieve a Js ...

Tips on toggling the visibility of a div using jQuery and CSS via a toggle switch

Hey there, I need some help with toggling the opening and closing of a div when clicking on a toggle switch. $('.tog').on('click', function() { $('.cntr').show(); }); .switch { position: relative; display: inline-bloc ...

Remove the class upon clicking

I recently created a toggle-menu for my website that includes some cool effects on the hamburger menu icon. The issue I am facing is that I added a JavaScript function to add a "close" class when clicking on the menu icon, transforming it into an "X". Whil ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

Divide Angular ngFor into separate divs

Here is an example of my current array: [a, b, c, d, e, f, g, h, i] I am aiming to iterate through it using ngFor and split it into groups of 3 elements. The desired output should look like this: <div class="wrapper"> <div class="main"> ...

Add a hyperlink alongside every row in the table

My table comprises three columns in each row, and I am looking to include a link next to each row. <table> <th> Name: </th> <th> Price: </th> <th> Description </th> ...

Issue with DIV height in Internet Explorer occurs only when application is accessed using server name

Encountering a unique issue specific to IE (confirmed in v8 and v9). When utilizing jquery to determine the height of a div: $('#sys_MainPage').height() In Chrome, Firefox, and when accessing using the IP address, this code returns around 26 ...

Troubleshooting: :before element not being hidden by jQuery slidetoggle()

My elements are all behaving correctly with the slidetoggle() function, except for my li:before class. I've attempted to manipulate the overflow, visibility, display, and other properties of both the :before pseudo-element and the li element, but the ...

It's impossible to remove a dynamically added class from a button

I'm facing an issue with adding and removing classes from a button using jQuery. I added a new class to the button, then removed it, but now when I click the button again I want to revert back to the initial class. Unfortunately, my code is not workin ...

moment.js incorrectly interprets the month as the day instead of the actual day

I am currently using moment.js (moment-with-locales.js - v.2.14.1) in my project. My goal is to extract only the date from a datetime string and remove the time. However, when I use the .format() method of moment.js, I receive an incorrect date. The datet ...

Troubleshooting Problems with CSS Span Placement

Challenges with Span Positioning in CSS Currently, I am encountering difficulties while working on the index.html.erb file for an example Rails website. Below is a snippet of the HTML code I am struggling with (please note that this is simply a fabricated ...

Trigger the opening of a bootstrap modal from an external source on the current page

One common question is how to load a modal from another page onto the current page, or how to open a modal on the current page when it loads. My idea is a little different: I want to click on an image hotspot (like a person in a team photo) on the /home p ...

What is the best way to center a Bootstrap 4 navigation menu horizontally?

The alignment of the navigation is causing a bit of confusion. I've attempted to set the links to navbar-brand, but while this centers them, it also causes other elements to shift slightly downward. Additionally, it's puzzling why the select opti ...

A function in Jasmine for testing that returns a promise

I have implemented the following function: function getRepo(url) { var repos = {}; if (repos.hasOwnProperty(url)) { return repos[url]; } return $.get(url) .then(repoRetrieved) .fail(failureHandler); function ...