Javascript dynamically generates CSS animations

I need assistance creating a div with a CSS3 animated timer inside it when a button is clicked. Here is the code I have been working on: http://jsfiddle.net/arcco96/y5nov6rz/1/. Unfortunately, the div is not being created as expected. I believe the code should work fine, but I am unsure if it is possible to create a div with a CSS animation after the page has loaded.

The foundation of my fiddle is based on this example: http://jsfiddle.net/zbGCq/118/.

My current approach to creating the div goes as follows:

$("#btn1").click(function(){
    jQuery('<div/>', {
        class: 'timer',
    }).appendTo('#center');
    jQuery('<div/>', {
        class: 'mask',
    }).appendTo('#center');
});

Any insights or suggestions would be greatly appreciated.

Thank you,

P.S. On a slightly different topic, I would like to know if it is possible to overlay content on the #timer element or if that will pose a challenge?

Answer №1

You attempted to use jQuery objects before they were even created.

Although the CSS is still not working correctly in my Firefox browser, the JavaScript functionality is operational.

In Chromium, there is an animated effect occurring, but I am unsure if that is the desired outcome.

Check out this link for more details.

var cv = $('.container').width();
$('.head').css({
    'height': (cv / 3) + 'px'
});

$("#btn1").click(function () {
    jQuery('<div/>', {
        class: 'timer',
    }).appendTo('#center');

    var cw = $('.timer').width();
    $('.timer').css({
        'height': cw + 'px'
    });

    jQuery('<div/>', {
        class: 'mask',
    }).appendTo('#center');
});

Answer №2

To achieve this effect, I recommend using JavaScript to animate the path element within an SVG.

You have the flexibility to adjust the size of the timer by modifying the value assigned to the width variable. Additionally, you can control the speed of the animation by changing the value of the t variable.

Check out a live demo on CodePen

var timer = document.getElementById('timer');
var svg = document.getElementById('svg');
var width = 150;
svg.setAttribute('width', width);
svg.setAttribute('height', width);
var t = 5;
var theta = 0;
var radius = svg.getAttribute('width') / 2;
timer.setAttribute('transform', 'translate(' + radius + ',' + radius + ')');

(function animate() {
  theta += 0.5;
  theta %= 360;
  var x = Math.sin(theta * Math.PI / 180) * radius;
  var y = Math.cos(theta * Math.PI / 180) * -radius;
  var d = 'M0,0 v' + -radius + 'A' + radius + ',' + radius + ' 1 ' + ((theta > 180) ? 1 : 0) + ',1 ' + x + ',' + y + 'z';
  timer.setAttribute('d', d);
  setTimeout(animate, t)
})();
body {
  background: #333333;
  text-align: center;
}
<svg id="svg">
  <path id="timer" fill="lightseagreen" />
</svg>

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

The error message "Invalid Data Type: Not an Array - google charts" was encountered

I am struggling with an ajax call that I have set up. The issue arises when passing an array from the backend to the frontend. Upon checking the data through an alert on the frontend, everything seems fine. However, Google charts raises an error stating th ...

Using CSS3 translate will result in children becoming relatively positioned

I am facing an issue with a sidebar that contains 2 divs. <div class="sectionsContainer clearfix"><-- Sidebar --> <div class="leftSection pull-left"> <p>Maor</p> </div> <div class="rightSection pu ...

Elements within the DIV tag are not displaying in a linear arrangement as intended

I'm having trouble creating a navbar with Bootstrap 4. The items in my div tag are not inline, and I can't align my nav item to the right. Here is the HTML code: <nav class="navbar navbar-inverse "> <div style="display:inline"> ...

Utilizing Laravel 5.2 to showcase a video

I am currently developing in Laravel 5.2 and facing an issue with displaying a video on my view page. While I can successfully store the video in my database table, I am encountering difficulties when trying to fetch and display it. In my database table, I ...

Having trouble accessing AJAX POST data in Python?

For this jQuery request, I utilize an HTTP POST. function retrieveData() { const information = JSON.stringify({ "test_id": "1" }); jQuery.post('/retrieveData', information, function (response) { a ...

Tips for making a standout testimonial card?

Apologies for the simplistic inquiry. As a fresh student of a full stack web developer bootcamp, I find myself grappling with this particular challenge. How can I go about creating a testimonial card similar to this one? I've attempted to write code ...

Instructions for sending a server error response with php

When the user clicks on the delete button, my jQuery script sends a request to the server to delete the selected item. Now, I want my php script to return either a success or an error response. Is it possible to trigger the error callback if the item can ...

Is it feasible to alter cookie data within a jQuery ajax call?

I'm currently developing a Chrome extension that enables users to capture all HTTP requests for a specific website, edit components of the request, and then send it again. My plan is to utilize jQuery's ajax function to design and dispatch the a ...

Is there a way to prevent my jQuery from triggering the <a href> unless the ajax post is successful?

I am attempting to update the database and redirect the user's browser to a new page with just one click. Here is how the HTML appears: <a id='updateLiveProgress' style='width:118px;' href='~link~'>Click here</ ...

Issue with Vue canvas $ref not being defined on resize causing error, but oddly still seems to function correctly

Within my application, there exists a tabbed interface. One of the tabs contains a canvas element that dynamically adjusts its size to fit the window whenever it is resized. The functionality works seamlessly at first, but upon switching tabs and returning ...

Strategies for extracting data from a third-party website that utilizes JavaScript to set the value

Before, I would use jQuery to load external website content such as html or json. Sometimes, I even utilized a proxy PHP page in order to bypass strict origin policies on certain sites. However, I've encountered an issue with some websites. In the HT ...

Difficulty with linking a CSS property to an HTML element using JavaScript

I'm currently working on building a custom carousel from scratch. Instead of using pre-made code snippets, I decided to challenge myself by creating one using setTimeout in JavaScript. However, I seem to be encountering an issue that I can't quit ...

Having trouble loading Yeoman Webapp SASS

Every time I try to build a web application using 'yo webapp', I encounter a 404 Error. GET http://localhost:9000/styles/main.css 404 (Not Found) I removed compass from the project, but that shouldn't be causing the issue, correct? ...

Python program that creates a spinning equilateral triangle

Could really use some assistance here, I'm completely stuck on the final step. [] I've included my code below. When it comes to rotating the triangle for the last step, I'm not sure how to go about it. ...

All I desire is to eliminate the term "class" from the text

Upon clicking the code, only the value 137 should display according to the image. However, the word "class" also appears. https://i.stack.imgur.com/HZhr4.png <a rel="facebox" href="portal.php?id='.$rowa["_id"].' class="icon-remove"></a ...

The ajaxStart event does not seem to be triggering when clicked on

I am having trouble adding a loader to my site using the ajaxStart and ajaxStop requests to show and hide a div. The issue is that these requests are not being triggered by button onclick events. <style> // CSS for loader // Another class with o ...

I'm curious about utilizing jsviews in conjunction with jquery sortable

Check out my jsFiddle Example where I am using jsViews in conjunction with JQuery sortable. By default, the remove function works fine; however, when you change the order of items and then try to delete one, multiple items are removed. How can this issue ...

degree of transparency when semi-transparent elements overlap

Imagine you have two <div> elements, one with an opacity of .5 and another overlaying it with the same opacity. What would be the combined opacity of the two? Interestingly, it's not as simple as, .5 × .5 or even, .5 + .5 How can this ...

What is the best way to eliminate all borders from a select box?

Is there a way to completely remove all borders from the selectbox using either CSS or JQuery? The code snippet is as follows: <select id="doctor_ch"> <option value="1" selected>One</option> <option value="2">Two</option& ...

The website flickers in and out as it loads

My site keeps flashing whenever it loads. Despite trying the solutions recommended in this stackoverflow post, I have had no success. Every page on my website loads a nav.html file using this code: $.get("nav.html", function(data){     $("#nav-placeho ...