0

I have a div that show a counter number, when data for this div be static all of things is good but, I wanna set data with Jquery or with ajax request. I tested this codes but not working

HTML Code

<div id="NewVistors" class="number count-to" data-from="" data-to="" data-speed="" data-fresh-interval="20"></div>

Jquery Code:

<script>
    window.onload=function(){

        var div = $('#NewVistors');
        div.data('data-from',0);
        div.data('data-to',20000);
        div.data('data-speed',1000);
        div.data('data-fresh-interval',20);
        console.log(div.data('data-to'));           
        }

</script>

When I run this codes in my console I can get data-to attribute, that is 20000

1

4 Answers 4

0

Here you go with the solution https://jsfiddle.net/5mwdcugq/

var div = $('#NewVistors');
div.attr('data-from',0);
div.attr('data-to',20000);
div.attr('data-speed',1000);
div.attr('data-fresh-interval',20);
console.log(div.attr('data-to'));           
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="NewVistors" class="number count-to" data-from="" data-to="" data-speed="" data-fresh-interval="20"></div>

Here you go with one more solution https://jsfiddle.net/5mwdcugq/1/

var div = $('#NewVistors');
div.data('from',0);
div.data('to',20000);
div.data('speed',1000);
div.data('fresh-interval',20);
console.log(div.data('to'));           
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="NewVistors" class="number count-to" data-from="" data-to="" data-speed="" data-fresh-interval="20"></div>

0

.data() uses internal cache it only uses uses the data attribute as the default value only. On performing update operation via .data(key, value) then DOM is not updated. Also the usage is also not correct, you don't need to prefix data- when using the method.

div.data('from',0);

I think you need to use use .attr() to get and set attribute value.

var div = $('#NewVistors');
div.attr('data-from',0);
0

You can set data using two different method

1st method

window.onload=function(){
    var div = $('#NewVistors');
    div.data('from',0);
    div.data('to',20000);
    div.data('speed',1000);
    div.data('fresh-interval',20);
    console.log(div.data('to'));           
}

2nd method

window.onload=function(){
    var div = $('#NewVistors');
    div.attr('data-from',0);
    div.attr('data-to',20000);
    div.attr('data-speed',1000);
    div.attr('data-fresh-interval',20);
    console.log(div.attr('data-to'));           
}
0

Please add this code into your function.

$("#NewVistors").html(div.data('data-to'));      

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.