Having trouble with the jQuery each function's functionality

I am creating circular counters for surveys by generating a counter for each answer option.

Currently, I am utilizing this "plugin":

Issue:

The problem lies in the plugin not fetching the text value from the <div> element and failing to draw counters for each div.

Note: It is functioning properly for a single div

Example:

http://jsbin.com/AHUkoBA/3/edit

http://jsfiddle.net/mgcq9/

HTML:

<div class="pollAnswerBar">15</div>
<div class="pollAnswerBar">50</div>
<div class="pollAnswerBar">75</div>

JS:

jQuery(document).ready(function() {

    function drawCounter(percent) {
        jQuery('div.pollAnswerBar').html('<div class="percent"></div><div id="slice"' + (percent > 50 ? ' class="gt50"' : '') + '><div class="pie"></div>' + (percent > 50 ? '<div class="pie fill"></div>' : '') + '</div>');
        var deg = 360 / 100 * percent;
        jQuery('#slice .pie').css({
            '-moz-transform': 'rotate(' + deg + 'deg)',
            '-webkit-transform': 'rotate(' + deg + 'deg)',
            '-o-transform': 'rotate(' + deg + 'deg)',
            'transform': 'rotate(' + deg + 'deg)'
        });
        jQuery('.percent').html(Math.round(percent) + '%');
    }

    jQuery('.pollAnswerBar').each(function() {
        var percent = jQuery(this).text();
        console.log(percent);
        drawCounter(percent);
    });

});

Answer №1

Check out this functional fiddle: http://jsfiddle.net/fKPb6/

The issue was with modifying all elements at once instead of specifying each one individually.

Here is the revamped code snippet.

JavaScript:

jQuery(document).ready(function () {

    function drawCounter(percent, element) {
        jQuery(element).html('<div class="percent"></div><div id="slice"' + (percent > 50 ? ' class="gt50"' : '') + '><div class="pie"></div>' + (percent > 50 ? '<div class="pie fill"></div>' : '') + '</div>');
        var deg = 360 * (percent / 100);
        jQuery('#slice .pie', element).css({
            '-moz-transform': 'rotate(' + deg + 'deg)',
                '-webkit-transform': 'rotate(' + deg + 'deg)',
                '-o-transform': 'rotate(' + deg + 'deg)',
                'transform': 'rotate(' + deg + 'deg)'
        });
        jQuery('.percent', element).html(Math.round(percent) + '%');
    }

    jQuery('.pollAnswerBar').each(function (index, element) {
        var percent = jQuery(element).text();
        console.log(percent);
        drawCounter(percent, element);
    });

});

By narrowing down the selection to specific elements within their scope, like jQuery('.percent', element), you are now targeting the correct elements rather than all instances of .percent.

Answer №2

To pass the event handler, you can follow this method:

// Insert the event handler in this manner
jQuery('.pollAnswerBar').each(drawCounter);

Then, proceed to call the function like so:

// Define the event handler with parameters received from .each()
function drawCounter(i, elm) {
    var percent = $(elm).text();
    jQuery(elm).html('<div class="percent"></div><div id="slice"' + (percent > 50 ? ' class="gt50"' : '') + '><div class="pie"></div>' + (percent > 50 ? '<div class="pie fill"></div>' : '') + '</div>');
    var deg = 360 * (percent / 100);
    jQuery('#slice .pie', elm).css({
        '-moz-transform': 'rotate(' + deg + 'deg)',
            '-webkit-transform': 'rotate(' + deg + 'deg)',
            '-o-transform': 'rotate(' + deg + 'deg)',
            'transform': 'rotate(' + deg + 'deg)'
    });
    jQuery('.percent', elm).html(Math.round(percent) + '%');
}

View the demonstration: Fiddle


Alternatively, you can utilize only the this keyword without any passed parameters as shown below:

// Implement the event handler here
jQuery('.pollAnswerBar').each(drawCounter);

// Create the event handler using `this`
function drawCounter() {
    var percent = $(this).text();
    jQuery(this).html('<div class="percent"></div><div id="slice"' + (percent > 50 ? ' class="gt50"' : '') + '><div class="pie"></div>' + (percent > 50 ? '<div class="pie fill"></div>' : '') + '</div>');
    var deg = 360 * (percent / 100);
    jQuery('#slice .pie', this).css({
        '-moz-transform': 'rotate(' + deg + 'deg)',
            '-webkit-transform': 'rotate(' + deg + 'deg)',
            '-o-transform': 'rotate(' + deg + 'deg)',
            'transform': 'rotate(' + deg + 'deg)'
    });
    jQuery('.percent', this).html(Math.round(percent) + '%');
}

Check out the demo: Fiddle

Answer №3

A more efficient way to achieve the same result is by utilizing jQuery's text() method like so:

function updateCounter(){
        var value = jQuery(this).text();
        console.log(value);
        displayCounter(value);
    });
jQuery('.resultBar').updateCounter();

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

What is the best way to create a jQuery object that encapsulates a snapshot of a DOM element?

Recently, I discovered that a JQuery object retains a reference to a DOM object. As the HTML is modified, the context of the JQuery object also changes. However, my concern now is how to log these changes without altering the history records of the JQuer ...

Struggle with incorporating a file

As part of the login process, I have two options available: easy login and standard login. The easy login requires an employee ID, birthdate, and captcha answer, while the standard login asks for first name, last name, birthdate, and captcha. To facilitate ...

Typedi's constructor injection does not produce any defined output

I am utilizing typedi in a Node (express) project and I have encountered an issue related to injection within my service class. It seems that property injection works fine, but constructor injection does not. Here is an example where property injection wo ...

Extract individual export icons from the React icon library

I've recently put together an icon package and am ready to share it with the world under the name @rct/icons. Here's a glimpse at my package.json: { "name": "@rct/icons", "version": "1.0.0", "sc ...

Using Javascript to dynamically add variables to a form submission process

Looking to enhance my javascript skills, I've created a script that locates an existing id and exchanges it with a form. Inside this form, I'm aiming to incorporate javascript variables into the submit url. Unsure if this is feasible or if I&apo ...

Initiate a unidirectional ajax request

My WCF service has a slow processing time when called for the first time, but caches the results in HttpRuntime.Cache afterwards. To initialize this cache, I want to initiate a fire-and-forget ajax call from JavaScript. Currently, my page contains the fol ...

Maintaining Style Values with jQuery While Navigating Back

I am facing an issue with maintaining the style value when returning to a page from another. My jQuery code is responsible for displaying my menu. $( "#burger" ).click(function() { if ($("#burger").hasClass("closed")) { $( "#menu" ).animate({ ...

Sending the value from a for loop through AJAX and populating it into a form field

Currently, I have implemented a piece of JavaScript code that captures user input, sends a request to an endpoint using AJAX, and appends a specific field from the returned results as an option within a datalist. This functionality is working perfectly fin ...

Struggling to implement nested routes with react-router-dom version 5.2.0?

I'm currently working on implementing nested routing in React using react-router-dom 5.2.0. For a better understanding of the project, you can access the CodeSandbox link here: https://codesandbox.io/s/nested-routes-8c7wq?file=/src/App.js Let's ...

What sets my project apart from the rest that makes TypeScript definition files unnecessary?

Utilizing .js libraries in my .ts project works seamlessly, with no issues arising. I have not utilized any *.d.ts files in my project at all. Could someone please explain how this functionality is achievable? ...

A guide to retrieving the timezone based on a specific address using the Google API

I need to utilize the Google API time zones, which requires geocoding the address to obtain the latitude and longitude for the time zone. How can I achieve this using a value from a textarea? Here are the 2 steps: Convert the textarea value into a geoc ...

What is the best way to conceal a sticky footer using another element?

I have a footer that remains fixed at the bottom of both long and short pages. Below is the CSS code for this footer: .footer{ position: absolute; bottom: 0; width: 100%; height: 100px; background-color: white; } My goal is to achieve a 'r ...

Jquery loop using closures

I've been working on creating a plugin that involves passing handler functions for specific events. Consider the scenario below: I have two buttons, and when I click button 1, its label is supposed to change to 'Button A', while clicking but ...

Error in Express Post Request: Headers cannot be modified after being sent to the client

I am a beginner in Node.js and I am facing some challenges while working on an app for learning purposes. I encountered the following issue: Error: Can't render headers after they are sent to the client. I am unsure of how to resolve it. C:\Us ...

What is the best way to redirect users to the login page when they are logged out from a different tab or window?

Ensuring user authentication and managing inactivity are crucial components of my Nodejs application, where I leverage cookie-session and passport.js. app.use(require("cookie-session")({ secret:keys.session.secret, resave:false, saveUninitiali ...

What is the best way to ensure the snackbar occupies the full width on smaller screens?

After reviewing this commit: https://github.com/callemall/material-ui/commit/11695dcfa01e802797115d42c6d3d82d7657b6ab#diff-e9014062cd8e3b4344ab619966f35ef2 In the latest update, the snackbar no longer expands to 100% width on mobile screens. Can someone p ...

What is the best way to pause function execution until a user action is completed within a separate Modal?

I'm currently working on a drink tracking application. Users have the ability to add drinks, but there is also a drink limit feature in place to alert them when they reach their set limit. A modal will pop up with options to cancel or continue adding ...

Is there a way to utilize redux to trigger the opening of my modal when a button is clicked?

I'm facing a challenge with opening my modal using redux when clicking <CheckoutButton/>. Despite my efforts, the modal keeps appearing every time I reload the browser. I've reviewed my code but can't pinpoint the issue. What am I doin ...

The color is missing in the custom button of Bootstrap v5.2

Trying to incorporate a unique button class in Bootstrap with an iris-purple color. Utilized Sass for creating the custom button: @import "../node_modules/bootstrap/scss/bootstrap"; $mynewcolor:#5D3FD3; .btn-purple { @include button-variant( ...

Utilize jQuery to wrap text within <b> tags and separate them with <br> tags

Upon receiving output in html string format from services, I am presented with the following: "<html>↵<h1>↵Example : ↵<br>Explanation↵</h1>↵<hr>↵<b>key1 : ABCD <br>key2 : 2016-10-18-18-38-29<br> ...