What is the solution to adding values from a counter?

I am trying to create a JavaScript counter:

function animateSun() {
  var $elie = $("#sun");
  $({
    degree: 0
  }).animate({
    degree: 360
  }, {
    duration: 190999,
    easing: 'linear',
    step: function(val) {
      now = Math.round(val);
      if ((now == 5) || (now == 10) || (now == 15)) //increment the value on every 5th number
      {
        var i = 0;
        $('#tam').text(i += 1);
      }
      $elie.css({
        transform: 'rotate(' + now + 'deg)'
      });
      $('#demo').text('sec:' + now);
    },


  });
}
animateSun();
#sun {
  position: absolute;
  width: 55px;
  height: 55px;
  border: 1px solid red;
  background-color: orange;
  opacity: 0.9;
  border-radius: 100%;
  text-align: center;
  top: 50%;
  left: 50%;
  animation: round 3s infinite linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p id="demo"></p>
<p id="tam">0</p>
<p id="sun">sun</p>

The timer was running. When the time value reaches 5, it should add 1 to #tam. Then when it reaches 10, #tam should be incremented by another 1 to change the value to 2. However, this is not working as expected. Could someone please help me figure out how to increment the value of #tam every time the count reaches a multiple of 5 and also display the changes on #demo? Thank you in advance.

Answer №1

Here is a suggestion for you to try out: use the Math.floor() function on step/5.

function animateSun() {
  var $elie = $("#sun");
  $({
    degree: 0
  }).animate({
    degree: 360
  }, {
    duration: 190999,
    easing: 'linear',
    step: function(val) {
      now = Math.round(val);
      $('#tam').text(Math.floor(val/5));
      $elie.css({
        transform: 'rotate(' + now + 'deg)'
      });
      $('#demo').text('sec:' + now);
    },


  });
}
animateSun();
#sun {
  position: absolute;
  width: 55px;
  height: 55px;
  border: 1px solid red;
  background-color: orange;
  opacity: 0.9;
  border-radius: 100%;
  text-align: center;
  top: 50%;
  left: 50%;
  animation: round 3s infinite linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p id="demo"></p>
<p id="tam">0</p>
<p id="sun">sun</p>

Answer №2

Following Rejith's advice, it is advisable to store the counter value in a global variable. Currently, the counter is being reset to 0 every time and then incremented, resulting in a constant output of 1.

let counter = 0;
function animateSun() {
  let $elie = $("#sun");
  $({
    degree: 0
  }).animate({
    degree: 360
  }, {
    duration: 190999,
    easing: 'linear',
    step: function(val) {
      now = Math.round(val);
//          if ((now == 5) || (now == 10) || (now == 15)) //increment the value on every 5 value
      if( now % 5 == 0 )
      {
        $('#tam').text(counter++);
      }
      $elie.css({
        transform: 'rotate(' + now + 'deg)'
      });
      $('#demo').text('sec:' + now);
    },


  });
}
animateSun();

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

Delete a table row based on the values of checkboxes using Jquery

I've successfully generated an array from values selected in an HTML form using checkboxes. Is there a way to pass these selected checkbox values to jQuery and utilize the code $('tr#myTableRow').remove(); for each value in the array submit ...

JavaScript Time and Amount Formatting

My issue involves the formatting of returned data. I am looking to compile all values into a list with adjustments made to the time format and fare amount as indicated. Specifically, I need to remove commas from fare amounts and AM/PM from departure and ar ...

JQuery is unable to initiate a keyup event

I am currently utilizing jQuery in a web application. On one of my pages, I have set up an event listener for keypresses as shown below: document.addEventListener('keyup', function (event) { event.preventDefault(); var key = event.k ...

Issues with CSS causing image resizing problems on Chrome, looking for solutions

On my website, I have favicons from various external domains. However, there seems to be an issue with resizing them when they are not 16px in size. Sometimes only the top or bottom half of the image is displayed, but upon refreshing the page, the entire i ...

Is there a way to verify within the "if" statement without repeating the code?

Is there a way in javascript (or typescript) to prevent redundant object rewriting within an if statement condition? For example: if (A != null || A != B) { // do something here } // can it be done like this: if (A != null || != B) { // avoid repeating ...

Passing props to component data in Vuejs: Best practices

I'm experimenting with Vue 2.0 and I've encountered a bit of confusion. How can I properly pass props to a component's internal data? I've followed the documentation, but it still seems unclear. HTML <service-list :services="model"& ...

Is it possible to utilize various providers in Next-Auth while still maintaining the same email address?

I am currently developing a Next.js application using NextAuth. At the moment, I have implemented login functionality with Google, credentials, and GitHub. However, I encountered an issue where if a user logs in with Google using the email "[email pro ...

Exploring ES6 classes in Java Script: accessing prototype properties

After searching extensively for an answer and coming up empty-handed, I decided to pose my question here. When creating an object constructor in JavaScript as shown below: function Car(speed){ this.speed = speed; this.position = 0; } Car.prototype.m ...

Error: The property 'language' is undefined and cannot be read

Struggling to execute the App-test.js file provided by React Native in the __test__ directory: import 'react-native'; import React from 'react'; import App from '../src/app'; // Note: test renderer must be required after rea ...

The character 'T' cannot be assigned to the data type 'number'

When working with an optional type argument function RECT(T), I encountered a situation where I need to check if the argument is an instance of date. If it is, I convert it to a number; if not, I use the number directly. However, I keep getting an error ...

Accessing properties of objects using specific keys

In my coffeescript code, I am attempting to retrieve the keys from an object where the key matches a specific value. However, in addition to the object's own properties, I am also getting function properties in my result. This issue is causing an err ...

Creating an attention-grabbing alert bar positioned above the menu

When I attempted to add this alert bar to my website, I encountered an issue where it was being hidden behind my menu. Some sources suggest that using z-index and position:absolute can resolve this problem by positioning one element above the other, but th ...

What steps should I take to keep a reference to a specific plugin instance following an AJAX callback?

When creating a plugin, I would like to trigger an AJAX call that retrieves data and then proceeds with building the plugin control. Here is a simplified example of what I have in mind: $.fn.grid = function (options) { this.each(function () { ...

Displaying a random div using javascript

Seeking a way to display random divs on my webpage, I came across a stackoverflow solution: Showing random divs using Jquery The recommended code can be found here: http://jsfiddle.net/nick_craver/RJMhT/ Despite following the provided instructions, I am ...

Positioning MDL cards in HTML documents

Seeking guidance on positioning MDL cards alongside existing text. I've attempted various methods without success so far, and the desired outcome has not been achieved. The goal is to have text aligned to the left (which is currently satisfactory) wi ...

Error: The parameter "q" provided in the Google Maps Embed API is

Currently, I am developing a Web Application using NodeJs, Express, and Pug/Jade. The pug code below is functional: iframe#map(width="100%", height="600", frameborder="0", style="border:0" src='https://www.google.com/maps/embed/v1/place?' + ...

What could be causing my css stylesheet to not function properly in Sinatra?

I'm fairly new to this, but based on my research, this code should be functioning correctly. I am attempting to link a CSS stylesheet to an .erb file. Here is the code snippet I am using: <link rel="stylesheet" type="text/css" h ...

Inheritance best practices for node.js applications

In C#, the concept of inheritance can be easily demonstrated through classes like Animal and Dog. class Animal { string name; public Animal() { } } class Dog : Animal { public Dog() : base() { this.name = "Dog"; } } When working ...

Tips on Monitoring Load Time of Partial Views inside jQuery DialogWould you like to know how

I am using a partial view in my project and rendering it with jQuery dialog functionality. I am interested in measuring the render time of this partial view in minutes, seconds, and milliseconds. Can anyone provide guidance on how to accurately measure t ...

Add adhesive dashes to the text box

I am looking to add sticky hyphens in a text input field. I have included an image illustrating my requirement. The areas that need fixing are highlighted in red. The first hyphen should appear after every three number inputs, followed by the next one afte ...