Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Alternative to dataset for Countdown Timer

  • This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #157444
    Ole Kristian
    Participant

    Hi

    Im making a Countdown Timer for a website and need it to support as many browsers as possible. Currently it does not have a very broad support.

    I have read that the dataset element is not the best way to go for maximal browser support, however i cant find a good way to make it work without. Here is my code:

    // set the date we're counting down to
    var target_date = new Date("Feb 24, 2014 20:00:00").getTime();
    
    var Clock = (function(){  
      var exports = function(element) {
        this._element = element;
        var html = '';
        for (var i=0;i<6;i++) {
          html += '<span>&nbsp;</span>';
        }
        this._element.innerHTML = html;
        this._slots = this._element.getElementsByTagName('span');
        this._tick();
      };
      exports.prototype = {
        _tick:function() {
          var time = new Date().getTime();
          var seconds_left = (target_date - time) / 1000;
          // do some time calculations
          var days = parseInt(seconds_left / 86400);
          seconds_left = seconds_left % 86400;
    
          var hours = parseInt(seconds_left / 3600);
          seconds_left = seconds_left % 3600;
    
          var minutes = parseInt(seconds_left / 60);
          this._update(this._pad(days) + this._pad(hours) + this._pad(minutes));
          var self = this;
          setTimeout(function(){
            self._tick();
          },1000);
        },
        _pad:function(value) {
          return ('0' + value).slice(-2);
        },
        _update:function(timeString) {
          var i=0,l=this._slots.length,value,slot,now;
          for (;i<l;i++) {
            value = timeString.charAt(i);
            slot = this._slots[i];
            now = slot.dataset.now;
            if (!now) {
              slot.dataset.now = value;
              slot.dataset.old = value;
              continue;
            }
            if (now !== value) {
              this._flip(slot,value);
            }
          }
        },
        _flip:function(slot,value) {
          slot.classList.remove('flip');
          slot.dataset.old = slot.dataset.now;
          slot.dataset.now = value;
          slot.offsetLeft;
          slot.classList.add('flip');
        }
      };
      return exports;
    }());
    var i=0,clocks = document.querySelectorAll('.clock'),l=clocks.length;
    for (;i<l;i++) {
      new Clock(clocks[i]);
    }
    

    You can see the timer in action here: http://codepen.io/olka/pen/dreaL

    If you can find any other things that I should improve to get maximal browser compatibility, please let me know! :)

Viewing 1 post (of 1 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.