Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                [Countdown.js](https://github.com/HugoGiraudel/Countdown.js)
============

Countdown.js is a little customizable countdown made in pure JavaScript. GitHub repository [here](https://github.com/HugoGiraudel/Countdown.js).

## Examples

    // Instanciating a new countdown with all defaults
    new Countdown();

<div class="timer"></div>

    // Instanciating a custom countdown
    new Countdown({
        selector: '.new-year',
        dateEnd: new Date('Jan 1, 2014 12:00:00'),
        msgPattern : 'Happy new year in {days} days, {hours} hours, {minutes} minutes !'
    });

<div class="new-year"></div>


You can also play around with the code at [CodePen](https://codepen.io/HugoGiraudel/pen/vCyJq). 

## Options

You can pass the constructor number of options, including:

#### `selector`

The selector you want to inject Countdown into.

*Default*: `.timer`

#### `msgBefore`

The message to display before reaching `dateStart`.

*Default*: `"Be ready!"`

#### `msgAfter`

The message to display once reaching `dateEnd`.

*Default*: `"It's over, sorry folks!"`

#### `msgPattern`

The message to display during the countdown where values between braces get replaced by actual numeric values.  
Possible patterns:

* `{years}`
* `{months}`
* `{weeks}`
* `{days}`
* `{hours}`
* `{minutes}`
* `{seconds}`

*Default*: `"{days} days, {hours} hours, {minutes} minutes and {seconds} seconds left."`

#### `dateStart`

The date to start the countdown to. Should be an instance of class `Date`. Documentation [here at MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date).

*Default*: `new Date()` (now)

#### `dateEnd`

The date to end the countdown to. Should be an instance of class `Date`. Documentation [here at MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date).

*Default*: `new Date(new Date().getTime() + (24 * 60 * 60 * 1000))` (tomorrow)

#### `onStart`

The callback to run whenever the countdown start ticking.

*Default*: `null`

#### `onEnd`

The callback to run whenever the countdown stops.

*Default*: `null`


              
            
!

CSS

              
                @import "compass/css3";

.timer, .new-year {
  color: darken(hotpink, 10%);
  text-align: center;
  padding: .5em;
  font-size: 1.25em;
}

body {
  padding: 1em;
  max-width: 600px;
  margin: 0 auto;
}

pre, 
code {
  background: #EFEFEF;
  border: 1px solid rgba(0,0,0,.1);
  border-radius: 4px;
}

pre {
  background: #EFEFEF;
  border: 1px solid rgba(0,0,0,.1);
  padding: .5em;
  border-radius: 4px;
  text-shadow: 0 1px rgba(255, 255, 255, .75);
  line-height: 1.4;
  font-size: .9em;
}

pre code {
  background: none;
  border: none;
  padding: 0;
  border-radius: 0;
}
              
            
!

JS

              
                (function(global) {
  "use strict";

  // Vanilla JS alternative to $.extend
  global.extend = function(obj, extObj) {
    obj = obj || {};
    if (arguments.length > 2) {
      for (var a = 1; a < arguments.length; a++) {
        global.extend(obj, arguments[a]);
      }
    } else {
      for (var i in extObj) {
        obj[i] = extObj[i];
      }
    }
    return obj;
  };

  // Countdown constructor
  var Countdown = function(conf) {
    this.conf = global.extend({
      // Dates
      dateStart  : new Date(),
      dateEnd    : new Date(new Date().getTime() + (24 * 60 * 60 * 1000)),

      // Default elements
      selector   : ".timer",

      // Messages
      msgBefore  : "Be ready!",
      msgAfter   : "It's over, sorry folks!",
      msgPattern : "{days} days, {hours} hours, {minutes} minutes and {seconds} seconds left.",

      // Callbacks
      onStart    : null,
      onEnd      : null
    }, conf);

    // Private variables
    this.selector = document.querySelectorAll(this.conf.selector);
    this.interval = 1000;
    this.now      = new Date();
    this.patterns = [
      { pattern: "{years}", secs: 31536000 },
      { pattern: "{months}", secs: 2628000 },
      { pattern: "{weeks}", secs: 604800 },
      { pattern: "{days}", secs: 86400 },
      { pattern: "{hours}", secs: 3600 },
      { pattern: "{minutes}", secs: 60 },
      { pattern: "{seconds}", secs: 1 }
    ];

    // Doing all the things!
    this.init();
  };

  // Initializing the instance
  Countdown.prototype.init = function() {
    this.defineInterval();
    if(this.now < this.conf.dateEnd && this.now >= this.conf.dateStart) {
      this.run();
      this.callback("start");
    } else {
      this.outOfInterval();
    }
  };

  // Running the countdown
  Countdown.prototype.run = function() {
    var now = this.now.valueOf() / 1000,
        tar = this.conf.dateEnd.valueOf() / 1000,
        sec = Math.abs(tar - now);

    // Vanilla JS alternative to $.proxy
    var that  = this;
    var timer = global.setInterval(function() {
      sec--;

      if(sec > 0) {
        that.display(sec);
      } else {
        clearInterval(timer);
        that.outOfInterval();
        that.callback("end");
      }
    }, this.interval);

    this.display(sec);
  };

  // Displaying the countdown
  Countdown.prototype.display = function(sec) {
    var output = this.conf.msgPattern;

    for (var b = 0; b < this.patterns.length; b++) {
      var currentPattern = this.patterns[b];

      if (this.conf.msgPattern.indexOf(currentPattern.pattern) !== -1) {
        var number = Math.floor(sec / currentPattern.secs);
        sec -= number * currentPattern.secs;
        output = output.replace(currentPattern.pattern, number);
      }
    }

    for(var c = 0; c < this.selector.length; c++) {
      this.selector[c].innerHTML = output;
    }
  };

  // Defining the interval to be used for refresh
  Countdown.prototype.defineInterval = function() {
    for (var e = this.patterns.length; e > 0; e--) {
      var currentPattern = this.patterns[e-1];

      if (this.conf.msgPattern.indexOf(currentPattern.pattern) !== -1) {
        this.interval = currentPattern.secs * 1000;
        return;
      }
    }
  };

  // Canceling the countdown in case it's over
  Countdown.prototype.outOfInterval = function() {
    var message = this.now < this.conf.dateStart ? this.conf.msgBefore : this.conf.msgAfter;
    for(var d = 0; d < this.selector.length; d++) {
      this.selector[d].innerHTML = message;
    }
  };

  // Dealing with events and callbacks
  Countdown.prototype.callback = function(event) {
    event = event.capitalize();

    // onStart callback
    if(typeof this.conf["on" + event] === "function") {
      this.conf["on" + event]();
    }

    // Triggering a jQuery event if jQuery is loaded
    if(typeof global.jQuery !== "undefined") {
      global.jQuery(this.conf.selector).trigger("countdown" + event);
    }
  };

  // Adding a capitalize method to String
  String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
  };

  global.Countdown = Countdown;
}(window));

// Initializing two countdowns
var tomorrow     = new Countdown(); // All defaults
var happyNewYear = new Countdown({  // Custom
  selector: '.new-year',
  dateEnd: new Date('2015/01/01'),
  msgPattern : 'Happy new year in {days} days, {hours} hours, {minutes} minutes !',
  onStart: function() { 
    console.log('Starting countdown'); 
  },
  onEnd: function() {
    console.log('Ending countdown');
  }
});

              
            
!
999px

Console