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

M.Ghavam
  • 101
  • 4
  • 16

4 Answers4

0

Please add this code into your function.

$("#NewVistors").html(div.data('data-to'));      
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>
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
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);
Satpal
  • 132,252
  • 13
  • 159
  • 168
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'));           
}
Super User
  • 9,448
  • 3
  • 31
  • 47