What is preventing the usage of $(this) in the jQuery .animate() function?

My progress bar is built with Bootstrap and here is the HTML code:

$(".progress-bar").animate({
      width: $(this).data('width') + '%'
    }, 2500);
<!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    <div class="alert alert-success">
      <div class="skill-name">ON PROGRESS 357/487</div>
      <div class="progress">
        <div class="progress-bar progress-bar-primary" role="progressbar" data-width="70">
        </div>
      </div>
    </div>

Why isn't the jQuery code above working when I use $(this).data('width') + '%'? But it works if I use

$(".progress-bar").data('width') + '%'?
Thank you for your help.

Edit

If I use

$(".progress-bar").data('width') + '%'? It will change all <code>.progress-bar
.

Answer №1

The issue at hand involves scoping. When using the .animate() method, keep in mind that it only scopes this within its complete callback. Otherwise, it typically scopes it to the caller.

To address this, store your selection in a variable and utilize it consistently throughout your code. This not only maintains the correct scope but is also more efficient as it eliminates the need to re-wrap this in a jQuery object.

var progressBar = $(".progress-bar");
progressBar.animate({
  width: progressBar.data('width') + '%'
}, 2500);

If you are working with multiple progress bars, employ .each() to iterate over them and apply the animation to each element while they remain in scope.

$(".progress-bar").each(function(i, item) {
  var progressBar = $(item); // Using $(this) would also suffice
  progressBar.animate({
    width: progressBar.data('width') + '%'
  }, 2500);
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="alert alert-success">
  <div class="skill-name">ON PROGRESS 357/487</div>
  <div class="progress">
    <div class="progress-bar progress-bar-primary" role="progressbar" data-width="70">
    </div>
  </div>
</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

PHP code that removes a table row from a database

Can anyone help me troubleshoot my code? My PHP seems to be functioning, but for some reason the delete button is not working! if(isset($_POST['delete'])) { $ID = $_POST['value']; $delete = "DELETE FROM tbl_document WHERE ID = ...

Making an API call using jquery and getting an empty response

I've been struggling to tweak an API call to load via jQuery after the page has loaded. While someone else assisted me, I still can't seem to get it working. The code is in PHP, and I'm not entirely sure if the syntax is correct. - Take a ...

Angular Floating Panels: A Guide to Creating Dynamic User Interfaces

In the process of developing an angular app, I require a dock-able panel. After researching available controls online, I found them difficult to use and they compromised our screen layout. As a result, I am considering building a custom dock panel from s ...

Ways to manage intricate HTML tables using Beautiful Soup

Currently, I am facing an issue while loading an HTML file into a data frame using BeautifulSoup. The table I am parsing contains a nested table in every row, and I am unsure of how to handle this situation as it is resulting in an AssertionError. The prob ...

Unable to establish a breakpoint in a source-mapped file (illustrated using jQuery)

Having trouble setting a breakpoint on a minified JavaScript source file that is mapped to real sources using a source map file. An example of this problem can be seen on the website jquery.com. On this particular site, the imported script is jquery.min. ...

The mobile display is crowded with stacked cards

Everything was going smoothly with the three cards I created, but when viewed on mobile devices they end up stacking on top of each other. This is not the result I had anticipated after importing all the necessary jQuery and CSS files. <link rel="sty ...

Can I access properties from the index.html file within the Vue.js mount element?

<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="widt ...

Strange CSS/browser storage glitch

UPDATE: JUST REALIZED THIS ISSUE IS ONLY OCCURRING ON FIREFOX, NOT CHROME ANOTHER UPDATE: Oddly enough, this problem only occurs locally. When I push it to GitHub, everything works fine. So strange. I suppose that means it's not a major issue. On my ...

Navigate to the Bootstrap Panel body when the relevant link is clicked

I am facing an issue with a long list of panels that are tedious to scroll through. To make navigation easier, I am attempting to create a shortcut link at the top of the page. Below is the code for the shortcut: <a data-toggle="collapse" data-parent ...

Discover how to extract a whole number (and *exclusively* a whole number) using JavaScript

Is it possible to convert a string to a number in a way that only integers produce a valid result? func('17') = 17; func('17.25') = NaN func(' 17') = NaN func('17test') = NaN func('') = NaN func('1e2& ...

Having trouble with drop down modification in Firefox

I have encountered an issue with my code that is designed to modify 2 drop down menus on page load and selection. The first menu should adjust based on the main categories related to the page category upon loading the page. The second menu offers different ...

Troubleshooting jQuery masonry problem related to initial display and height settings

Within a div, there is a masonry container with the inline style property display:none. With several divs on the page, clicking their respective buttons during load causes them to switch like a slideshow. This disrupts masonry's ability to calculate t ...

Missing td data when using Beautiful Soup to parse HTML tables in Python

When attempting to extract a table using Beautiful Soup, I encounter an issue. from selenium import webdriver from bs4 import BeautifulSoup import pandas as pd import numpy as np import lxml import xlrd HorseNo = ["T421"] ...

Inconsistent animations on Firefox with animate.css

Rock, Paper, Scissors! Greetings, I've been honing my coding skills by developing an HTML game utilizing these fantastic CSS3 animations paired with jQuery. Unfortunately, I've encountered a frustrating issue with Firefox as it only plays the a ...

Utilize ASP to limit the application of a CSS file exclusively to the child page

My website consists of a master page and several child pages. I have created specific CSS classes for styling. However, I only want certain child pages to utilize these styles while the master page should always use them. How can I limit the access to th ...

Display an additional HTML page without altering the existing one

First of all, I would like to apologize for my poor English. Attending a French school didn't provide much opportunity to practice other languages. I have a header.html on my website that I am unable to modify because it is not owned by me. However, ...

Django navigation bar customization

I attempted to implement a navigation bar on my Django website, but encountered an error stating "Reverse for 'about' not found. 'about' is not a valid view function or pattern name." I followed this solution from [Stack Overflow][1] in ...

What is the best method to align a form in three columns from each side without relying on Bootstrap?

Is there a way to center the form inside a card with 3 columns on each side, so that the form appears in the middle occupying about 6 columns without relying on Bootstrap, Materialize or any similar framework? Thanks! <div class="card"> & ...

Swapping out bullet points for delicious food icons in an unordered list on an HTML page

I am working with the following code snippet: <div id="instructions"> <h3>Get it done</h3> <ol> <li>In a blender add the eggs, chocolate powder, butter, flour, sugar and milk.</li> <li>Then whisk ...

Deactivate an option within an angularjs multi-select menu

Currently, I am utilizing an angularjs multiselect box which is displayed below: https://i.stack.imgur.com/w6ffN.png Here is the html code snippet: <select multiple ng-options="Language.LangID as Language.LangName for Language in AllLanguages " ng-mo ...