From jQuery to JavaScript Without Tears

Un-possible?

Looking for a cute set of progress bars for my app, I searched around and found a great blog post with a few examples. Originally I had zero intention of using animated progress bars, but they seemed to fit well enough for my needs and actually added a bit of, dare I say, pizazz, to the page.

So I go to play around with the code… aaand it’s jQuery.

facepalm, the other Picard maneuver

On a positive note, usually I can tell what’s going on in jQuery, as if reading psuedocode. It feels sort of like guessing what a Spanish billboard says as an English speaker (to me, anyway). I suppose the faster way to move forward with my project would have been to just import some jQuery via CDN, but I decided that I wanted to fully understand what was going on, and thus decided to rewrite it in plain JavaScript.

“Mayhaps, in the span since first we met, an AI hath vanquished thee, mighty jQuery,” I said to my screen as I Googled “jQuery to JavaScript converter.”

Surprisingly, there was a tool which actually did something, or enough to get me started. Despite some very strange copy on their page, the WorkVersatile converter did deliver on their promise of only “some errors” after conversion.

The original jQuery:

$(".animated-progress span").each(function () {
$(this).animate(
{
width: $(this).attr("data-progress") + "%",
},
1000
);
$(this).text($(this).attr("data-progress") + "%");
});

… and the invalid JavaScript output:

document.querySelectorAll(".animated-progress span").each(function () {
this.animate(
{
width: this.attr("data-progress") + "%",
},
1000
);
this.innerText = this.attr("data-progress" + "%");
});

My end product; instead of innerText, I used the Django template to fill in the element’s text:

document.querySelectorAll(".animated-progress span").forEach(ele => { 
  
  ele.animate(
  [
    { width: ele.getAttribute("data-progress") + "%", },
  ], 
    {
      duration: 1000,
      fill: "forwards"
    }
  );

});

Leave a Reply

Your email address will not be published. Required fields are marked *