Is it possible to time a page without relying on the Form tag?

As I search for solutions, I have come across some examples that require a Form tag, but unfortunately, it doesn't seem to integrate well with my current application.

My goal is to implement a timer on a webpage that starts counting when one button is clicked and stops when another button is clicked. These buttons will be placed outside of the UpdatePanel where the stopwatch should be located.

Can this be achieved using Java? I came across a potential solution in this answer, but it didn't work as expected:

How to create a stopwatch timer

The issue seemed to arise with the first line of the tm1_Tick function which was unable to recognize 'sw' as NULL.

I would greatly appreciate any sample code or guidance on how to proceed.

Answer №1

Some instances I have come across necessitate a Form tag

This is because they are ASP.NET WebForms (similar to the one you referenced: many server controls with namespace tag "asp").

Instead of using a Form tag, why not solely rely on JavaScript? Record the time on any event and then, utilizing setTimeout, periodically update the page content.

(It is interesting to note that the only similarity between Java – the multi-platform language created by Sun and now owned by Oracle – and JavaScript – the scripting language seamlessly integrated into browsers – is the first four letters in their names.)

Answer №2

It appears you are referring to "JavaScript". A great way to implement this is by using a client-side solution with JS.

Stumbled upon this fantastic example online (disclaimer: the following code is not mine):

http://jsfiddle.net/oukjfavu/

var h1 = document.getElementsByTagName('h1')[0],
    start = document.getElementById('start'),
    stop = document.getElementById('stop'),
    clear = document.getElementById('clear'),
    seconds = 0, minutes = 0, hours = 0,
    t;

function add() {
    seconds++;
    if (seconds >= 60) {
        seconds = 0;
        minutes++;
        if (minutes >= 60) {
            minutes = 0;
            hours++;
        }
    }

    h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);

    timer();
}
function timer() {
    t = setTimeout(add, 1000);
}
timer();


/* Start button */
start.onclick = timer;

/* Stop button */
stop.onclick = function() {
    clearTimeout(t);
}

/* Clear button */
clear.onclick = function() {
    h1.textContent = "00:00:00";
    seconds = 0; minutes = 0; hours = 0;
}

Answer №3

For the sake of clarity, I am providing this response based on Jamieson's answer. The final outcome involved incorporating the following Javascript code:

<script type = "text/javascript">
    /* Stop, Clear and Pause the timer displayed under the pause buttons  */
    var h1 = document.getElementsByTagName('h1')[0],
        start = document.getElementById('start'),
        stop = document.getElementById('stop'),
        clear = document.getElementById('clear'),
        seconds = 0, minutes = 0, hours = 0,
        t;

    function add() {
        seconds++;
        if (seconds >= 60) {
            seconds = 0;
            minutes++;
            if (minutes >= 60) {
                minutes = 0;
                hours++;
            }
        }

        document.getElementById('<%=h1.ClientID%>').innerText = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);;
        timer();
    }
    function timer() {
        t = setTimeout(add, 1000);
    }

    function stp() {
        clearTimeout(t);
    }

    function clr() {
        document.getElementById('<%=h1.ClientID%>').innerText = "00:00:00";
        seconds = 0; minutes = 0; hours = 0;  
    }
</script>

To incorporate the ASP.Net component, you will need to include the following:

 <asp:UpdatePanel ID="UpdatePanel4" runat="server">
     <ContentTemplate>
         <table style="width:132px; margin-left:13px">
             <tr>
                 <td style="text-align:center; margin-left:2px; border:double; background-color:darkcyan">
                     <asp:Label ID="h1" runat="server" ForeColor="White"><time>00:00:00</time></asp:Label>
                 </td>
             </tr>
         </table>                                    
     </ContentTemplate>
</asp:UpdatePanel>

Subsequently, for the ASP buttons, the following was added:

onclientclick="stp();"

If there is already an onclientclick attribute on your button, simply separate them with a semicolon as multiple functions can be called simultaneously.

In addition, certain sections in the code-behind required the following additions:

ScriptManager.RegisterClientScriptBlock(UpdatePanel4, this.GetType(), "script", "stp()", true);
ScriptManager.RegisterClientScriptBlock(UpdatePanel4, this.GetType(), "script", "clr()", true);

Please note that the necessity of the last piece may vary depending on the context of your implementation.

Answer №4

If I understand your query correctly, you have the ability to construct a personalized countdown timer using JavaScript exclusively and then trigger an AJAX call to update your panel.

Take a look at this brief example of a countdown timer written in pure JS:

var start = document.getElementById("start");
start.addEventListener("click", function() {
  var interval = setInterval(function() {
    var watch = document.getElementById("watch");
    var value = watch.value - 1;
    watch.value = value;
    if (value <= 0)
      clearInterval(interval);
  }, 1000);
});
<input id="watch" value="10" />
<input id="start" type="button" value="start" />

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

Activate a click event on an element using Simple HTML DOM

I need assistance in triggering a click on the element below and then retrieving its innertext. <a class="btn btn-sm btn-default" href="javascript:;" onClick="score(238953,this)">Show result</a> Once the "onClick" event is triggered, the elem ...

Comparison of element state prior to and post editing (with contentEditable)

Exploring how elements within a div can be monitored for changes made by the user (thanks to contentEditable), I created a sample page with the following setup: before_html = $("#example_div").children(); $("#differences_button").on("click", ...

Complete a form on an external website using either C# or Javascript

I am looking for a solution to automatically fill and submit a form from a specific URL, as I need to trigger this process from my domoticz. Despite attempting different methods like using AJAX or injecting JavaScript, I keep encountering issues with the S ...

"Error message: Antd datepicker is throwing an error stating that date.clone/date.load is not a

I am working on a React app that has a checkbox to disable a datepicker. However, when I use the checkbox to disable it, I am unable to select any date. If I remove the checkbox and its function, there is no error. Currently, the error message I am getting ...

What causes the intersection observer handler to not trigger when using scrollTo or scrollIntoView?

When an intersection observer is added to an element, it triggers the handler function when scrolled past a specific point. However, if the element is scrolled past that point using a button click, the handler does not get triggered. Is there a way to man ...

Possible revision: "Exploring ways to iterate through an array of objects in Node/Express and verify if a corresponding entry exists in a MongoDB

Working on building a web application using the MEAN stack and Yelp API to retrieve an array of objects representing local businesses. I manipulate this data on the front-end, but before sending a response, I need to verify if a specific object exists in m ...

Combining two elements in Angular 2

I am looking to find the intersection of two objects. My goal is to compare these objects and if they have matching values on corresponding keys, then I want to add them to a new object. obj1 = { "Projects": [ "test" ], "Companies": [ "facebook", "google ...

The ajax success error function does not trigger in jQuery

Hey, check out my code below: <html> <head> <script src="http://code.jquery.com/jquery-1.8.0.min.js"> </script> </head> <body> <form id="foo"> <label for="bar">A bar</label> <input id ...

Why is Vue Router Navigation Guard throwing an error about exceeding the maximum call stack size?

Encountering a recurring issue of maximum stack size exceeded while implementing the following code for vue router navigation guards per-route: import state from "../vuex-store/state.js"; import Editor from "../views/Editor"; const routes = [ { ...

Using AngularJS routing with an Express 4.0 backend API

Recently, I began working on an application utilizing Express 4.0 server. Following a tutorial on scotch.io (http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4), I structured the routes to support a backend api serving an An ...

What is the best way to trigger an action in response to changes in state within Vuex

Are there more sophisticated methods to trigger actions in vuex when a state changes, rather than using a watcher on that state? I want to ensure the most efficient approach is being utilized. ...

[Tutorial] [C#] Dragging, Hovering, and Dropping Elements in Selenium

My website is hosted on an internal server, so I can't provide a direct link. However, I can share some relevant code snippets that appear when you click "show element". There are 5 key elements involved: Group1 student move1 Group2 move2 This ...

Finding your way to a particular section within a webpage through an external source

Hey there! I'm currently working on creating a link that will direct users to a specific section within my webpage. For example, redirecting them to https://blabla.github.io/my-website. My code is quite straightforward and it functions properly when ...

Tips for avoiding parent div click interference in Angular

Working with Angular8, I have a div containing a routelink along with other components including a checkbox. Here's the structure: <div [routerLink]="['/somewhere', blablabla]"> <!--other components that navigate to the ro ...

Stop the execution of the setTimeout function when the webpage loads in JavaScript

In my postgres database, I have a table named students for storing student information. The structure of the table is as follows: id first_name last_name time_remind 1 pers1 pers1_name 2022-07-30 21:30 2 pers2 pers2_name 2022-07-30 20:38 Current ...

As my character slides off the moving platform in this exciting Javascript canvas game, my heart

Can anyone help me figure out how to keep my player on the moving platform? I'm not sure if I need to add gravity or something else. I'm still learning the ropes. export function checkTopCollision({ item1, item2 }) { return ( item1.y + item ...

Error message: Unexpected character found at the beginning of JSON data - REST API using node.js and Express

Recently, I have embarked on the journey of learning REST API with node and express. My main goal is to achieve file read and write operations using APIs. However, a frustrating error arises when attempting to hit the API through Postman. Strangely enough, ...

Using a javascript variable in php within the Laravel framework

I am trying to retrieve an id from a button for use in my ajax request. Below is the code snippet for the button: <form> <div class="form-group"> <button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delet ...

Using Javascript to save a numeric value and accessing it on a different webpage

I'm encountering an issue with a specific feature on my website. I want users to click on a hyperlink that will redirect them to an application form page. The challenge is ensuring that the reference number (a 5-digit code displayed as a header) is st ...

Deciding on excluding empty key:value pairs from an object for various filtering needs

One of the features in my app allows users to filter results by "blood group" and "city", along with other areas. The information is retrieved from a database using Axios for Vuejs, incorporating query strings within the URL. For example: http://example.co ...