JavaScript: Implementing a seamless spinning effect for an image [Compass needle]

I have been working on developing a compass app for mobile devices and have successfully created a function that returns the change-values for the compass-needle rotation (e.g. 20). However, I have noticed that setting the 'image-transform' to 'rotate(x deg)' results in a slightly jumpy motion. To enhance the user experience, I am keen on adding a smooth animation for the needle to move.


Could you help me with coding a JavaScript function that can incorporate an animation for my compass needle?

Of utmost importance: How do I handle a situation where the function is called with a parameter '20', and 0.5 seconds later (while the initial animation is in progress) the function is called with a different parameter '-30'. I need the function to cancel the ongoing animation, add the new change-value ('-30') to the old one ('20'), and initiate a new animation seamlessly.


I hope my issue is clear. Below is the basic framework of my function:

var change_value = 20;
function start_animation(change_value){ 
  $needle_element.css("-webkit-transform", "rotate(" + change_value + "deg)")
}

Answer №1

Is this the solution you seek?

// Accessing DOM elements
var input = document.getElementById("angle");
var btn = document.getElementById("btnGo");
var needle = document.getElementById("needle");

// Setting up click event handler
btn.addEventListener("click", start_animation);

// Storing the previous angle
var lastAngle = "";

function start_animation(){ 
  // Updating the total angle required
  lastAngle = +lastAngle + +input.value;
  
  // For testing purposes:
  console.clear()
  console.log("Total current angle: " + lastAngle);

  // Moving the needle:
  needle.style.transform = "rotate(" + lastAngle + "deg)";
}
#needle {
  height:5px;
  background-color:#808080;
  width:100px;
  margin-top:100px;

  /* Initial rotate value required for smooth transition */
  transform:rotate(0);  

  /* CSS transition for smooth effect */
  transition:all 1.5s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="angle" value="20"><button type="button" id="btnGo">Go!</button>
<div id="needle"></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

assistance in incorporating CSS classes using jQuery

In an attempt to modify the bottom border color of my navigation bar based on the link being hovered over, I want the bottom border color to change to match that of the hovered link. When the link loses focus or hover, the navigation bottom-border should r ...

utilizing class manipulation to trigger keyframe animations in react

Currently, I am delving into my very first React project. In my project, I have implemented an onClick event for one of the elements, which happens to be a button. The aim is to smoothly transition an image's opacity to 0 to indicate that the user ha ...

splitting the array elements in JavaScript

I'm having trouble with my code that is supposed to separate the array in customer and customerportals. let j = 0; let k = 0; let myVar = []; $.each(Object.customer, function(index, value) { $.each(value.portal.customerPortal, function(innerIn ...

Steps for removing a chosen file from several input files by clicking a button

Within my application, there is an input file that displays a list of selected files underneath it. Each of these selected files has a corresponding remove button. While I am able to successfully remove a single file with ease, I struggle when attempting t ...

Implementing dynamic components in Vuejs by passing props from objects

I have developed a dashboard application that allows users to customize their dashboard by adding widgets in any order. While the functionality is working fine, I am looking to address some technical debt and clean up the code. Let's simplify things ...

When you hit a certain point on the website, the scrolling momentarily pauses

Upon refreshing the page and scrolling down, I notice that the website experiences a brief lag for a few milliseconds before continuing as normal. Oddly enough, this issue only occurs after refreshing the page. Any suggestions on how to resolve this? Th ...

Unable to click on links due to issues with the CSS and HTML

On my page at , there are links on the right side that I am unable to click. Does anyone know why this might be happening? Content on the Left Side: <nav class="woocommerce-breadcrumb" itemprop="breadcrumb"><a class="home" href="http://artendije ...

What is the best way to create a strip within an oval using CSS to achieve a partially filled vertical vessel effect?

I need to create an oval shape with a strip inside to represent the level of liquid volume. Here is my initial attempt: <style scoped> .strip:before { position: absolute; background: #343434; border-bottom: 2px solid black; content: ""; ...

JSOUP is cleverly filtering out specific tags while navigating through the HTML tree

While attempting to navigate the HTML tree of a Wikipedia page, I noticed that certain blocks of HTML elements in the code are being omitted. Is there a way to prevent these omissions? CODE Document doc = Jsoup.connect(url).timeout(10000).userAgent(USER_ ...

Troubleshooting Java REST service integration in AngularJS for UPDATE and DELETE operations

After successfully implementing a REST service with Java and testing all HTTP methods using Postman, I decided to explore AngularJS. Upon integrating it to consume the REST service, I encountered issues specifically with the Delete and Put methods not func ...

Trying to replace all instances of a word in an HTML document with a <span> element, but only for <p>, <span>, and <div> tags. It shouldn't work if the parent node already contains

Here is the HTML code snippet I am working with: <div> hello world <p> the world is round <img src="domain.com/world.jpg"> </p> </div> I am looking to replace the word "world" (or any mixed case variations) with < ...

Maximize the performance of displaying images

At the moment, I have a set of 6 graphics (0,1,2,3,4,5)... The arrangement of these graphics looks fantastic! However, I am facing an issue when a user only has 3 graphics, for example 0, 2, and 5. In this scenario, my graphics do not line up correctly. D ...

Limit the vertical movement in Vue drag and drop operations

Currently, I am working on a project that involves implementing drag-and-drop functionality using vue-draggable. You can find more information about it here: https://github.com/SortableJS/Vue.Draggable. I am facing an issue where the height of the element ...

Tips for saving the ajax response to the browser cache using jquery

I am currently working on storing the ajax response in the browser cache. I have successfully managed to store it for URLs like (example.com), but now I am facing a challenge with storing data for URLs like (example.com?xyz=abc%20efg&mno=hjk). Here is ...

Implementing logic with multiple columns in JavaScript

Looking for a way to display an array of data in multiple columns using Java Script, like this: 1 2 3 4 5 6 7 8 9 instead of 1 4 7 2 5 8 3 6 9 Any suggestions would be greatly appreciated. Thank you. ...

Is it possible to create an HTML dropdown menu with integer values?

What is the best way to create a dropdown menu in HTML with integer values ranging from 1 to 12? How can I ensure that when a value is selected, it gets saved into a variable? All I need is a simple select field in HTML that displays options from 1 to 12 ...

Changing a background image url using jQuery by clicking a button

I'm struggling to find a way to use jQuery to add a background image URL to my CSS. Everything I've attempted so far has been unsuccessful. let button = document.querySelector('form button.btn') button.addEventListener('click&ap ...

A fatal error has occurred in Node as it is unable to set headers after

Just getting started with nodeJs and I'm attempting to read a file from the system. It seems like I can view the file content in the console, but for some reason it's not displaying in the browser. Any ideas what I might be overlooking? var myD ...

Is it true that loading "undefined" into an array can use up a significant amount of memory?

I've encountered a strange issue where a bug is consuming excessive memory and leading to frequent server crashes. Every 30 seconds, a value is saved to an array: historicalValues.push( valueToSave ) When valueToSave is set to 1, the memory usage r ...

My onClick AngularJS function contains a for loop that is not functioning properly upon initial click

When I click on a student's name in my AngularJS app, the program is supposed to show the student's full name and list of tuitions. However, I am encountering an issue where the for loop does not work on the first click, but it works fine on the ...