`Arc canvas countdown timer`

My countdown timer created using canvas is functioning well, but I am encountering some issues:

I would like to align the circle representing seconds with the circles for minutes, hours, and days similar to this demo.

Please ensure running the code snippet in a full page.

Kindly refrain from suggesting plugins, as I prefer writing concise code and expanding my knowledge of jQuery & JavaScript.

Answer №1

Make sure each canvas has a unique ID assigned to it; for hours and days, use the same scale as for seconds.

Next, you should call the function with the appropriate parameters to draw each canvas separately instead of grouping them all in one function (It's better to create a function that takes a canvas and draws it). I combined everything in one function for efficiency.

(function ($) {
    jQuery.fn.countdown = function (options, callback) {
        var settings = {
            'date': null
        };
        if (options) {
            $.extend(settings, options);
        }
        this_sel = $(this);
        /*Canvas Variables*/

        // Define canvas variables here and adjust accordingly
        
        function count_exec() {
            // Code logic for countdown execution here
        }

        // #region Execute Interval
         count_exec();
        interval = setInterval(count_exec, 1000);
        // #endregion       
    };
})(jQuery);
$(document).ready(function () {
    $("#countdown").countdown({
        date: "6 january 2017 7:15:00"
    },
      function () {
          $("#countdown").text("merry christmas");
      }
    );

})
#countdown .countdown-container{
                width:25%;
                position:relative;
                float:left;
                border:1px solid #0fd562;
            }
            #countdown .countdown-container >div{
                position:absolute;
                top:100px;
                left:95px;
                text-align:center;
            }
            .secs, span{
                font-size:16px;
            }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="countdown">
        <div class="countdown-container">
            // HTML structure goes here
        </div>
        <div class="countdown-container">
            // Another container
        </div>
        <div class="countdown-container">
            // Container for hours
        </div>
        <div class="countdown-container">
            // Container for days
        </div>
    </div>

I've set up the formula for days as 365 format (2PI/365=0.0172), but feel free to modify it for weeks or months if needed.

Hope this explanation helps!

Answer №2

Give this a shot:

(function ($) {
    jQuery.fn.timer = function (options, callback) {
        var settings = {
            'targetDate': null
        };
        if (options) {
            $.extend(settings, options);
        }
        elem = $(this);
        
        /*Canvas Declarations*/
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        var centerX = canvas.width / 2;
        var centerY = canvas.height / 2;

        // Additional Canvas Variables and Parameters
        
        var radius = 70;
        var angle = 0;
        var secondsPassed = 0;

        /*End of Canvas Declarations*/
        function timerExecution() {
            targetTime = Date.parse(settings['targetDate']) / 1000;
            currentTime = Math.floor($.now() / 1000);

            if (targetTime <= currentTime) {
                callback.call(this);
                clearInterval(interval);
            }

            remainingSeconds = targetTime - currentTime;
            daysLeft = Math.floor(remainingSeconds / (60 * 60 * 24));
            remainingSeconds -= daysLeft * 60 * 60 * 24;
            hoursLeft = Math.floor(remainingSeconds / (60 * 60));
            remainingSeconds -= hoursLeft * 60 * 60;
            minutesLeft = Math.floor(remainingSeconds / 60);
            remainingSeconds -= minutesLeft * 60;

            context.clearRect(50, 50, canvas.width, canvas.height);
            angle = ((60 - remainingSeconds) * parseFloat(0.10471));

            context.beginPath();
            context.arc(centerX, centerY, radius, 1.5 * Math.PI, 1.5 * Math.PI + angle, false);
            context.lineWidth = 8;
            context.strokeStyle = '#14E170';
            context.stroke();

            // Update countdown values
            if (!isNaN(targetTime)) {
                elem.find('.days').text(daysLeft);
                elem.find('.hours').text(hoursLeft);
                elem.find('.minutes').text(minutesLeft);
                elem.find('.seconds').text(remainingSeconds);
            }
        }

        // #region Execute Interval
         timerExecution();
        interval = setInterval(timerExecution, 1000);
        // #endregion
       
    };
})(jQuery);
$(document).ready(function () {
    $("#timer").timer({
        targetDate: "25 December 2022 00:00:00"
    },
      function () {
          $("#timer").text("Happy Holidays");
      }
    );

})
#timer .countdown-container{
                width:25%;
                position:relative;
                float:left;
                border:1px solid #0fd562;
            }
            #timer .countdown-container >div{
                position:absolute;
                top:100px;
                left:95px;
                text-align:center;
            }
            .secs, span{
                font-size:16px;
            }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="timer">
        <div class="countdown-container">
            <div class="contents">
                <div class="seconds">
                    00
                </div>
                <span>Seconds</span>
            </div>
            <canvas id="canvas" width="250" height="250"></canvas>
        </div>
    </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

Implementing the jQueryUI checkboxradio feature across all checkboxes within an entire ASP web application

I have a collection of Checkboxes in my ASP Webform app. I want to implement the jQuery UI checkboxradio() for all checkboxes in my app. To achieve this, I have added the following code in my Site.Master file. However, it is not functioning properly, even ...

Dynamic header showing various sections of the image depending on screen size

Looking to create a responsive header image for my website using the 'mobile first' approach. I have a specific picture in mind that I want to display differently depending on the device's screen size, all while using the same image file. Fo ...

Using placeholder in number and range input in Angular.js to display a placeholder text instead of a value when the input is 0

I am using Angular.js to link a number and range input so they work together with the same value. I have set the default value to 0 when the page loads as $scope.lbs_needed = 0;. My goal is to display a placeholder="0" whenever the user sets the value of e ...

Challenges arise when using CSS Grid to design a basic layout with rows and several centered divs

As a CSS Grid beginner, I am working on creating a simple layout for my personal blog using codepen.io Visit my codepen.io project here I aim to have multiple rows with full width, each containing various divs of different widths centered within the row. ...

The light slider feature is experiencing technical difficulties within the Bootstrap model

I am experiencing an issue with the Light Slider in a Bootstrap modal. Strangely, when I press F12 for inspect element, the Light Slider starts working. For more details and to see the link provided in the comment below, can anyone offer assistance, plea ...

Tips for transforming a JSON array retrieved from a REST API into a usable object

Upon receiving a message from my backend, it appears as follows: [ [ { "id": 1, "date": "2018-12-31" }, { "id": 12, "standard": null, "capacity": 7, "descr ...

Click on another part of the page to reveal a dropdown menu

I am seeking a way to trigger the opening of this dropdown select not by directly clicking on its position, but rather by clicking on another <span>. Displayed below is the dropdown menu: <div class="styled-select"> <span id="camDurati ...

Refresh a div element automatically with information from a different webpage using jQuery

I've been attempting to automatically reload a page and fetch new data every 10 seconds, or even less. However, the codes I've tried so far have not been successful. Here is my current approach... // script // <script> $(document).rea ...

Troubles with a straightforward Jquery script

Upon initial execution of this code, the page abruptly jumps to the top before functioning correctly upon subsequent hovers on other elements. For a demonstration, visit the following jsfiddle link: http://jsfiddle.net/FXhLz/ The issue may not be immedia ...

Unable to include the index parameter in the subsequent $http request

Here is a code snippet showcasing a $http request to retrieve quizzes and their respective results. The problem lies in the fact that 'i' is representing obtained values instead of index. $http.get(url).success(function(response) { $scope.qu ...

The visibility of the eye icon on the password field may vary, occasionally appearing and disappearing from view

Here is the code for my login form password field (I'm using bootstrap 4): <div class="form-account-label-input"> <label> Password <span class="star-red">&nbsp;*</span></label> <input type ...

Chrome displaying unexpected behavior with Jquery ajax response

Currently, I am facing an issue with my jQuery AJAX specifically on Chrome. The AJAX function echoes the result in the following format: 1||result goes here Below is the AJAX script that I am using: $("#load_cards").click(function() { $("#load_c ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Generating a JSON array from a C# collection can be achieved by utilizing the System.Web.Script.Serialization

Can someone help me with this code snippet? var httpWebRequestAuthentication = (HttpWebRequest)WebRequest.Create("http://api"); httpWebRequestAuthentication.ContentType = "application/json"; httpWebRequestAuthentication.Accept ...

Include an additional section in the stunning Radar Chart

I am trying to use the amCharts 4 library to create a Radar graph similar to this example: https://i.sstatic.net/9S0ka.png In the example, there are two categories being compared with bullets surrounding each one, right? The code I currently have is as ...

React does not recognize the use of `.css` or `.scss` files for styling

Recently, I encountered an issue with my React code where inline styles were working fine: render() { return ( <div style={{ fontSize: 48 }}>LOLOLO</div> ) } However, when I tried using index.css (which defines .me { font-size ...

Is there a simple method to add animation to a group of images displayed on click using JQuery?

Here is my JavaScript code that I'm currently using: $(document).ready(function() { $(".button-list .next").click(function() { project = $(this).parents().filter(".projektweb").eq(0); currentimg = project.find(".im ...

Express.js and Node version 0.10.29: The Mystery Post

Having trouble with sending JSON data to an express server and receiving 'undefined' for req.body.name. This is how the configuration is set up: const express = require('express'); const app = express(); app.configure(function(){ ...

What steps should I take to incorporate Bootstrap's JavaScript into Vue (Gridsome)?

Check out my website: The site is built with Gridsome, a static site generator for Vue. If you navigate to the mobile version and try to open the Bootstrap Hamburger menu, it doesn't work as expected. I've followed the instructions in Gridsome ...

Tips for keeping my background image from shrinking when I resize the window?

When I resize the webpage window, my background image shrinks in size. Currently, it is not repeating (which is a step forward), but now I need it to cover the entire screen to avoid showing white space around the background when the window gets smaller. ...