Is it possible to include two of these on a single page with unique variables? (Using JQuery)

I am looking to create two similar pages, each with different percentages. However, when I try modifying the JS or changing class/ID names, it keeps pulling data from the first SPAN element.

http://jsfiddle.net/K62Ra/

<div class="container">
<div class="bw"></div>
<div class="show"></div>
<div id="bar" data-total="100">
    <div class="text">Currently at <br/><span>70</span><br><i>Click To Give</div>
</div>

All necessary JS and CSS code can be found in the provided Fiddle link.

Thank you for your help.

Answer №1

Here is a reliable solution:

http://jsfiddle.net/K62Ra/7/

$('.bar').each(function() {
    var percentStart = 0;
    var total = $(this).data('total');
    var percent = parseInt($(this).find('span').html());

    $(this).find('> div').addClass("load");

    var that = this;
    var timer = setInterval(function() {
        $(that).siblings('.show').css('height', percentStart/total*100+'%');
        $(that).css('height', percentStart/total*100+'%');
        $(that).find('span').html('%'+percentStart);
        if(percentStart<percent) { percentStart=percentStart+1; return; }
        clearInterval(timer);
    }, 35);
});

Make sure to end the interval properly to avoid it running indefinitely without purpose.

Answer №2

I made a modification by changing the id="bar" to a class attribute. Then, I implemented an iteration through each element with the class .bar. You can view the updated code snippet in this fiddle: http://jsfiddle.net/K62Ra/4/

Here is the revised code:

$('.bar').each(function (index, element) {
  var percent = $(this).find('span').html();
  var total = $(this).attr('data-total');
  var percentStart = 0;

  setInterval(function () {
    $('.show').css('height', percentStart / total * 100 + '%');
    $(this).css('height', percentStart / total * 100 + '%');
    $(this).find('span').html('%' + percentStart);
    if (percentStart < percent) {
        percentStart = percentStart + 1;
    }
  }, 35);

});
$(".bar div").addClass("load");

Answer №3

As mentioned in previous comments, having duplicate ids can lead to issues and errors in design.

To address this problem, you can make some changes. Instead of using id selectors '#' for divs, opt for class '.' like

$('.bar')

The next step would be to ensure each 'container' div's uniqueness by utilizing a closure

$('.container').each(function(){
   var x
   var y
   .
   .
});

Lastly, refrain from directly selecting elements in the selector and utilize $(this) along with .find() to stay within the current 'container' div.

http://jsfiddle.net/K62Ra/5/

$('.container').each(function(){
    var percent = $(this).find('div.bar div span').html();
    var total = $(this).find('div.bar').attr('data-total');
    var percentStart = 0;

    var that = $(this);

    setInterval(function() {
      that.find('.show').css('height',percentStart/total*100+'%');
      that.find('div.bar').css('height',percentStart/total*100+'%');
      that.find('div.bar div span').html('%'+percentStart);
      if(percentStart<percent) {percentStart=percentStart+1;}
    },35);

    $(this).find("div.bar div").addClass("load");
});

Answer №4

Among the myriad answers provided here, I suggest running a validation on your HTML code. Additionally, some of your CSS settings were causing glitches while scrolling due to fixed background images not moving along.

My approach differed slightly from the rest as I opted for $.animate and a step function instead of using setInterval. Just like others, I selected a class named 'fill-me-up' to target each item individually.

Here is the updated Fiddle link: http://jsfiddle.net/LFbKs/6/

NOTE: Take a look at the fiddle as I made minor adjustments to the HTML and significant changes to the CSS.

// for each item we need to "fill up"
$('.fill-me-up').each(function(){

    // cache DOM references
    var this$ = $(this)
      , bar$ = this$.find('.bar')
      , show$ = this$.find('.show')
      , span$ = bar$.find('div span')

      // the target percentage height for this item
      , p = span$.text()

      // combine '.bar' and '.show' so we can apply the animation to both
      , toAnimate = $().add(bar$).add(show$);

    // add class causing fade-in
    bar$.find('div').addClass('is-visible');

    // animate height to target height over 2 seconds and 
    // at each step, update the span with a truncated value
    toAnimate.animate(
        { height: p+'%' },
        { 
            duration: 2000,
            step: function( currentStep ) {
                span$.html('%'+currentStep.toFixed(0));
            }
        }
    );
});

Cheers

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

Unable to access the newly created object's properties following the instantiation of a new resource in AngularJS

Currently, I am in the process of developing a new Resource utilizing AngularJS that falls under the category of Person. After successfully creating this resource, my goal is to retrieve the id associated with the new resource from the server. it('sh ...

Getting a list of connected users on a PeerJS server using Express is simple and straightforward. Follow these steps to

Trying to incorporate PeerJS, a webRTC library, into a game and utilizing their server for user discovery has proven challenging. The goal is to manage a list of connected users, but grappling with the PeerJS server has been difficult. The documentation s ...

Retrieve the image from a protected internet service

In need of assistance with a REST web service that generates images in png or jpeg format, rather than providing an image URL. This particular service is protected by basic authentication, requiring clients to include a username and password in the header ...

"Enhanced file manager: Elfinder with multiple buttons to seamlessly update text input fields

Every button is responsible for updating the respective element: <input type="text" id="field" name="image" value="<?php echo @$DuzenleSonuc[0]['image']; ?>" /> I need to ensure that each button updates the correct field: onclick ...

Exploration Pointers for Foursquare Web Users

Why does my search suggestion keep returning '568 broadway' even after I have updated the authentication to my client id and client secret? Currently running on: https://api.foursquare.com/v2/venues/suggestCompletion?ll=40.7,-74&query=fours ...

What is the best way to horizontally center a div with the layout attribute set to "row"?

I am currently working with a grid composed of cards from the Angular Material library. The issue I am facing is that the cards have a fixed size, which results in extra space on the right immediately after wrapping. My goal is to eliminate this space by ...

Having trouble with submitting a form using @submit in Vue 3

I am facing an issue with the vuejs @submit.prevent feature in my login form. When I click the login button on my website, it does not work as expected. Even after adding a catch error in the function, the console still shows nothing. Can someone please as ...

Arrange divs in a stack fashion

Currently, I have a table-styled three-column set of divs. I would like these columns to stack vertically on mobile devices. I think this can be achieved using the float method, but the titles and descriptions for each column are in separate rows (divs), ...

The Chrome Extension is unable to recognize a portion of the URL following the # symbol in the contentscript.js code

I am currently developing an extension for a specific website that I don't have ownership of. The URLs on this site only change after a /#/. For instance, starting from the URL .../#/PF/charts/patients/419d3081-5e20-4347-a852-52b2c333ce85/summary W ...

Save message in the callback function of the express app.listen method

I'm currently integrating winston logging into my application and aiming to switch all info or error level logs with winston's .info and .error. Everything seems to be working well except when trying to log an info message from within the app.lis ...

Can you explain the purpose of the window.constructor and global.constructor functions in JavaScript?

Can someone explain the purpose of this function? I've been searching for information but can't find anything. I tested it in Firefox: window.constructor() // TypeError: Illegal constructor new window.constructor() // TypeError: Illegal constru ...

Comparing GET and POST actions in mod_rewrite search form

Hey there, thank you for taking the time to address this query. I have implemented a live search form using jQuery on my website. The search bar is present on every page and functions well. Now, I am looking to enhance its functionality. When users press ...

Implement a delay before sending a new ajax request with jQuery in order to optimize performance

I've got a collection of hyperlinks that lead to various HTML pages. <ul id="item-list"> <li><a href="assets/data/item1.html">Item 1</a></li> <li><a href="assets/data/item2.html& ...

A unique CSS transition effect applied after toggling a class

Greetings everyone I recently created this code pen https://codepen.io/alexyap/full/MmYvLw/. I am facing a challenge with my navigation menu. The transition in works perfectly, but the fade-out effect looks terrible. I'm struggling to figure out this ...

Is it possible for the controller of a modal window to have access to functions within the parent controller

If you were to launch a modal window using $modal.open from an angular directive, would the modal window be able to access functions defined within the parent directive? Below is the code for the directive controller: function parentFunction() { re ...

Creating a custom button in PHP

Currently, I am in the process of developing a shopping cart feature. One key requirement is to send both the product ID and the desired quantity chosen by the user to another file named cart.php. Below is an excerpt from my code snippet: for($i=0;$i< ...

Utilizing nested v-for in Vue.js with lodash's groupBy function

When fetching data from a database, I am using lodash groupby to group my data like so: var vm = this axios.get(this.buildURL()) .then(function(response) { Vue.set(vm.$data, 'model', response.data.model) vm.groupData = _.groupBy(vm.model ...

Best practice for organizing sort icons in a table with React and MaterialUI

I am currently implementing the following code in a tsx component. I am still learning about the various layout options available. You can view my code on this sandbox link. import React from "react"; import { ArrowDropUp, ArrowDropDown } from "@materia ...

Using jQuery for a smooth transition with fadeIn and fadeOut Effect

After reviewing various posts in the community, I have not been able to find a solution for my specific issue. However, I did come across some HTML and jQuery code that was somewhat similar but didn't quite meet my requirements. Just to be transparent ...

An unusual icon with three varying sizes in a single file

I have come across an interesting favicon file. Click here to download the favicon file Unfortunately, I am unable to upload this image file as it does not meet the required format standards. Upon viewing the file in Windows 7, a fascinating discovery w ...