What is the best way to create a JavaScript animation for altering the width of a div element?

Need help with creating a dynamic poll chart based on YES and NO votes? Check out this project where you can visually see the results by clicking HERE.

Looking to add some animation effects to your poll? You can achieve a smooth transition using CSS with transition: width 100ms linear;. Take a look at the sample code below:

<!DOCTYPE html>
<html>
<head>
    <title>Document</title>
    <style>
        .poll{
            height: 50px;
            width: 300px;
            background-color: black;
            transition: all 300ms;
        }
        .poll:hover{
            width: 500px;
        }
    </style>
</head>
<body>
    <div class="poll"></div>
</body>
</html>

If you're having trouble implementing similar transitions in your own divs, check out the function below:

function renderPoll(){
container.innerHTML=''; //reset container
let poll1 = document.createElement('div');
let poll2 = document.createElement('div');

poll1.classList.add('poll-attr');
poll2.classList.add('poll-attr');

let innerTextPoll = Math.round(calcPerc()); 
poll1.style.width = calcPerc() + '%';
poll2.style.width = 100-calcPerc() + '%';

poll1.innerText = innerTextPoll + '%';
poll2.innerText = 100-innerTextPoll + '%';

container.appendChild(poll1);
container.appendChild(poll2);

}

Seeking assistance to make your poll animations stand out? Let me know your thoughts!

Answer №1

Expanding on your code and incorporating @Noel Maróti's insight, it is important to remember to set an interval for animating the polls once they have been added to the container.

function renderPoll() {
  container.innerHTML = ''; //clear the container
  let poll1 = document.createElement('div');
  let poll2 = document.createElement('div');

  poll1.classList.add('poll-attr');
  poll2.classList.add('poll-attr');

  let innerTextPoll = Math.round(calcPerc()); //calcPerc() calculates the percentage of YES 
  poll1.innerText = innerTextPoll + '%';
  poll2.innerText = 100 - innerTextPoll + '%';

  container.appendChild(poll1);
  container.appendChild(poll2);

  var target_length = 300;

  animatePoll(poll1, 0, (calcPerc()) * target_length / 100);
  animatePoll(poll2, 0, (100 - calcPerc()) * target_length / 100);

}

function calcPerc() {
  return 75;
}

function animatePoll(elem, from, to) {
  let id = null;
  let width = from || 0;
  var speed = 2.5;
  requestAnimationFrame(frame);

  function frame() {
    if (width < to) {
      width += speed;
      elem.style.width = width + "px";
      requestAnimationFrame(frame);
    }
  }
}


renderPoll();
.poll-attr {
  border: 1px solid blue;
  height: 50px;
  background: lightyellow;
}

.poll {
  height: 50px;
  width: 300px;
  background-color: black;
  transition: all 300ms;
}

.poll:hover {
  width: 500px;
}
<div class="poll"></div>
<div id="container"></div>

Answer №2

Here is a simple way to achieve it:

function animateWidth() {
  let id = null;
  const element = document.querySelector(".poll");   
  let width = 300; // initial width
  clearInterval(id);
  id = setInterval(changeWidth, 5); // adjust the number for different animation speed
  function changeWidth() {
    if (width == 500) { // stop animation at 500px width
      clearInterval(id); // stop animation
    } else {
      width++; 
      element.style.width = width + "px"; 
    }
  }
}

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

Touchwipe incorporation - single-page website script

Today has been dedicated to troubleshooting and searching for a solution regarding the integration of TouchWipe () on a custom one-page-site script based on Parallax that I found perfect for my latest project (). The script itself performs beautifully wit ...

Centering a button within a table-cell through movement

I'm facing an issue with aligning a button placed inside a table cell. The table setup is as follows: <b-table v-if="rows.length" :thead-tr-class="'bug-report-thead'" :tbody-tr-class="'bug-report-tbody& ...

Signaling an Event from a module in the node_modules directory to the Vue application

Is there a way to capture an event emitted by a node module and receive it in a Vue file? Sample code from the JavaScript node module: const EventEmitter = require('events') class Find extends EventEmitter { // code snippets here } class Fin ...

When a user taps on a link or anchor within a specific webpage on an iPhone, the font size will automatically increase

The issue is specific to iPhones. I have tested it on an iPhone 5 (landscape mode) and an iPhone 4s (landscape mode). For a visual demonstration, you can view the video here. I attempted to fix the problem by specifying the font size, but unfortunately, ...

The current HTML scraping results are showing a variation in numbers

I recently created a code to extract the price of a mutual fund into an excel sheet using VBA. It was working perfectly fine until last night when it suddenly started pulling in a different number, specifically the % return on the Dow at the top of the pag ...

Guide on merging all Vue js functions into a single js file?

As a newcomer to vue.js, I am in the process of consolidating several functions into one js file. Here is an example: example.js: function containObject(obj, list) { for (let i = 0; i < list.length; i += 1) { if (list[i] === obj) { return ...

Passing arguments from the command line to an npm script

The scripts section in my package.json is currently set up as follows: "scripts": { "start": "node ./script.js server" } This allows me to use npm start command to initiate the server. All working well so far. However, I ...

Invoking a shared controller function in AngularJS from a separate controller

My main objective is to retrieve the current logged-in user by calling back to the server when a visitor lands on the site while still logged in. The challenge I face is determining which controller will be active since it's uncertain which page the v ...

Attempting to position a centrally aligned div block containing images towards the left side

I'm having an issue with aligning multiple images on my webpage. I want them to be left justified when the page is resized, while still keeping the div block centered. Currently, they are all being centered: See below: Here is the HTML and CSS code ...

Include characteristics in JSX.Element following its declaration

Suppose I have an item in a dictionary with the following structure: let item = { element: <myElement/>, color: "#0e76a8" } Is it possible to add a style attribute to the item.element within the render() method? I tried the following appro ...

Intrusive JQuery Code Incorporating Itself into SharePoint 2010's HTML Markup

There seems to be an issue with my content editor web part wherein the menu, which is clickable and hoverable due to the jQuery installed, is causing some unexpected behavior. Whenever the menu is clicked or hovered over, it changes the content in the adja ...

What steps can be taken to modify the style of a single button belonging to a broader group of elements?

Is there a way to hide the save button within a Vue Modal without affecting other buttons with the same class? .btn.btn-primary { display: none; } Simply targeting .btn-primary in the CSS affects all elements with that class, and adding .modal woul ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

The layout of my website is perfect when my laptop's zoom is set to 90%, but at 100% it starts overflowing

Currently, I am in the process of building a website on my laptop while following an instructor's video tutorial. It has been important for me to set the same pixel measurements as the instructor in order to replicate the design they provided. However ...

Tips for optimizing AngularJS performance with large scopes

Currently, I am working on an Angular app for my company and have encountered a major issue. The app has become extremely slow, even after trying to optimize it using techniques like onetimebind and track by. Despite initial improvements, the performance i ...

What steps can I take to allow a third-party JavaScript to access my TypeScript object?

I am working on an Angular application and I have a requirement to develop an API for a third-party JavaScript that will be injected dynamically. public class MyApi{ public callSomeFunction():void{...} public getSomeValue():any {...} } var publicA ...

Programmatically link validation rules to form fields

I have implemented validation in a form using VeeValidate with Vue.js. Each input displays an error message related to the specific field where the error occurred. <div class="input-group"> <input type="date" class= ...

Having trouble with the jQuery slideUp function?

Exploring some jQuery features for a trial run, I stumbled upon an unusual behavior. Perhaps someone in this forum can provide some insight. Keep in mind that this is all just test code, so please overlook any messy aspects. Currently, I am working with ...

Issues arise with the functionality of Zurb Foundation 5 tabs

Utilizing the tabs feature in ZURB Foundation 5, I've noticed that clicking on a tab changes the hash in the URL. However, I actually want to prevent this behavior as I rely on the hash for managing page loads. Although I attempted to use preventDef ...

Is it possible to establish a connection between React and a MySQL Database?

I've been encountering issues with connecting to a remote database in React. Despite my efforts, I haven't been successful in establishing the connection. I have tried various solutions without any luck. The goal is simple - I just want to connec ...