Pass value from div to JS

In php file I have div with id

and returned data, see code:

<div id="dom-target" style="display: none;" data-stuff="2017, 8, 20, 0, 0"></div>

      

Ok, now I need to pass the data value of the data to a new Date call (countdown), I try to use a variable, but it shows NaN

like

var ar = $('#dom-target').data('stuff'); 

      

Finally, the JS code:

if (jQuery().mbComingsoon) {
    var ar = $('#dom-target').data('stuff');
    jQuery('#myCounter').mbComingsoon({expiryDate: new Date(ar), speed: 500});
    setTimeout(function () {
        jQuery(window).resize();
    }, 200);
}

      

Apparently I can't use new Date(ar)

to call data from a div?

Thank!

+3


source to share


3 answers


Instead of trying to parse '2017, 9, 20, 0, 0' in your javascript, why don't you use a more appropriate date format in your html like:



data-stuff="2019-08-20 00:00"

+2


source


new Date('2017, 8, 20, 0, 0')

returns Invalid Date

. This is because it expects separate arguments instead of a string containing all of them.

Since you cannot call apply

directly on the constructor, it requires some magic:



var raw = '2017, 8, 20, 0, 0',
    parts = [null].concat(raw.split(',').map(function (item) {
        return parseInt(item.trim(), 10);
    })),
    _Date = Function.prototype.bind.apply(Date, parts);

console.log(parts, new _Date); // Wed Sep 20 2017 00:00:00 GMT-0400 (EDT)

      

There is a decent explanation here.

+1


source


You can do

...
// Get data of element and split it into an array
var ar = $('#dom-target').data('stuff').split(',');
// Use this array to get a Date
var parsedDate = new Date(Date.UTC.apply(null, ar));
// Do your logic
jQuery('#myCounter').mbComingsoon({expiryDate: parsedDate , speed: 500});
...

      

0


source







All Articles