Skip to content

Instantly share code, notes, and snippets.

@dcneiner
Created September 14, 2013 18:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcneiner/6564192 to your computer and use it in GitHub Desktop.
Save dcneiner/6564192 to your computer and use it in GitHub Desktop.
A quick jQuery plugin I wrote for a friend. Just will show or hide certain elements based on the time.
<!-- show this div between 2:00 and 2:30 September 19 -->
<div class="time-based" data-start="September 19, 2013 14:00:00 CDT" data-end="September 19, 2013 14:30:00 CDT">Hello there!</div>
<script>
$( ".time-based" ).timeBased();
</script>
$.fn.timeBased = function ( options ) {
options = $.extend( {}, $.fn.timeBased.defaults, options );
return this.each( function ( i, el ) {
var $el = $( el );
var dStart = Date.parse( $el.data( "start" ) );
var dEnd = Date.parse( $el.data( "end" ) );
var state = "uninitialized";
var check = function () {
var now = +(new Date());
var newState = now >= dStart && now <= dEnd;
if ( state !== newState ) {
state = newState;
options[ newState ? "on" : "off" ]( $el );
}
};
setInterval( check, options.interval );
check();
});
}
$.fn.timeBased.defaults = {
on: function ( $el ) {
$el.show();
},
off: function ( $el ) {
$el.hide();
},
interval: 1000
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment