0

I have this simple html generated by Adobe Muse (I can't change it directly):

<div id="randomID" title="counter"><p>1290</p></div>

And I have this options from the CountUp script:

var counter = new countUp( 'counterID', 0, *Some Value*, 0, 2 ); 
counter.start(); // run counter

The question is:

I need to find ALL elements with title="counter", set ID's for each <p>, then get value from <p>1290</p>, put it into the script options and run each counters separately.

I tries to do this:

var counters={};
$("[title='counter']").each(function(){
counters['counter' + this.id]=$(this).children('p').html();   });

$.each( counters, function( id, value ) {
var id = new countUp( $('#' + id), 0, value, 0, 2 );
id.start();
});

Where I'm wrong?

1 Answer 1

1

I believe what you are looking for might be this:

/* jquery */
var result={};
$("div[title=counter]").each(function(){
    result[this.id]=$(this).find("p").html();    
});
console.log(result);

/* pure js */
var result2={};
var allP=document.getElementsByTagName("p");
for(var i=0, len=allP.length; i<len; i++){
    var parent=allP[i].parentNode;
    if(parent.nodeName=="DIV" && parent.title=="counter")
        result2[parent.id]=allP[i].innerHTML;
}
console.log(result2);

EDIT:

I do not see, why you use

counters['counter' + this.id]=(...) // why adding 'counter'?

which adds 'counter' to your key inside array, you could have as well just used

counters[this.id]=(...)

then in your $.each 'loop' you pass jQuery object instead of id string as required by showcase you provided. If you keep (for any reason) adding string 'counter' to key in your array, you will have to transform your loop like this:

$.each( counters, function( id, value ) {
    // you should name variables differently, maybe key and counter, or key and id, just avoid naming two different variales same
    var id = new countUp( id.substr(7), 0, value, 0, 2 );
    id.start();
});

So perhaps this might work as well and might be understood better

$.each( counters, function( key, value ) {
      var objCounter = new countUp(key.substr(7), 0, value, 0, 2);
      objCounter.start();
      // which could be replaced by (new countUp(key.substr(7), 0, value, 0, 2)).start();
});
Sign up to request clarification or add additional context in comments.

3 Comments

It's so easy to understand! Thank you!
I have just added edit to my answer so you can get your code right.
Omg, I was trying to find solution about four hours.. And it's so easy )) Thank you, I clearly understand! It's work like a charm =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.