How to make timer not to restart after page refresh in psgTimer library of Jquery? - javascript

This is the code snippet of psgTimer Jquery Library, I want not to reload the timer when the page refreshes. I try to save the time diff in local storage. But not able to get the result. Please provide the solution.
(function () {
var callbacks = {
onInit: function () {
},
onStart: function () {
},
onStop: function () {
},
onEnd: function () {
},
onChangeStart: function () {
},
onChangeEnd: function () {
}
};
var base = {
stopped: true,
timezone: 0,
diff: null,
isEnd: false
};
var PsgTimer = function (selector, options) {
var timer = this;
if (selector.nodeType === Node.ELEMENT_NODE) {
timer.container = $(selector);
} else if (typeof selector === 'string') {
timer.selector = selector;
timer.container = $(timer.selector);
} else if (typeof selector === 'object') {
options = selector;
timer.selector = options.selector;
timer.container = $(timer.selector);
}
timer.options = $.extend({}, {
selector: '#psgTimer',
animation: false,
multipleBlocks: false,
endDateTime: undefined,
// currentDateTime: window.serverTime['U'] * 1000 || Date.now(),
currentDateTime: Date.now(),
labels: {
days: timer.container.attr('data-label-days') ? timer.container.attr('data-label-days') : false,
hours: timer.container.attr('data-label-hours') ? timer.container.attr('data-label-hours') : false,
minutes: timer.container.attr('data-label-minutes') ? timer.container.attr('data-label-minutes') : false,
seconds: timer.container.attr('data-label-seconds') ? timer.container.attr('data-label-seconds') : false
}
}, options);
timer.callbacks = timer.options.callbacks = $.extend({}, callbacks, timer.options.callbacks);
timer.base = $.extend({}, base);
if (typeof timer.options.endDateTime === 'string') {
timer.options.endDateTime = setTimerEndFromString(timer, timer.options.endDateTime);
}
timer.container.length ? timer.init() : console.log('No timer element on this page');
};
PsgTimer.prototype.init = function () {
var timer = this,
options = this.options;
var timerEnd = timer.container.attr('data-timer-end');
if (timerEnd !== undefined) {
options.endDateTime = setTimerEndFromString(timer, timerEnd);
}
// options.endDateTime = options.endDateTime + (timer.base.timezone * 1000 * 60 * 60);
timer.countdown = transformCountToArray(getCurrentCountDown(timer), options.multilpeBlocks);
timer.container.addClass('psgTimer').append(createMarkup(timer));
if (options.animation) {
timer.container.addClass('psgTimer_' + options.animation);
}
timer.query = setQueries(timer);
timer.callbacks.onInit();
if (!timer.base.isEnd) {
timer.start();
}
};
PsgTimer.prototype.start = function () {
var timer = this;
if (timer.base.stopped) {
timer.base.stopped = false;
timer.intervalId = setInterval(function () {
updateCounter(timer);
}, 1000);
timer.callbacks.onStart();
}
};
PsgTimer.prototype.restart = function () {
var timer = this;
timer.options.currentDateTime = Date.now();
timer.start();
};
PsgTimer.prototype.stop = function () {
var timer = this;
timer.base.stopped = true;
clearTimeout(timer.intervalId);
timer.callbacks.onStop();
};
var getCurrentCountDown = function (timer) {
var options = timer.options;
var base = timer.base;
options.currentDateTime = options.currentDateTime + 1001;
base.diff = options.endDateTime - options.currentDateTime;
var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
if (base.diff > 0) {
var total = parseFloat(((((base.diff / 1000.0) / 60.0) / 60.0) / 24.0));
days = parseInt(total);
total -= days;
total *= 24.0;
hours = parseInt(total);
total -= hours;
total *= 60.0;
minutes = parseInt(total);
total -= minutes;
total *= 60;
seconds = parseInt(total);
} else {
timer.callbacks.onEnd();
timer.stop();
timer.base.isEnd = true;
}
return {
days: {
amount: days,
max: Infinity,
className: 'days'
},
hours: {
amount: hours,
max: 24,
className: 'hours'
},
minutes: {
amount: minutes,
max: 60,
className: 'minutes'
},
seconds: {
amount: seconds,
max: 60,
className: 'seconds'
}
}
};
var transformCountToArray = function (count, multilpeBlocks) {
if (typeof count === 'object') {
for (var unit in count) {
if (count.hasOwnProperty(unit)) {
count[unit].amount = count[unit].amount.toString();
if (count[unit].amount.length < 2) {
count[unit].amount = '0' + count[unit].amount;
}
if (multilpeBlocks) {
count[unit].amount = count[unit].amount.split('');
} else {
count[unit].amount = [count[unit].amount];
}
}
}
}
return count;
};
var getTimeZone = function (string) {
var hours, minutes;
var number = string.replace(/\D/g, '');
var digit = string.replace(/[^+-]/g, '');
var multiplier = digit === '-' ? (-1) : 1;
if (number.length >= 3) {
hours = Number(number.substr(0, number.length - 2));
minutes = Number(number.substr(number.length - 2, 2));
} else {
hours = Number(number);
minutes = 0;
}
return (hours + minutes/60) * multiplier;
};
var setTimerEndFromString = function (timer, endTimeString) {
var timerDate = {};
var timerEnd = endTimeString.split(' ');
var endTime;
var timeExp = /^([0-1]\d|2[0-3])(:[0-5]\d){1,2}$/;
var dateExp = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
var zoneExp = /(UTC|GMT)[+-](\d{1,2}([:,.]?\d{2})?)/;
for (var i = 0; i < timerEnd.length; i++) {
if (timerEnd[i].match(timeExp)) {
timerDate.time = timerEnd[i].split(':');
} else if (timerEnd[i].match(dateExp)) {
timerDate.date = timerEnd[i].split('.');
} else if (timerEnd[i].match(zoneExp)) {
timer.base.timezone = getTimeZone(timerEnd[i]);
} else {
console.log('Wrong end time.');
}
}
timerDate.year = parseInt(timerDate.date[2]) || 0;
timerDate.month = parseInt(timerDate.date[1]) - 1 || 0;
timerDate.day = parseInt(timerDate.date[0]) || 0;
timerDate.hours = parseInt(timerDate.time[0]) || 0;
timerDate.minutes = parseInt(timerDate.time[1]) || 0;
timerDate.seconds = parseInt(timerDate.time[2]) || 0;
timerDate.miliseconds = parseInt(timerDate.time[3]) || 0;
endTime = Date.UTC(timerDate.year, timerDate.month, timerDate.day, timerDate.hours, timerDate.minutes, timerDate.seconds, timerDate.miliseconds);
return endTime;
};
var createMarkup = function (timer) {
var countdown = timer.countdown;
var markup = {};
for (var unit in countdown) {
if (countdown.hasOwnProperty(unit)) {
var numberBlocks = '';
countdown[unit].amount.forEach(function (num) {
numberBlocks += numberContainer(timer, num);
});
markup.unit += '<div class="' + countdown[unit].className + ' psgTimer_unit">' + numberBlocks + '</div>';
}
}
markup.numbers = '<div class="psgTimer_numbers">' + markup.unit + '</div>';
markup.full = markup.numbers;
if (
timer.options.labels &&
timer.options.labels.days &&
timer.options.labels.hours &&
timer.options.labels.minutes &&
timer.options.labels.seconds
) {
var labels = timer.options.labels;
markup.labels = '<div class="psgTimer_labels">' +
'<div class="days">' + labels.days + '</div>' +
'<div class="hours">' + labels.hours + '</div>' +
'<div class="minutes">' + labels.minutes + '</div>' +
'<div class="seconds">' + labels.seconds + '</div>' +
'</div>';
markup.full = markup.numbers + markup.labels;
} else {
markup.full = markup.numbers;
}
return markup.full;
};
var numberContainer = function (timer, num) {
var markup = '',
data = 'data-number="' + num + '"';
var numberBlock = '<div class="number" ' + data + '>' + num + '</div>';
if (timer.options.animation === 'fade') {
markup = '<div>' + numberBlock + '</div>';
} else {
markup = numberBlock;
}
return markup;
};
var setQueries = function (timer) {
var countdown = timer.countdown,
query = {};
for (var unit in countdown) {
if (countdown.hasOwnProperty(unit)) {
query[unit] = timer.container.find(numberSelector(timer, countdown[unit].className));
}
}
return query;
};
var numberSelector = function (timer, className) {
var selector = '';
if (timer.options.animation === 'fade') {
selector = '.' + className + ' .number';
} else {
selector = '.' + className + ' .number';
}
return selector;
};
var updateCounter = function (timer) {
timer.callbacks.onChangeStart();
timer.countdown = transformCountToArray(getCurrentCountDown(timer), timer.options.multilpeBlocks);
for (var unit in timer.countdown) {
if (timer.countdown.hasOwnProperty(unit)) {
timer.countdown[unit].amount.forEach(function (number, index) {
if (timer.query[unit][index].getAttribute('data-number') !== number) {
aminate(timer.query[unit][index], number, timer.options.animation);
}
});
}
}
timer.callbacks.onChangeEnd();
};
var aminate = function (el, value, animationType) {
var $el = $(el);
$el.attr('data-number', value);
if (animationType === 'fade') {
animation.fade($el, value);
} else {
$el.html(value);
}
};
var animation = {
fade: function ($el, value) {
var animDuration = 350;
$el.css({
'transition': 'opacity ' + animDuration + 'ms',
'opacity': '0'
});
setTimeout(function () {
$el.html(value).css('opacity', 1);
}, animDuration + 10);
}
};
window.PsgTimer = PsgTimer;
})();
.psgTimer{display:table;margin:0 auto 30px auto;font-size:0;font-family:'Roboto', sans-serif}.psgTimer_numbers>div,.psgTimer_labels>div{display:inline-block;font-size:0;width:124px;text-align:center}.psgTimer_numbers>div{position:relative}.psgTimer_numbers>div:after{content:":";line-height:60px;height:60px;display:block;font-weight:bold;font-size:24px;color:#21272C;position:absolute;top:0;right:-4px}.psgTimer_numbers>div:last-child:after{content:none}.psgTimer_numbers>div>div{display:inline-block;vertical-align:top;width:44px;height:60px;line-height:60px;background:#21272C;box-shadow:0px 4px 8px rgba(0,0,0,0.2);border-radius:6px;font-weight:bold;font-size:24px;text-align:center;color:#FFD631}.psgTimer_numbers>div>div:first-child{margin-right:5px}.psgTimer_labels>div{padding-top:5px !important;font-size:12px;line-height:18px;text-transform:uppercase;letter-spacing:1.2px;color:#21272C}#media screen and (max-width: 640px){.psgTimer_numbers>div,.psgTimer_labels>div{width:74px}.psgTimer_numbers>div{position:relative}.psgTimer_numbers>div:after{line-height:40px;height:40px;font-size:16px;right:-2px}.psgTimer_numbers>div div{width:26px;height:40px;line-height:40px;font-size:16px}.psgTimer_numbers>div div:first-child{margin-right:2px}.psgTimer_labels>div{font-size:10px;line-height:16px}}
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<div id="firstTimer"></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
var timer = new PsgTimer({
selector: '#firstTimer',
currentDateTime: Date.UTC(2018, 0, 26, 12, 0, 0),
endDateTime: Date.UTC(2018, 0, 26, 12, 5, 0),
multilpeBlocks: true,
animation: 'fade',
labels: {
days: 'Days',
hours: 'Hours',
minutes: 'minutes',
seconds: 'seconds'
},
callbacks: {
onInit: function () {
console.log('Hello world!');
}
}
});
})
</script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
</body>
</html>
You can take the reference from psgTimer library
https://www.jqueryscript.net/time-clock/psg-countdown-timer.html

Related

html/java Input with Slider

I do have slider that outputs a value as text. Now I need also to build an input Textfield that does change the slider value and the slider value change the input Textfield value. I did find couple solutions, but that does not work for me, because I have comparison boxes that work hand in hand, when I try those solutions everything crashes.
Here my code:
// Term Slider
function comparisons_term_slider($settings) {
$term = str_replace('[term]',$settings['terminitial'],$settings['termoutput']);
$term = str_replace('[period]',$settings['plural'],$term);
$output = '<div class="comparisons-range comparisons-slider-term">
<div class="comparisons_slider_output">';
$output .= '<div class="output-pad"><span class="circle-down circle-control"></span><span class="output-number"><label for="loan-term">'.$settings['termlabel'].'</label> <output>'.$term.'</output><span class="circle-up circle-control"></span></div>';
$output .= '</div>
<input type="range" class="loan_term" name="loan-term" id="loan-term" min="'.$settings['termmin'].'" max="'.$settings['termmax'].'" value="'.$settings['terminitial'].'" step="'.$settings['termstep'].'" data-comparisons>
</div>';
return $output;
}
and in javascript
// Select all relevant loan slider forms
$(comparisons_loan_selector).each(function() {
// Initialize sliders
var sliders = $(this).find('[data-comparisons]'), x = $(this);
sliders.change(comparisonsCalculate);
sliders.comparisons({polyfill:false});
$('#lc_show_more').click(function() {
comparisonsShowMore.apply(this);
//comparisonsCalculate;
});
$('#sortby').change(comparisonsCalculate);
// Up and down buttons
x.find('.circle-control').click(function() {
var holder = $(this).closest('.comparisons-range'),
range = holder.find('input'),
newVal = parseFloat(range.val()),
step = parseFloat(range.attr('step')),
min = parseFloat(range.attr('min')),
max = parseFloat(range.attr('max'));
if ($(this).hasClass('circle-down')) { // reduce the slider value
newVal = newVal - step;
if (newVal > min) range.val(newVal);
else range.val(min);
} else { // raise the slider value
newVal = newVal + step;
if (newVal < max) range.val(newVal);
else range.val(max);
}
range.change();
});
// Sliders
jQuery(document).ready(function($) {
(function(factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports === 'object') {
factory(require('jquery'));
} else {
factory(jQuery);
}
} (function($) {
'use strict';
function supportsRange() {
var input = document.createElement('input');
input.setAttribute('type', 'range');
return input.type !== 'text';
}
var pluginName = 'comparisons',
pluginInstances = [],
inputrange = supportsRange(),
defaults = {
polyfill: true,
rangeClass: 'comparisons',
disabledClass: 'comparisons--disabled',
fillClass: 'comparisons__fill',
handleClass: 'comparisons__handle',
startEvent: ['mousedown', 'touchstart', 'pointerdown'],
moveEvent: ['mousemove', 'touchmove', 'pointermove'],
endEvent: ['mouseup', 'touchend', 'pointerup']
};
function delay(fn, wait) {
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(function(){ return fn.apply(null, args); }, wait);
}
function debounce(fn, debounceDuration) {
debounceDuration = debounceDuration || 100;
return function() {
if (!fn.debouncing) {
var args = Array.prototype.slice.apply(arguments);
fn.lastReturnVal = fn.apply(window, args);
fn.debouncing = true;
}
clearTimeout(fn.debounceTimeout);
fn.debounceTimeout = setTimeout(function(){
fn.debouncing = false;
}, debounceDuration);
return fn.lastReturnVal;
};
}
function Plugin(element, options) {
this.$window = $(window);
this.$document = $(document);
this.$element = $(element);
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.startEvent = this.options.startEvent.join('.' + pluginName + ' ') + '.' + pluginName;
this.moveEvent = this.options.moveEvent.join('.' + pluginName + ' ') + '.' + pluginName;
this.endEvent = this.options.endEvent.join('.' + pluginName + ' ') + '.' + pluginName;
this.polyfill = this.options.polyfill;
this.onInit = this.options.onInit;
this.onSlide = this.options.onSlide;
this.onSlideEnd = this.options.onSlideEnd;
if (this.polyfill) {
if (inputrange) { return false; }
}
this.identifier = 'js-' + pluginName + '-' +(+new Date())+'-'+(pluginInstances.length + 1);
this.min = parseFloat(this.$element[0].getAttribute('min') || 0);
this.max = parseFloat(this.$element[0].getAttribute('max') || 100);
this.value = parseFloat(this.$element[0].value || this.min + (this.max-this.min)/2);
this.step = parseFloat(this.$element[0].getAttribute('step') || 1);
this.$fill = $('<div class="' + this.options.fillClass + '" />');
this.$handle = $('<div class="' + this.options.handleClass + '" />');
this.$range = $('<div class="' + this.options.rangeClass + '" id="' + this.identifier + '" />').insertAfter(this.$element).prepend(this.$fill, this.$handle);
this.$element.css({
'position': 'absolute',
'width': '1px',
'height': '1px',
'overflow': 'hidden',
'opacity': '0'
});
this.handleDown = $.proxy(this.handleDown, this);
this.handleMove = $.proxy(this.handleMove, this);
this.handleEnd = $.proxy(this.handleEnd, this);
this.init();
var _this = this;
this.$window.on('resize' + '.' + pluginName, debounce(function() {
delay(function() { _this.update(); }, 300);
}, 20));
this.$document.on(this.startEvent, '#' + this.identifier + ':not(.' + this.options.disabledClass + ')', this.handleDown);
this.$element.on('change' + '.' + pluginName, function(e, data) {
if (data && data.origin === pluginName) {
return;
}
var value = e.target.value,
pos = _this.getPositionFromValue(value);
_this.setPosition(pos);
});
}
Plugin.prototype.init = function() {
if (this.onInit && typeof this.onInit === 'function') {
this.onInit();
}
this.update();
};
Plugin.prototype.attributes = function() {
var e = this.$element;
this.min = parseFloat(e.attr('min'));
this.max = parseFloat(e.attr('max'));
this.value = parseFloat(e.attr('value'));
if (this.value > this.max) this.setValue(this.max);
if (this.value < this.min) this.setValue(this.min);
if (this.value > this.min && this.value > this.min) this.setValue(this.value);
this.update();
};
Plugin.prototype.update = function() {
this.handleWidth = this.$handle[0].offsetWidth;
this.rangeWidth = this.$range[0].offsetWidth;
this.maxHandleX = this.rangeWidth - this.handleWidth;
this.grabX = this.handleWidth / 2;
this.position = this.getPositionFromValue(this.value);
if (this.$element[0].disabled) {
this.$range.addClass(this.options.disabledClass);
} else {
this.$range.removeClass(this.options.disabledClass);
}
this.setPosition(this.position);
};
Plugin.prototype.handleDown = function(e) {
e.preventDefault();
this.$document.on(this.moveEvent, this.handleMove);
this.$document.on(this.endEvent, this.handleEnd);
if ((' ' + e.target.className + ' ').replace(/[\n\t]/g, ' ').indexOf(this.options.handleClass) > -1) {
return;
}
var posX = this.getRelativePosition(this.$range[0], e),
handleX = this.getPositionFromNode(this.$handle[0]) - this.getPositionFromNode(this.$range[0]);
this.setPosition(posX - this.grabX);
if (posX >= handleX && posX < handleX + this.handleWidth) {
this.grabX = posX - handleX;
}
};
Plugin.prototype.handleMove = function(e) {
e.preventDefault();
var posX = this.getRelativePosition(this.$range[0], e);
this.setPosition(posX - this.grabX);
};
Plugin.prototype.handleEnd = function(e) {
e.preventDefault();
this.$document.off(this.moveEvent, this.handleMove);
this.$document.off(this.endEvent, this.handleEnd);
if (this.onSlideEnd && typeof this.onSlideEnd === 'function') {
this.onSlideEnd(this.position, this.value);
}
};
Plugin.prototype.cap = function(pos, min, max) {
if (pos < min) { return min; }
if (pos > max) { return max; }
return pos;
};
Plugin.prototype.setPosition = function(pos) {
var value, left;
value = (this.getValueFromPosition(this.cap(pos, 0, this.maxHandleX)) / this.step) * this.step;
left = this.getPositionFromValue(value);
this.$fill[0].style.width = (left + this.grabX) + 'px';
this.$handle[0].style.left = left + 'px';
this.setValue(value);
this.position = left;
this.value = value;
};
Plugin.prototype.getPositionFromNode = function(node) {
var i = 0;
while (node !== null) {
i += node.offsetLeft;
node = node.offsetParent;
}
return i;
};
Plugin.prototype.getRelativePosition = function(node, e) {
return (e.pageX || e.originalEvent.clientX || e.originalEvent.touches[0].clientX || e.currentPoint.x) - this.getPositionFromNode(node);
};
Plugin.prototype.getPositionFromValue = function(value) {
var percentage, pos;
percentage = (value - this.min)/(this.max - this.min);
pos = percentage * this.maxHandleX;
return pos;
};
Plugin.prototype.getValueFromPosition = function(pos) {
var percentage, value;
percentage = ((pos) / (this.maxHandleX || 1));
value = this.step * Math.round((((percentage) * (this.max - this.min)) + this.min) / this.step);
return Number((value).toFixed(2));
};
Plugin.prototype.setValue = function(value) {
if (value !== this.value) {
this.$element.val(value).trigger('change', {origin: pluginName});
}
};
Plugin.prototype.destroy = function() {
this.$document.off(this.startEvent, '#' + this.identifier, this.handleDown);
this.$element
.off('.' + pluginName)
.removeAttr('style')
.removeData('plugin_' + pluginName);
if (this.$range && this.$range.length) {
this.$range[0].parentNode.removeChild(this.$range[0]);
}
pluginInstances.splice(pluginInstances.indexOf(this.$element[0]),1);
if (!pluginInstances.length) {
this.$window.off('.' + pluginName);
}
};
$.fn[pluginName] = function(options) {
return this.each(function() {
var $this = $(this),
data = $this.data('plugin_' + pluginName);
if (!data) {
$this.data('plugin_' + pluginName, (data = new Plugin(this, options)));
pluginInstances.push(this);
}
if (typeof options === 'string') {
data[options]();
}
});
};
}));
});
any solutions possible? Do you need more code?
Already did try this but it doesnt work aswell..
<div>
<input id="rangeInput" type="range" min="0" max="200" oninput="amount.value=rangeInput.value" />
<input id="amount" type="number" value="100" min="0" max="200" oninput="rangeInput.value=amount.value" />
</div>

angularjs re-initialize directive

I have the following code
HTML
<countdown ng-show="vm.inhotel" init-val="vm.finishtime" init-lastmess="''" init-mess="'Sjekk ut'"></countdown>
Controller
vm.finishtime = 0;
vm.inhotel = false;
$rootScope.$on('enterhotel', function(data) {
console.log(data);
console.log("entering hotel for " + data.totime);
vm.inhotel = true;
vm.finishtime = new Date().getTime() + 60 * 60 * 24 * 1000;
});
Countdown directory
angular
.module('users')
.directive('countdown', countdown);
function getFormattedTime(secs) {
var date = new Date(null);
date.setSeconds(secs);
return date.toISOString().substr(11, 8);
}
function countdown() {
return {
restrict: 'E',
template: '<div class=\"{{class}}\" style=\"{{isfloating}} margin-right:5px;\""><span style=\"font-size:{{firstsize}}px;\">{{firstmess}}</span> <span style=\"font-size:{{initsize}}px;\">{{result}}</span></div>',
scope: {
initVal: '=',
initMess: '=',
initLastmess: '=',
initMesssize: '=',
initSize: '=',
initIsfloating: '=',
},
controller: function($scope, $interval) {
if ($scope.initIsfloating) {
$scope.isfloating = 'float:left;';
} else {
$scope.isfloating = '';
}
if ($scope.initLastmess == 'undefined') {
$scope.initLastmess = '';
}
$scope.countdownVal = $scope.initVal;
$scope.countdownVal = Math.floor($scope.countdownVal / 1000) - Math.floor(Date.now() / 1000);
var b = getFormattedTime($scope.countdownVal);
$scope.class = "";
$scope.firstsize = $scope.initMesssize;
$scope.initsize = $scope.initSize;
$scope.firstmess = $scope.initMess;
if ($scope.countdownVal > 0) {
$scope.result = b + " " + $scope.initLastmess;
} else {
$scope.class = "";
$scope.result = "00:00:00 " + $scope.initLastmess;
}
$interval(function () {
$scope.firstsize = $scope.initMesssize;
$scope.initsize = $scope.initSize;
$scope.firstmess = $scope.initMess;
if ($scope.initIsfloating) {
$scope.isfloating = 'float:left;';
} else {
$scope.isfloating = '';
}
if ($scope.initLastmess == 'undefined') {
$scope.initLastmess = '';
}
if ($scope.countdownVal > 0) {
$scope.class = "";
$scope.countdownVal = $scope.initVal;
$scope.countdownVal = ($scope.initVal / 1000) - Math.floor(Date.now() / 1000);
$scope.result = getFormattedTime($scope.countdownVal) + " " + $scope.initLastmess;
} else {
$scope.class = "";
$scope.result = " 00:00:00 " + $scope.initLastmess;
}
}, 1000);
}
}
};
but the countdown wont change the new finishtime object. is it possible to reinitialize the countdown directive to refresh it with my new countdown?

JW Player - Amazon Web Services CDN and Advanced Javascript Debugging

I have a customized JW Player 7 Pro embedded on the following page: http://dev.sharepoint-videos.com/jw-player-self-hosted/.
The embed code is as follows:
<!--Course Video, Scripts and Style-->
<div id="visualSPPlayer">Loading the player...</div>
<script type="text/javascript">
var playerInstance = jwplayer("visualSPPlayer");
playerInstance.setup({
file: "http://dbt8c2ssdzlxg.cloudfront.net/Search2013.mp4",
primary: "HTML5",
image: "https://assets-jpcust.jwpsrv.com/thumbs/2kOAeo0k-320.jpg?1443200073230",
width: "100%",
aspectratio: "16:9",
tracks: [
{
file: "http://dbt8c2ssdzlxg.cloudfront.net/captions/Search/Captions.srt",
label: "English",
kind: "captions",
},
{
file: 'http://dbt8c2ssdzlxg.cloudfront.net/chapters/Search/Chapters.vtt',
kind: 'chapters'
},
{
file: "http://dbt8c2ssdzlxg.cloudfront.net/thumbnails/search_thumbnails.vtt",
kind: "thumbnails"
}
],
skin: {
name: "vapor",
active: "#E16933",
inactive: "#E16933",
background: "#333333"
}
});
</script>
<script type="application/javascript" src="http://dev.sharepoint-videos.com/wp-content/themes/symplex-child/js/player.js"></script>
<link rel="stylesheet" href="http://dev.sharepoint-videos.com/wp-content/themes/symplex-child/css/player.css" type="text/css" media="screen"/>
The player.js file contents:
jQuery(document).ready(function () {
jQuery(function ($) {
var playerInstance = jwplayer();
var chapters = [];
var captions = [];
var toc = [];
var caption = -1;
var matches = [];
var seekArr = [];
var seekPos = [];
var seePos;
var query = "";
var cycle = -1;
var transcript = document.getElementById('courseTranscript');
var search = document.getElementById('courseSearch');
var match = document.getElementById('courseMatch');
var caption_file;
var chapter_file;
playerInstance.onReady(function () {
//Self-Hosted
caption_file = playerInstance.getPlaylist()[0].tracks[0].file;
chapter_file = playerInstance.getPlaylist()[0].tracks[1].file;
if (playerInstance.getRenderingMode() == "flash") {
return;
}
tag = document.querySelector('video');
tag.defaultPlaybackRate = 1.0;
tag.playbackRate = 1.0;
playerInstance.addButton("http://dev.sharepoint-videos.com/wp-content/uploads/2015/09/hare.png", "1.5x", function () {
playerInstance.seek(playerInstance.getPosition());
tag.playbackRate = 1.5;
}, "playerHighSpeed");
playerInstance.addButton("http://dev.sharepoint-videos.com/wp-content/uploads/2015/09/normal.png", "1.0x", function () {
playerInstance.seek(playerInstance.getPosition());
tag.playbackRate = 1.0;
}, "playerNormalSpeed");
playerInstance.addButton("http://dev.sharepoint-videos.com/wp-content/uploads/2015/09/snail.png", "0.5x", function () {
playerInstance.seek(playerInstance.getPosition());
tag.playbackRate = 0.5;
}, "playerSlowSpeed");
});
//Adds Player Focus on Playing
playerInstance.on('play', function () {
$('html, body').animate({
scrollTop: $(".jwplayer").offset().top - 190
}, 1000);
});
playerInstance.onReady(function () {
$.get(caption_file, function (data) {
data = data.trim();
var t = data.split("\n\r\n");
for (var i = 0; i < t.length; i++) {
var c = parse(t[i]);
chapters.push(c);
}
loadCaptions();
loadChapters();
});
//
});
// Load chapters / captions
function loadCaptions() {
$.get(caption_file, function (data) {
data = data.trim();
var t = data.split("\n\r\n");
t.pop();
var h = "<p>";
var s = 0;
for (var i = 0; i < t.length; i++) {
var c = parse(t[i]);
if (s < chapters.length && c.begin > chapters[s].begin) {
s++;
}
h += "<span id='caption" + i + "'>" + c.text + "</span>";
captions.push(c);
}
transcript.innerHTML = h + "</p>";
});
};
function parse(d) {
var a = d.split("\n");
//console.log(a[1]);
var i = a[1].indexOf(' --> ');
var t = a[2]; //Caption text
if (a[3]) {
t += " " + a[3];
}
t = t.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return {
begin: seconds(a[1].substr(0, i)),
btext: a[1].substr(3, i - 7),
end: seconds(a[1].substr(i + 5)),
text: t
}
};
function seconds(s) {
var a = s.split(':');
secs = a[2].substring(0, a[2].indexOf(','));
var r = Number(secs) + Number(a[a.length - 2]) * 60;
if (a.length > 2) {
r += Number(a[a.length - 3]) * 3600;
}
return r;
};
function toc_seconds(s) {
var a = s.split(':');
secs = a[2].substring(0, a[2].indexOf('.'));
var r = Number(secs) + Number(a[a.length - 2]) * 60;
if (a.length > 2) {
r += Number(a[a.length - 3]) * 3600;
}
return r;
};
function toc_time(s) {
var a = s.split(':');
var ms = a[2].split(".");
var h = a[0];
if (h != "00") {
var r = a[0] + ":" + a[1] + ":" + ms[0];
} else {
var r = a[1] + ":" + ms[0];
}
return r;
};
// Highlight current caption and chapter
playerInstance.onTime(function (e) {
var p = e.position;
for (var j = 0; j < captions.length; j++) {
if (captions[j].begin < p && captions[j].end > p) {
if (j != caption) {
var c = document.getElementById('caption' + j);
if (caption > -1) {
document.getElementById('caption' + caption).className = "";
}
c.className = "current";
if (query == "") {
transcript.scrollTop = c.offsetTop - transcript.offsetTop - 40;
}
caption = j;
}
break;
}
}
});
// Hook up interactivity
transcript.addEventListener("click", function (e) {
if (e.target.id.indexOf("caption") == 0) {
var i = Number(e.target.id.replace("caption", ""));
playerInstance.seek(captions[i].begin);
}
});
/**/
search.addEventListener('focus', function (e) {
setTimeout(function () {
search.select();
}, 100);
resetSearch();
$("#prevMatchLink").hide();
$("#nextMatchLink").hide();
});
search.addEventListener('keydown', function (e) {
if (e.keyCode == 27) {
resetSearch();
$("#prevMatchLink").hide();
$("#nextMatchLink").hide();
} else if (e.keyCode == 13) {
$("#prevMatchLink").show();
$("#nextMatchLink").show();
var q = this.value.toLowerCase();
if (q.length > 0) {
if (q == query) {
if (cycle >= matches.length - 1) {
cycleSearch(0);
} else {
cycleSearch(cycle + 1);
}
} else {
resetSearch();
searchTranscript(q);
}
} else {
resetSearch();
}
} else if (e.keyCode == 37) {
cycleSearch(cycle - 1);
}
else if (e.keyCode == 39) {
cycleSearch(cycle + 1);
}
});
$("#prevMatchLink").click(function (e) {
e.preventDefault();
cycleSearch(cycle - 1);
});
$("#nextMatchLink").click(function (e) {
e.preventDefault();
cycleSearch(cycle + 1);
});
// Execute search
function searchTranscript(q) {
matches = [];
query = q;
for (var i = 0; i < captions.length; i++) {
var m = captions[i].text.toLowerCase().indexOf(q);
if (m > -1) {
document.getElementById('caption' + i).innerHTML =
captions[i].text.substr(0, m) + "<em>" +
captions[i].text.substr(m, q.length) + "</em>" +
captions[i].text.substr(m + q.length);
matches.push(i);
}
}
if (matches.length) {
cycleSearch(0);
} else {
resetSearch();
}
};
function cycleSearch(i) {
if (cycle > -1) {
var o = document.getElementById('caption' + matches[cycle]);
o.getElementsByTagName("em")[0].className = "";
}
var c = document.getElementById('caption' + matches[i]);
c.getElementsByTagName("em")[0].className = "current";
match.innerHTML = (i + 1) + " of " + matches.length;
transcript.scrollTop = c.offsetTop - transcript.offsetTop - 40;
cycle = i;
};
function resetSearch() {
if (matches.length) {
for (var i = 0; i < captions.length; i++) {
document.getElementById('caption' + i).innerHTML = captions[i].text;
}
}
query = "";
matches = [];
match.innerHTML = "0 of 0";
cycle = -1;
transcript.scrollTop = 0;
};
var videoTitle = $(".videoTitle").text();
var hasPlayed = false;
playerInstance.onBeforePlay(function (event) {
if (hasPlayed == false) {
ga('send', 'event', 'Video', 'Play', videoTitle);
hasPlayed = true;
}
});
//Can be used to trigger the Course to Marked Completed so the user doesn't have to
playerInstance.on('complete', function () {
});
function loadChapters() {
$.get(chapter_file, function (data) {
data = data.trim();
var c = data.split("\n\r\n");
var d;
for (var i = 0; i < c.length; i++) {
d = c[i].split("\n");
//pushes in Title for each chapter
toc.push(d[0]);
//pushes in the time intervals for each chapter
seekArr.push(d[1]);
};
for (var a = 0; a < seekArr.length; a++) {
//Splits the time interval and pushes the start interval for each chapter
var tempPos = seekArr[a].split(" --> ");
seekPos.push(tempPos[0]);
};
runTOC(seekPos);
var toc_output = "";
$.each(toc, function (i, v) {
toc_output += "<li class=ch" + i + "><a href='#' onclick='jwplayer().seek(" + toc_seconds(seekPos[i]) + ");'>" + v + "</a> (" + toc_time(seekPos[i]) + ")</li>"
});
if (toc.length < 7) {
toc_output += " <li class='blank'> </li><li class='blank'> </li>";
}
$(".courseTitles ul").html(toc_output);
});
};
function runTOC(x) {
playerInstance.onTime(function (event) {
for (var i = 0; i < x.length; i++) {
if (event.position > toc_seconds(x[i])) {
$(".courseTitles ul li").removeClass("active");
$(".courseTitles ul li.ch" + i).addClass('active');
}
};
});
}
});
});
We are hosting the video and Chapter/Captions VTT files using Amazon Web Services with Cloudfront.
We have included the interactive transcript from the captions as well as dynamic video chapters to be loaded once the video is ready to be played.
One thing I have noticed is that the chapters and the transcript do not always load and require the page to be refreshed several times so I was thinking that maybe it was a caching issue on the AWS side of the equation.
I have used Google Chrome and there are no errors in the developers console when the chapters and transcript do not load.
It should be noted that this functionality was working flawlessly when were using the JW Platform cloud hosted solution so it seems to be a factor of the AWS/Cloudfront CDN.
function load_jwp_scripts() {
wp_enqueue_script('jwplayer-js', plugins_url( "/js/jwplayer.js", __FILE__), array(), '1.0', false);
wp_enqueue_script('jwplayer-license-js', plugins_url( "/js/jwplayer_license.js", __FILE__), array(), '1.0', false);
wp_enqueue_script('jwplayer-player-js', plugins_url( "/js/player.js", __FILE__), array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'load_jwp_scripts');
I was able to find a workable solution to my problem.
The issue was the use of the $(document).ready declaration. It is not compatible with jwplayer.on("ready").
Removing that and it is rendering properly again.

how to make synchronous call to json data from angularjs

I am calling some data from a JSON file in AngularJS but due to the asynchronous call the code is moving to other step before receiving the data so that is causing an error.
I used $http.get
$http.get('job.json').success(function (response) {
$scope.big = response;
});
Can you suggest some synchronous method to call json data which is
{
"days": [{
"dayname": "Sun,23 Aug 2015",
"date": "2015-08-23",
"hours": "hoursArray(array24)"
}, {
"dayname": "Mon,24 Aug 2015",
"date": "2015-08-24",
"hours": "hoursArray(array24)"
}, {
"dayname": "Tue,25 Aug 2015",
"date": "2015-08-25",
"hours":"hoursArray(array24)"
}, {
"dayname": "Wed,26 Aug 2015",
"date": "2015-08-26",
"hours": "hoursArray(array24)"
}]
}
this is the jquery file i am using
(function($) {
$.fn.schedule = function(options) {
var methods = {
init : function(ele, opt) {
//methods.currentdate = methods.now.getFullYear() + "Engine Change" + methods.now.getMonth() + "Engine Change" + methods.now.getDate();
methods.currentdate = methods.now.getFullYear() + "-" + methods.now.getMonth() + "-" + methods.now.getDate();
// $("#scheduleAllDays > *").each(function(){
// var item = $(this);
// $("#scheduleAllDays").width($("#scheduleAllDays").width()+item.width());
// });
// $("#scheduleAllDays").width($("#scheduleAllDays").width());
ele.find("[data-row]").each(function() {
var drow = $(this), drowset = $("[data-row='" + drow.data("row") + "']");
var maxheight = methods.elesMaxHeight(drowset);
drowset.height(maxheight);
});
methods.allocateDurations(ele);
$("#scheduleContentInner", ele).css("min-height", $(".schedule-drag-wrap", ele).innerHeight());
},
elesMaxHeight : function(ele) {
var heights = $(ele).map(function() {
return $(this).height();
}).get();
return Math.max.apply(null, heights);
},
allocateDurations : function(ele) {
methods.flightdata = {
routes : {}
};
ele.find("[data-flight-row]").each(function(i, ival) {
var flight = $(this);
methods.flightdata.routes["row" + i] = [];
flight.find("[data-flight-record]").each(function() {
var currentFlight = $(this), flightrecord = methods.makeStringToObject(currentFlight.data("flight-record"));
flightrecord.element = currentFlight;
methods.flightdata.routes["row" + i].push(flightrecord);
});
});
methods.positionSet(ele);
},
positionSet : function(ele) {
var dayelement = $("#scheduleAllDays > *", ele);
var totaldaywidth = $("#scheduleAllDays").width() + 30;
var totaldays = dayelement.size();
var totalSeconds = (((totaldays * 24) * 60) * 60);
var perSecondsWidth = Number(totaldaywidth / totalSeconds);
var divider = $(".schedule-h-divider");
dayelement.each(function(i, ival) {
var dayele = $(this), dividerele = divider.eq(i);
dividerele.css({
top : $("#scheduleAllDays").height(),
left : dayele.offset().left - 104
});
});
for (var i in methods.flightdata.routes) {
var iobj = methods.flightdata.routes[i];
for (var j in iobj) {
var jobj = iobj[j];
var duration = jobj.duration, width = Number(methods.hmtosec(duration, ".") * perSecondsWidth);
var parent = jobj.element.parent();
jobj.element.css({
// position : "relative",
width : width + "px",
overflow : "hidden",
"white-space" : "nowrap"
}).parent().css({
// width : width+"px",
// overflow : "hidden"
// position:"absolute",
left : (j==0)?0:parent.prev().position().left+parent.prev().width()
});
}
}
methods.dragInit(ele);
},
setCurrentTimeMarker : function(ele) {
var marker = $(".schedule-current-time-marker");
var markerpills = $(".schedule-time-marker-pills");
var dayelement = $("#scheduleAllDays > *", ele);
var totaldaywidth = $("#scheduleAllDays").width() + 30;
var totaldays = dayelement.size();
var totalSeconds = (((totaldays * 24) * 60) * 60);
var perSecondsWidth = Number(totaldaywidth / totalSeconds);
var currentdate = new Date();
var format = currentdate.getFullYear() + "Engine Change" + currentdate.getMonth() + "Engine Change" + currentdate.getDate();
var currentdateele = $("#scheduleAllDays").find("[data-date='" + format + "']");
var days = (currentdateele.index()), seconds = ((days * 24) * 60) * 60;
seconds = seconds + methods.hmtosec(currentdate.getHours() + "." + currentdate.getMinutes(), ".");
marker.stop().animate({
top : $("#scheduleAllDays",ele).height()-53,
left : (seconds * perSecondsWidth) - (marker.width() / 2)
}, 1000, "swing");
markerpills.html(currentdate.getHours() + ":" + currentdate.getMinutes());
methods.markermove = setInterval(function() {
currentdate = new Date();
marker.css({
left : marker.position().left + perSecondsWidth
}, "fast", "swing");
markerpills.html(methods.makezerodigit(currentdate.getHours()) + " : " + methods.makezerodigit(currentdate.getMinutes()));
// methods.schedulemove(ele,perSecondsWidth);
}, 1000);
},
schedulemove : function(ele,seconds) {
var dragwrap = ele.find(".schedule-drag-wrap");
var routewidth = $(".schedule-route:eq(0)").width() + $(".schedule-route:eq(1)").width();
var maxleft = -(dragwrap.width() - ($(window).width() - routewidth));
if (Math.abs(dragwrap.position().left) < Math.abs(maxleft)) {
dragwrap.css({
left : (dragwrap.position().left - (dragwrap.width)) + "px"
});
}
},
makezerodigit : function(digit) {
return (String(digit).match(/^[0-9]$/)) ? "0" + digit : digit;
},
dragInit : function(ele) {
var currentdaycol = $("[data-date='" + methods.currentdate + "']");
ele.find(".schedule-drag-wrap").css({
left : -(currentdaycol.position().left - 50) + "px"
}).animate({
left : -currentdaycol.position().left - 0 + "px"
}, 1000, "swing", function() {
methods.drag(ele);
methods.setCurrentTimeMarker(ele);
});
},
drag : function(ele) {
methods.move = null;
$(".schedule-drag-wrap", ele).on("mousedown", function(e) {
var dragele = $(this), position = dragele.position();
methods.move = {
x : e.pageX,
y : e.pageY,
left : position.left
};
}).on("mouseup mouseleave", function(e) {
var dragele = $(this);
if (methods.move) {
methods.move = null;
dragele.removeClass("userselect-none cursor-move");
}
}).on("mousemove", function(e) {
var dragele = $(this), position = dragele.position(), movedx, drag = true;
if (methods.move) {
methods.curmove = {
x : e.pageX,
y : e.pageY
};
var routewidth = $(".schedule-route:eq(0)").width() + $(".schedule-route:eq(1)").width();
var maxleft = -(dragele.width() - ($(window).width() - routewidth));
var xcondition = (methods.move.x > methods.curmove.x);
dragele.addClass("userselect-none cursor-move");
if (position.left <= maxleft && xcondition) {
drag = false;
dragele.css({
left : maxleft
});
}
if (position.left > -10 && !xcondition) {
drag = false;
dragele.css({
left : 0
});
}
if (drag) {
//if direction right to left
movedx = methods.move.left + (methods.curmove.x - methods.move.x);
dragele.css({
left : movedx
});
}
}
});
},
now : new Date(),
currentdate : "",
hmtosec : function(hours, identy) {
var s = (hours.match(/\./)) ? hours.split(identy) : [hours, 0], h = s[0], m = s[1];
h = (Number(h)) ? (h * 60) * 60 : 0;
m = (m == 0) ? 0 : m * 60;
return Number(h + m);
},
makeStringToObject : function(string) {
var loc_string = String(string).split("|");
var output = {};
for (var i in loc_string) {
var keyvalue = loc_string[i].split("~");
output[keyvalue[0]] = keyvalue[1];
}
return output;
}
};
return this.each(function() {
methods.init($(this), $.extend({}, $.fn.schedule.setting, options));
});
};
$.fn.schedule.setting = {};
})(jQuery);
and this is the error i am getting
Uncaught TypeError: Cannot read property 'left' of undefined
In service: var deferred = $q.defer();
$http.get('job.json')
.success(function(response) {
defer.resolve(response);
}).error(function(error){
console.log(error);
})
return deferred.promise;
In controller:
var p=<serviceCall>
p.then(function(s){
$scope.ans=s;
})
The $q is used for getting synchronous response.for more details:https://docs.angularjs.org/api/ng/service/$q
You can't do a synchronous HTTP request, since the reponse (in your case it is the JSON file) can not be loaded instantly. However, $http.get returns a promise which is resolved when the request completes. You should do everything you want to do as soon as the JSON file has loaded inside the then-block of the promise.
$http.get('job.json').then(function (response) {
$scope.big = response;
// Do anything else you need to after JSON has been loaded.
});
Using promise.then you can update your value.
var promise=$http.get('job.json');
promise.then(function(result){
$scope.big=response;
});
alternative way
function getObj(callback){
$http.get('job.json').success(callback);;
}
getObj(function(result){
console.log(result)
// add your jquery code
})

How to implement ipad-like password field behaviour in a text input field using jquery

Is there any plugin similar to the iPad-like password field behaviour. We need to show only the focus number that the customer enters when they enter their credit card number, and then switch to a bullet once the customer types the next number.
For numbers that have been entered prior to the number being entered, they all need to be changed to the bullet style.
Not sure about Jquery plugin. tried this out. Hope this works for you - http://jsfiddle.net/Lhw7xcy6/12/
(function () {
var config = {},
bulletsInProgress = false,
bulletTimeout = null,
defaultOpts = {
className: 'input-long',
maxLength: '16',
type: 'tel',
autoComplete: 'off'
};
var generateBullets = function (n) {
var bullets = '';
for (var i = 0; i < n; i++) {
bullets += "\u25CF";
}
return bullets;
},
getCursorPosition = function (elem) {
var el = $(elem).get(0);
var pos = 0;
var posEnd = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
posEnd = el.selectionEnd;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
posEnd = Sel.text.length;
}
return [pos, posEnd];
},
keyInputHandler = function (e, elem, $inpField) {
var keyCode = e.which || e.keyCode,
timeOut = 0,
$bulletField = $(elem),
tempInp = $bulletField.data('tempInp'),
numBullets = $bulletField.data('numBullets');
var position = getCursorPosition(elem);
if (keyCode >= 48 && keyCode <= 57) {
e.preventDefault();
clearTimeout(bulletTimeout);
$bulletField.val(generateBullets(numBullets) + String.fromCharCode(keyCode));
tempInp += String.fromCharCode(keyCode);
numBullets += 1;
bulletsInProgress = true;
timeOut = 3000;
} else if (keyCode == 8) {
clearTimeout(bulletTimeout);
tempInp = (position[0] == position[1]) ? tempInp.substring(0, position[0] - 1) + tempInp.substring(position[1]) : tempInp.substring(0, position[0]) + tempInp.substring(position[1]);
numBullets = (position[0] == position[1]) ? numBullets - 1 : numBullets - (position[1] - position[0]);
tempInp = ($.trim($bulletField.val()) === '') ? '' : tempInp;
numBullets = ($.trim($bulletField.val()) === '') ? 0 : numBullets;
timeOut = 0;
} else {
e.preventDefault();
return false;
}
$bulletField.data('numBullets', numBullets);
$bulletField.data('tempInp', tempInp);
$inpField.val(tempInp);
$('#output').val(tempInp); // testing purpose
bulletTimeout = setTimeout(function () {
$bulletField.val(generateBullets(numBullets));
bulletsInProgress = false;
}, timeOut);
};
$.fn.bulletField = function (options) {
var opts = $.extend({}, defaultOpts, options);
//console.log(opts);
this.each(function () {
var $inpField = $(this),
id = $inpField.attr('id');
$inpField.after('<input id="bullet_' + id + '" type=' + opts.type + ' maxlength=' + opts.maxLength + ' autocomplete=' + opts.autoComplete + ' class=' + opts.className + '>');
$inpField.hide();
var bulletFieldId = 'bullet_' + id;
var $bulletField = $('#' + bulletFieldId);
$bulletField.data('numBullets', 0);
$bulletField.data('tempInp', '');
$('#' + bulletFieldId).on('keydown', function (e) {
keyInputHandler(e, this, $inpField);
});
$('#' + bulletFieldId).on('blur', function () {
//$inpField.trigger('blur');
});
});
return this;
};
}());
$(function () {
/*USAGE - invoke the plugin appropriately whenever needed. example -onclick,onfocus,mousedown etc.*/
//$('body').on('mousedown', '#bulletField', function () {
$('#bulletField').bulletField();
//$('body').off('mousedown');
// });
/* ---OR ----
$('#bulletField').bulletField({
className: 'input-short',
maxLength : '4'
});*/
});

Categories