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>
Related
Hi there I'm pretty new to using functions and onclick actions to call javascript so I could do with some help. Basically, I've installed a plugin on WordPress which adds a button to the page in the form of a widget and once clicked it starts a script. However, I don't like their button so I'm trying to code my own but I want it to start the script like there's.
Here's the script code:
/*
* Timely BookButton plugin
* Example usage:
* var button = new timelyButton('doedayspa');
*
* Booking process can be kicked off manually by calling the start method on the button instance e.g.
* button.start();
*
*/
// Need this for legacy support of older versions of the BookingButton
var timelyButton;
(function () {
"use strict";
var context = window;
var mobile = {
Android: function () {
return navigator.userAgent.match(/Android/i) ? true : false;
},
BlackBerry: function () {
return navigator.userAgent.match(/BlackBerry/i) ? true : false;
},
iOS: function () {
return navigator.userAgent.match(/iPhone|iPod/i) ? true : false;
},
Windows: function () {
return navigator.userAgent.match(/IEMobile/i) ? true : false;
},
any: function () {
return (mobile.Android() || mobile.BlackBerry() || mobile.iOS() || mobile.Windows());
}
};
timelyButton = function (id, opts) {
var options = opts || {};
var businessId = id;
var resellerCode = options.reseller || resellerCode || '';
var productId = options.product || productId || '';
var categoryId = options.category || categoryId || '';
var staffId = options.staff || staffId || '';
var locationId = options.location || locationId || '';
var giftVoucherId = options.giftVoucherId || giftVoucherId || '';
var isPurchaseButton = options.isPurchaseButton != null ? options.isPurchaseButton : false; // default not a purchase
var dontCreateButton = !!options.dontCreateButton;
window.timelyBookFrame = {};
var XD;
var style = options.style || 'light';
var buttonId = options.buttonId || false;
var bookButton;
var scriptSource = (function() {
var script = document.getElementById('timelyScript');
if (script.getAttribute.length !== undefined) {
return script.src;
}
return script.getAttribute('src', -1);
}());
var isOwnImage = !!options.imgSrc;
var imgButtonType = isPurchaseButton ? "purchase-buttons" : "book-buttons";
var imgSrc = options.imgSrc || getDomain() + '/images/' + imgButtonType + '/button_' + style + '#2x.png';
var hoverSrc = getDomain() + '/images/' + imgButtonType + '/button_' + style + '_hover#2x.png';
var activeSrc = getDomain() + '/images/' + imgButtonType + '/button_' + style + '_active#2x.png';
var locationUrl = (isPurchaseButton ? '/giftvoucher/details/' : '/booking/location/') + businessId;
function init() {
if (dontCreateButton) return true;
if (isOwnImage) {
bookButton = document.createElement('a');
bookButton.href = 'javascript:void(0)';
bookButton.onclick = eventHandler.prototype.Book;
bookButton.innerHTML = '<img src=\'' + imgSrc + '\' border=\'0\' />';
} else {
bookButton = document.createElement('a');
bookButton.style.backgroundImage = "url(" + imgSrc + ")";
bookButton.style.backgroundRepeat = "no-repeat";
bookButton.style.backgroundPosition = "0px 0px";
bookButton.style.backgroundSize = (isPurchaseButton ? "220px" : "162px") + " 40px";
bookButton.style.width = isPurchaseButton ? "220px" : "162px";
bookButton.style.height = "40px";
bookButton.style.display = "inline-block";
bookButton.href = 'javascript:void(0)';
bookButton.onclick = eventHandler.prototype.Book;
bookButton.innerHTML += '<img src="' + hoverSrc + '" style="display:none;" border=\'0\' />';
bookButton.innerHTML += '<img src="' + activeSrc + '" style="display:none;" border=\'0\' />';
bookButton.onmouseenter = function() { this.style.backgroundImage = "url(" + hoverSrc + ")"; };
bookButton.onmouseout = function () { this.style.backgroundImage = "url(" + imgSrc + ")"; };
bookButton.onmousedown = function () { this.style.backgroundImage = "url(" + activeSrc + ")"; };
bookButton.onmouseup = function () { this.style.backgroundImage = "url(" + hoverSrc + ")"; };
}
var insertionPoint = findInsertionPoint(buttonId);
insertAfter(bookButton, insertionPoint);
}
function findInsertionPoint(buttonId) {
var insertionPoint = false;
if (buttonId) {
insertionPoint = document.getElementById(buttonId);
} else {
if (("currentScript" in document)) {
insertionPoint = document.currentScript;
} else {
var scripts = document.getElementsByTagName('script');
insertionPoint = scripts[scripts.length - 1];
}
}
return insertionPoint;
}
function getDomain() {
return ('https:' == document.location.protocol ? 'https://' : 'http://') + scriptSource.match( /:\/\/(.[^/]+)/ )[1];
}
function startBooking() {
var url = "";
if (resellerCode) {
url += '&reseller=' + resellerCode;
}
if (productId) {
url += '&productId=' + productId;
}
if (categoryId) {
url += '&categoryId=' + categoryId;
}
if (staffId) {
url += '&staffId=' + staffId;
}
if (locationId) {
url += '&locationId=' + locationId;
}
if (giftVoucherId) {
url += '&giftVoucherId=' + giftVoucherId;
}
if (window.innerWidth < 768 || mobile.any()) {
url = getDomain() + locationUrl + "?mobile=true" + url;
window.location.href = url;
return;
}
window.timelyBookFrame = document.createElement('iframe');
window.timelyBookFrame.className = 'timely-book-frame';
window.timelyBookFrame.style.cssText = 'width: 100%; height: 100%; position: fixed; top: 0; left: 0; z-index: 99999999;';
window.timelyBookFrame.setAttribute('frameBorder', 0);
window.timelyBookFrame.setAttribute('allowTransparency', 'true');
url = getDomain() + (isPurchaseButton ? '/giftvoucher' : '/booking') + '/overlay/' + businessId + '?x' + url;
url += '#' + encodeURIComponent(document.location.href);
window.timelyBookFrame.src = url;
window.timelyBookFrame.style.display = 'none';
document.getElementsByTagName('body')[0].appendChild(window.timelyBookFrame);
var element = document.getElementById('timely-lightbox');
if (typeof(element) != 'undefined' && element != null) {
$('#timely-lightbox').fadeOut();
}
}
function insertAfter(f, n) {
var p = n.parentNode;
if (n.nextSibling) {
p.insertBefore(f, n.nextSibling);
} else {
p.appendChild(f);
}
}
function eventHandler() {
// prototype instance
}
eventHandler.prototype.Book = function() {
startBooking();
};
// everything is wrapped in the XD function to reduce namespace collisions
XD = function () {
var interval_id,
last_hash,
cache_bust = 1,
attached_callback,
window = context;
return {
postMessage: function (message, target_url, target) {
if (!target_url) {
return;
}
target = target || parent; // default to parent
if (window['postMessage']) {
// the browser supports window.postMessage, so call it with a targetOrigin
// set appropriately, based on the target_url parameter.
target['postMessage'](message, target_url.replace(/([^:]+:\/\/[^\/]+).*/, '$1'));
} else if (target_url) {
// the browser does not support window.postMessage, so use the window.location.hash fragment hack
target.location = target_url.replace(/#.*$/, '') + '#' + (+new Date) + (cache_bust++) + '&' + message;
}
},
receiveMessage: function (callback, source_origin) {
// browser supports window.postMessage
if (window['postMessage']) {
// bind the callback to the actual event associated with window.postMessage
if (callback) {
attached_callback = function (e) {
if ((typeof source_origin === 'string' && e.origin !== source_origin)
|| (Object.prototype.toString.call(source_origin) === "[object Function]" && source_origin(e.origin) === !1)) {
return !1;
}
callback(e);
};
}
if (window['addEventListener']) {
window[callback ? 'addEventListener' : 'removeEventListener']('message', attached_callback, !1);
} else {
window[callback ? 'attachEvent' : 'detachEvent']('onmessage', attached_callback);
}
} else {
// a polling loop is started & callback is called whenever the location.hash changes
interval_id && clearInterval(interval_id);
interval_id = null;
if (callback) {
interval_id = setInterval(function () {
var hash = document.location.hash,
re = /^#?\d+&/;
if (hash !== last_hash && re.test(hash)) {
last_hash = hash;
callback({ data: hash.replace(re, '') });
}
}, 100);
}
}
}
};
}();
// setup a callback to handle the dispatched MessageEvent. if window.postMessage is supported the passed
// event will have .data, .origin and .source properties. otherwise, it will only have the .data property.
XD.receiveMessage(function (message) {
if (message.data == 'close') {
var element = document.getElementById('timely-lightbox');
if (typeof (element) != 'undefined' && element != null) {
$('#timely-lightbox').show();
}
if (window.timelyBookFrame && window.timelyBookFrame.parentNode) window.timelyBookFrame.parentNode.removeChild(window.timelyBookFrame);
}
if (message.data == 'open' && window.timelyBookFrame) {
window.timelyBookFrame.style.display = 'block';
}
}, getDomain());
init();
// expose the BookButton API
return {
start: function() {
startBooking();
}
};
};
})();
So how can I run this javascript when I click the button?
Any help would be greatly appreciated!
You could create a script tag automatically if the button has been clicked.
document.getElementById('myButton').addEventListener('click', () => {
const script = document.createElement("script");
script.src = 'my-other-file.js';
document.head.appendChild(script);
})
<button id="myButton">Load JS File</button>
I am using below library for lazy loading the code is as :
angular.module('me-lazyload', [])
.directive('lazySrc', ['$window', '$document', function($window, $document){
var doc = $document[0],
body = doc.body,
win = $window,
$win = angular.element(win),
uid = 0,
elements = {};
function getUid(el){
var __uid = el.data("__uid");
if (! __uid) {
el.data("__uid", (__uid = '' + ++uid));
}
return __uid;
}
function getWindowOffset(){
var t,
pageXOffset = (typeof win.pageXOffset == 'number') ? win.pageXOffset : (((t = doc.documentElement) || (t = body.parentNode)) && typeof t.scrollLeft == 'number' ? t : body).scrollLeft,
pageYOffset = (typeof win.pageYOffset == 'number') ? win.pageYOffset : (((t = doc.documentElement) || (t = body.parentNode)) && typeof t.scrollTop == 'number' ? t : body).scrollTop;
return {
offsetX: pageXOffset,
offsetY: pageYOffset
};
}
function isVisible(iElement){
var elem = iElement[0],
elemRect = elem.getBoundingClientRect(),
windowOffset = getWindowOffset(),
winOffsetX = windowOffset.offsetX,
winOffsetY = windowOffset.offsetY,
elemWidth = elemRect.width || elem.width,
elemHeight = elemRect.height || elem.height,
elemOffsetX = elemRect.left + winOffsetX,
elemOffsetY = elemRect.top + winOffsetY,
viewWidth = Math.max(doc.documentElement.clientWidth, win.innerWidth || 0),
viewHeight = Math.max(doc.documentElement.clientHeight, win.innerHeight || 0),
xVisible,
yVisible;
if(elemOffsetY <= winOffsetY){
if(elemOffsetY + elemHeight >= winOffsetY){
yVisible = true;
}
}else if(elemOffsetY >= winOffsetY){
if(elemOffsetY <= winOffsetY + viewHeight){
yVisible = true;
}
}
if(elemOffsetX <= winOffsetX){
if(elemOffsetX + elemWidth >= winOffsetX){
xVisible = true;
}
}else if(elemOffsetX >= winOffsetX){
if(elemOffsetX <= winOffsetX + viewWidth){
xVisible = true;
}
}
return xVisible && yVisible;
};
function checkImage(){
angular.forEach(elements, function(obj, key) {
var iElement = obj.iElement,
$scope = obj.$scope;
if(isVisible(iElement)){
iElement.attr('src', $scope.lazySrc);
}
});
}
$win.bind('scroll', checkImage);
$win.bind('resize', checkImage);
function onLoad(){
var $el = angular.element(this),
uid = getUid($el);
$el.css('opacity', 1);
if(elements.hasOwnProperty(uid)){
delete elements[uid];
}
}
return {
restrict: 'A',
scope: {
lazySrc: '#',
animateVisible: '#',
animateSpeed: '#'
},
link: function($scope, iElement){
iElement.bind('load', onLoad);
$scope.$watch('lazySrc', function(){
var speed = "1s";
if ($scope.animateSpeed != null) {
speed = $scope.animateSpeed;
}
if(isVisible(iElement)){
if ($scope.animateVisible) {
iElement.css({
'opacity': 0,
'-webkit-transition': 'opacity ' + speed,
'transition': 'opacity ' + speed
});
}
iElement.attr('src', $scope.lazySrc);
}else{
var uid = getUid(iElement);
iElement.css({
'opacity': 0,
'-webkit-transition': 'opacity ' + speed,
'transition': 'opacity ' + speed
});
elements[uid] = {
iElement: iElement,
$scope: $scope
};
}
});
$scope.$on('$destroy', function(){
iElement.unbind('load');
var uid = getUid(iElement);
if(elements.hasOwnProperty(uid)){
delete elements[uid];
}
});
}
};
}]);
works good for vertical scroll but when i go for horizontal scroll the images doesn't load until i scroll vertically and i the default image also doesn't work for this.
for more reference go to https://github.com/Treri/me-lazyload
regards
!function ($) {
"use strict"; // jshint ;_
/* FILEUPLOAD PUBLIC CLASS DEFINITION
* ================================= */
var Fileupload = function (element, options) {
this.$element = $(element)
this.type = this.$element.data('uploadtype') || (this.$element.find('.thumbnail').length > 0 ? "image" : "file")
this.$input = this.$element.find(':file')
if (this.$input.length === 0) return
this.name = this.$input.attr('name') || options.name
this.$hidden = this.$element.find('input[type=hidden][name="'+this.name+'"]')
if (this.$hidden.length === 0) {
this.$hidden = $('<input type="hidden" />')
this.$element.prepend(this.$hidden)
}
this.$preview = this.$element.find('.fileupload-preview')
var height = this.$preview.css('height')
if (this.$preview.css('display') != 'inline' && height != '0px' && height != 'none') this.$preview.css('line-height', height)
this.original = {
'exists': this.$element.hasClass('fileupload-exists'),
'preview': this.$preview.html(),
'hiddenVal': this.$hidden.val()
}
this.$remove = this.$element.find('[data-dismiss="fileupload"]')
this.$element.find('[data-trigger="fileupload"]').on('click.fileupload', $.proxy(this.trigger, this))
this.listen()
}
Fileupload.prototype = {
listen: function() {
this.$input.on('change.fileupload', $.proxy(this.change, this))
$(this.$input[0].form).on('reset.fileupload', $.proxy(this.reset, this))
if (this.$remove) this.$remove.on('click.fileupload', $.proxy(this.clear, this))
},
change: function(e, invoked) {
if (invoked === 'clear') return
var file = e.target.files !== undefined ? e.target.files[0] : (e.target.value ? { name: e.target.value.replace(/^.+\\/, '') } : null)
if (!file) {
this.clear()
return
}
this.$hidden.val('')
this.$hidden.attr('name', '')
this.$input.attr('name', this.name)
if (this.type === "image" && this.$preview.length > 0 && (typeof file.type !== "undefined" ? file.type.match('image.*') : file.name.match(/\.(gif|png|jpe?g)$/i)) && typeof FileReader !== "undefined") {
var reader = new FileReader()
var preview = this.$preview
var element = this.$element
reader.onload = function(e) {
preview.html('<img src="' + e.target.result + '" ' + (preview.css('max-height') != 'none' ? 'style="max-height: ' + preview.css('max-height') + ';"' : '') + ' />')
element.addClass('fileupload-exists').removeClass('fileupload-new')
}
reader.readAsDataURL(file)
} else {
this.$preview.text(file.name)
this.$element.addClass('fileupload-exists').removeClass('fileupload-new')
}
},
clear: function(e) {
this.$hidden.val('')
this.$hidden.attr('name', this.name)
this.$input.attr('name', '')
//ie8+ doesn't support changing the value of input with type=file so clone instead
if (navigator.userAgent.match(/msie/i)){
var inputClone = this.$input.clone(true);
this.$input.after(inputClone);
this.$input.remove();
this.$input = inputClone;
}else{
this.$input.val('')
}
this.$preview.html('')
this.$element.addClass('fileupload-new').removeClass('fileupload-exists')
if (e) {
this.$input.trigger('change', [ 'clear' ])
e.preventDefault()
}
},
reset: function(e) {
this.clear()
this.$hidden.val(this.original.hiddenVal)
this.$preview.html(this.original.preview)
if (this.original.exists) this.$element.addClass('fileupload-exists').removeClass('fileupload-new')
else this.$element.addClass('fileupload-new').removeClass('fileupload-exists')
},
trigger: function(e) {
this.$input.trigger('click')
e.preventDefault()
}
}
/* FILEUPLOAD PLUGIN DEFINITION
* =========================== */
$.fn.fileupload = function (options) {
return this.each(function () {
var $this = $(this)
, data = $this.data('fileupload')
if (!data) $this.data('fileupload', (data = new Fileupload(this, options)))
if (typeof options == 'string') data[options]()
})
}
$.fn.fileupload.Constructor = Fileupload
/* FILEUPLOAD DATA-API
* ================== */
$(document).on('click.fileupload.data-api', '[data-provides="fileupload"]', function (e) {
var $this = $(this)
if ($this.data('fileupload')) return
$this.fileupload($this.data())
var $target = $(e.target).closest('[data-dismiss="fileupload"],[data-trigger="fileupload"]');
if ($target.length > 0) {
$target.trigger('click.fileupload')
e.preventDefault()
}
})
}(window.jQuery);
I am using this js for upload file. with it i can upload and preview only one file but i want to upload multiple file with preview anyone can help me to make it for multiple file upload .
i wanna upload multiple file within a time with preview.
see this example.
<div id="mulitplefileuploader">Upload</div>
<div id="status"></div>
<script>
$(document).ready(function()
{
var settings = {
url: "upload.php",
method: "POST",
allowedTypes:"jpg,png,gif,doc,pdf,zip",
fileName: "myfile",
multiple: true,
onSuccess:function(files,data,xhr)
{
$("#status").html("<font color='green'>Upload is success</font>");
},
afterUploadAll:function()
{
alert("all images uploaded!!");
},
onError: function(files,status,errMsg)
{
$("#status").html("<font color='red'>Upload is Failed</font>");
}
}
$("#mulitplefileuploader").uploadFile(settings);
});
</script>
//php code
$output_dir = "./uploads/";
if(isset($_FILES["myfile"]))
{
$ret = array();
$error =$_FILES["myfile"]["error"];
{
if(!is_array($_FILES["myfile"]['name'])) //single file
{
$RandomNum = time();
$ImageName = $_FILES['myfile']['name'];
$ImageType = $_FILES['myfile']['type']; //"image/png", image/jpeg etc.
if (is_dir($output_dir) && is_writable($output_dir)) {
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $ImageName);
//echo "<br> Error: ".$_FILES["myfile"]["error"];
$ret[$ImageName]= $output_dir.$ImageName;
}
else {
echo 'Upload directory is not writable, or does not exist.';
}
}
else
{
$fileCount = count($_FILES["myfile"]['name']);
for($i=0; $i < $fileCount; $i++)
{
$ImageName = $_FILES['myfile']['name'][$i];
$ImageType = $_FILES['myfile']['type'][$i]; //"image/png", image/jpeg etc.
$ret[$ImageName]= $output_dir.$ImageName;
if (is_dir($output_dir) && is_writable($output_dir)) {
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$ImageName );
}
else {
echo 'Upload directory is multi not writable, or does not exist.';
}
}
}
}
echo json_encode($ret);
}
//js code
/*!
* jQuery Upload File Plugin
* version: 3.1.2
* #requires jQuery v1.5 or later & form plugin
* Copyright (c) 2013 Ravishanker Kusuma
* http://hayageek.com/
*/
(function(b) {
if (b.fn.ajaxForm == undefined) {
b.getScript("http://malsup.github.io/jquery.form.js")
}
var a = {};
a.fileapi = b("<input type='file'/>").get(0).files !== undefined;
a.formdata = window.FormData !== undefined;
b.fn.uploadFile = function(t) {
var r = b.extend({
url: "",
method: "POST",
enctype: "multipart/form-data",
formData: null,
returnType: null,
allowedTypes: "*",
fileName: "file",
formData: {},
dynamicFormData: function() {
return {}
},
maxFileSize: -1,
maxFileCount: -1,
multiple: true,
dragDrop: true,
autoSubmit: true,
showCancel: true,
showAbort: true,
showDone: true,
showDelete: false,
showError: true,
showStatusAfterSuccess: true,
showStatusAfterError: true,
showFileCounter: true,
fileCounterStyle: "). ",
showProgress: false,
onSelect: function(s) {
return true
},
onSubmit: function(s, u) {},
onSuccess: function(u, s, v) {},
onError: function(v, s, u) {},
deleteCallback: false,
afterUploadAll: false,
uploadButtonClass: "upload",
dragDropStr: "<span><b>Drag & Drop Files</b></span>",
abortStr: "Abort",
cancelStr: "Cancel",
deletelStr: "Delete",
doneStr: "Done",
multiDragErrorStr: "Multiple File Drag & Drop is not allowed.",
extErrorStr: "is not allowed. Allowed extensions: ",
sizeErrorStr: "is not allowed. Allowed Max size: ",
uploadErrorStr: "Upload is not allowed",
maxFileCountErrorStr: " is not allowed. Maximum allowed files are:"
}, t);
this.fileCounter = 1;
this.selectedFiles = 0;
this.fCounter = 0;
this.sCounter = 0;
this.tCounter = 0;
var d = "upload-" + (new Date().getTime());
this.formGroup = d;
this.hide();
this.errorLog = b("<div></div>");
this.after(this.errorLog);
this.responses = [];
if (!a.formdata) {
r.dragDrop = false
}
if (!a.formdata) {
r.multiple = false
}
var m = this;
var e = b("<div>" + b(this).html() + "</div>");
b(e).addClass(r.uploadButtonClass);
(function k() {
if (b.fn.ajaxForm) {
if (r.dragDrop) {
var s = b('<div class="ajax-upload-dragdrop" style="vertical-align:top;"></div>');
b(m).before(s);
b(s).append(e);
b(s).append(b(r.dragDropStr));
f(m, r, s)
} else {
b(m).before(e)
}
q(m, d, r, e)
} else {
window.setTimeout(k, 10)
}
})();
this.startUpload = function() {
b("." + this.formGroup).each(function(u, s) {
if (b(this).is("form")) {
b(this).submit()
}
})
};
this.stopUpload = function() {
b(".upload-red").each(function(u, s) {
if (b(this).hasClass(m.formGroup)) {
b(this).click()
}
})
};
this.getResponses = function() {
return this.responses
};
var g = false;
function j() {
if (r.afterUploadAll && !g) {
g = true;
(function s() {
if (m.sCounter != 0 && (m.sCounter + m.fCounter == m.tCounter)) {
r.afterUploadAll(m);
g = false
} else {
window.setTimeout(s, 100)
}
})()
}
}
function f(w, u, v) {
v.on("dragenter", function(s) {
s.stopPropagation();
s.preventDefault();
b(this).css("border", "2px solid #000000")
});
v.on("dragover", function(s) {
s.stopPropagation();
s.preventDefault()
});
v.on("drop", function(x) {
b(this).css("border", "2px solid #000000");
x.preventDefault();
w.errorLog.html("");
var s = x.originalEvent.dataTransfer.files;
if (!u.multiple && s.length > 1) {
if (u.showError) {
b("<div style='color:red;'>" + u.multiDragErrorStr + "</div>").appendTo(w.errorLog)
}
return
}
if (u.onSelect(s) == false) {
return
}
l(u, w, s)
});
b(document).on("dragenter", function(s) {
s.stopPropagation();
s.preventDefault()
});
b(document).on("dragover", function(s) {
s.stopPropagation();
s.preventDefault();
v.css("border", "2px solid #000000")
});
b(document).on("drop", function(s) {
s.stopPropagation();
s.preventDefault();
v.css("border", "2px solid #000000")
})
}
function i(s) {
var v = "";
var u = s / 1024;
if (parseInt(u) > 1024) {
var w = u / 1024;
v = w.toFixed(2) + " MB"
} else {
v = u.toFixed(2) + " KB"
}
return v
}
function o(x) {
var y = [];
if (jQuery.type(x) == "string") {
y = x.split("&")
} else {
y = b.param(x).split("&")
}
var u = y.length;
var s = [];
var w, v;
for (w = 0; w < u; w++) {
y[w] = y[w].replace(/\+/g, " ");
v = y[w].split("=");
s.push([decodeURIComponent(v[0]), decodeURIComponent(v[1])])
}
return s
}
function l(H, B, u) {
for (var C = 0; C < u.length; C++) {
if (!c(B, H, u[C].name)) {
if (H.showError) {
b("<div style='color:red;'><b>" + u[C].name + "</b> " + H.extErrorStr + H.allowedTypes + "</div>").appendTo(B.errorLog)
}
continue
}
if (H.maxFileSize != -1 && u[C].size > H.maxFileSize) {
if (H.showError) {
b("<div style='color:red;'><b>" + u[C].name + "</b> " + H.sizeErrorStr + i(H.maxFileSize) + "</div>").appendTo(B.errorLog)
}
continue
}
if (H.maxFileCount != -1 && B.selectedFiles >= H.maxFileCount) {
if (H.showError) {
b("<div style='color:red;'><b>" + u[C].name + "</b> " + H.maxFileCountErrorStr + H.maxFileCount + "</div>").appendTo(B.errorLog)
}
continue
}
B.selectedFiles++;
var D = H;
var w = new FormData();
var A = H.fileName.replace("[]", "");
w.append(A, u[C]);
var y = H.formData;
if (y) {
var F = o(y);
for (var z = 0; z < F.length; z++) {
if (F[z]) {
w.append(F[z][0], F[z][1])
}
}
}
D.fileData = w;
var E = new p(B, H);
var G = "";
if (H.showFileCounter) {
G = B.fileCounter + H.fileCounterStyle + u[C].name
} else {
G = u[C].name
}
E.filename.html(G);
var v = b("<form style='display:block; position:absolute;left: 150px;' class='" + B.formGroup + "' method='" + H.method + "' action='" + H.url + "' enctype='" + H.enctype + "'></form>");
v.appendTo("body");
var x = [];
x.push(u[C].name);
n(v, D, E, x, B);
B.fileCounter++
}
}
function c(w, v, y) {
var x = v.allowedTypes.toLowerCase().split(",");
var u = y.split(".").pop().toLowerCase();
if (v.allowedTypes != "*" && jQuery.inArray(u, x) < 0) {
return false
}
return true
}
function h(u, w) {
if (u.showFileCounter) {
var v = b(".upload-filename").length;
w.fileCounter = v + 1;
b(".upload-filename").each(function(A, y) {
var s = b(this).html().split(u.fileCounterStyle);
var x = parseInt(s[0]) - 1;
var z = v + u.fileCounterStyle + s[1];
b(this).html(z);
v--
})
}
}
function q(y, B, D, u) {
var A = "ajax-upload-id-" + (new Date().getTime());
var w = b("<form method='" + D.method + "' action='" + D.url + "' enctype='" + D.enctype + "'></form>");
var v = "<input type='file' id='" + A + "' name='" + D.fileName + "'/>";
if (D.multiple) {
if (D.fileName.indexOf("[]") != D.fileName.length - 2) {
D.fileName += "[]"
}
v = "<input type='file' id='" + A + "' name='" + D.fileName + "' multiple/>"
}
var z = b(v).appendTo(w);
z.change(function() {
y.errorLog.html("");
var K = D.allowedTypes.toLowerCase().split(",");
var G = [];
if (this.files) {
for (H = 0; H < this.files.length; H++) {
G.push(this.files[H].name)
}
if (D.onSelect(this.files) == false) {
return
}
} else {
var I = b(this).val();
var F = [];
G.push(I);
if (!c(y, D, I)) {
if (D.showError) {
b("<div style='color:red;'><b>" + I + "</b> " + D.extErrorStr + D.allowedTypes + "</div>").appendTo(y.errorLog)
}
return
}
F.push({
name: I,
size: "NA"
});
if (D.onSelect(F) == false) {
return
}
}
h(D, y);
u.unbind("click");
w.hide();
q(y, B, D, u);
w.addClass(B);
if (a.fileapi && a.formdata) {
w.removeClass(B);
var J = this.files;
l(D, y, J)
} else {
var E = "";
for (var H = 0; H < G.length; H++) {
if (D.showFileCounter) {
E += y.fileCounter + D.fileCounterStyle + G[H] + "<br>"
} else {
E += G[H] + "<br>"
}
y.fileCounter++
}
if (D.maxFileCount != -1 && (y.selectedFiles + G.length) > D.maxFileCount) {
if (D.showError) {
b("<div style='color:red;'><b>" + E + "</b> " + D.maxFileCountErrorStr + D.maxFileCount + "</div>").appendTo(y.errorLog)
}
return
}
y.selectedFiles += G.length;
var s = new p(y, D);
s.filename.html(E);
n(w, D, s, G, y)
}
});
w.css({
margin: 0,
padding: 0
});
var C = b(u).width() + 10;
if (C == 10) {
C = 120
}
var x = u.height() + 10;
if (x == 10) {
x = 35
}
u.css({
position: "relative",
overflow: "hidden",
cursor: "default"
});
z.css({
position: "absolute",
cursor: "pointer",
top: "0px",
width: C,
height: x,
left: "0px",
"z-index": "100",
opacity: "0.0",
filter: "alpha(opacity=0)",
"-ms-filter": "alpha(opacity=0)",
"-khtml-opacity": "0.0",
"-moz-opacity": "0.0"
});
w.appendTo(u)
}
function p(v, u) {
//console.log(this);
this.statusbar = b("<div class='upload-statusbar'></div>");
this.filename = b("<div class='upload-filename'></div>").appendTo(this.statusbar);
this.progressDiv = b("<div class='upload-progress'>").appendTo(this.statusbar).hide();
this.progressbar = b("<div class='upload-bar " + v.formGroup + "'></div>").appendTo(this.progressDiv);
this.abort = b("<div class='upload-red " + v.formGroup + "'>" + u.abortStr + "</div>").appendTo(this.statusbar).hide();
this.cancel = b("<div class='upload-red'>" + u.cancelStr + "</div>").appendTo(this.statusbar).hide();
this.done = b("<div class='upload-green'>" + u.doneStr + "</div>").appendTo(this.statusbar).hide();
this.del = b("<div class='upload-red'>" + u.deletelStr + "</div>").appendTo(this.statusbar).hide();
v.errorLog.after(this.statusbar);
return this
}
function n(z, y, u, w, A) {
var x = null;
var v = {
cache: false,
contentType: false,
processData: false,
forceSync: false,
data: y.formData,
formData: y.fileData,
dataType: y.returnType,
beforeSubmit: function(F, C, E) {
if (y.onSubmit.call(this, w) != false) {
var B = y.dynamicFormData();
if (B) {
var s = o(B);
if (s) {
for (var D = 0; D < s.length; D++) {
if (s[D]) {
if (y.fileData != undefined) {
E.formData.append(s[D][0], s[D][1])
} else {
E.data[s[D][0]] = s[D][1]
}
}
}
}
}
A.tCounter += w.length;
j();
return true
}
u.statusbar.append("<div style='color:red;'>" + y.uploadErrorStr + "</div>");
u.cancel.show();
z.remove();
u.cancel.click(function() {
u.statusbar.remove()
});
return false
},
beforeSend: function(B, s) {
u.progressDiv.show();
u.cancel.hide();
u.done.hide();
if (y.showAbort) {
u.abort.show();
u.abort.click(function() {
B.abort();
A.selectedFiles -= w.length
})
}
if (!a.formdata) {
u.progressbar.width("5%")
} else {
u.progressbar.width("1%")
}
},
uploadProgress: function(E, s, D, C) {
if (C > 98) {
C = 98
}
var B = C + "%";
if (C > 1) {
u.progressbar.width(B)
}
if (y.showProgress) {
u.progressbar.html(B);
u.progressbar.css("text-align", "center")
}
},
success: function(B, s, C) {
A.responses.push(B);
u.progressbar.width("100%");
if (y.showProgress) {
u.progressbar.html("100%");
u.progressbar.css("text-align", "center")
}
u.abort.hide();
y.onSuccess.call(this, w, B, C);
if (y.showStatusAfterSuccess) {
if (y.showDone) {
u.done.show();
u.done.click(function() {
u.statusbar.hide("slow");
u.statusbar.remove()
})
} else {
u.done.hide()
}
if (y.showDelete) {
u.del.show();
u.del.click(function() {
u.statusbar.hide().remove();
if (y.deleteCallback) {
y.deleteCallback.call(this, B, u)
}
A.selectedFiles -= w.length;
h(y, A)
})
} else {
u.del.hide()
}
} else {
u.statusbar.hide("slow");
u.statusbar.remove()
}
z.remove();
A.sCounter += w.length
},
error: function(C, s, B) {
u.abort.hide();
if (C.statusText == "abort") {
u.statusbar.hide("slow").remove();
h(y, A)
} else {
y.onError.call(this, w, s, B);
if (y.showStatusAfterError) {
u.progressDiv.hide();
u.statusbar.append("<span style='color:red;'>ERROR: " + B + "</span>")
} else {
u.statusbar.hide();
u.statusbar.remove()
}
A.selectedFiles -= w.length
}
z.remove();
A.fCounter += w.length
}
};
if (y.autoSubmit) {
z.ajaxSubmit(v)
} else {
if (y.showCancel) {
u.cancel.show();
u.cancel.click(function() {
z.remove();
u.statusbar.remove();
A.selectedFiles -= w.length;
h(y, A)
})
}
z.ajaxForm(v)
}
}
return this
}
}(jQuery));
It works in chrome.But when i use with Mozilla Firefox then it shows this
" A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue.
Script: http://localhost/tsdev_v2/resources/js/libs/jquery-1.8.3.js:6841"
My code is...
<script>
/*$("table").stickyTableHeaders();*/
/* $(function(){
$("table").stickyTableHeaders();
});*/
$(document).ready(function() {
$("table").stickyTableHeaders({fixedOffset:40});
});
</script>
<script>
;(function ($, window, undefined) {
'use strict';
var name = 'stickyTableHeaders',
id = 0,
defaults = {
fixedOffset: 0,
leftOffset: 0,
marginTop: 0,
objDocument: document,
objHead: 'head',
objWindow: window,
scrollableArea: window
};
function Plugin (el, options) {
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
base.id = id++;
// Listen for destroyed, call teardown
base.$el.bind('destroyed',
$.proxy(base.teardown, base));
// Cache DOM refs for performance reasons
base.$clonedHeader = null;
base.$originalHeader = null;
// Keep track of state
base.isSticky = false;
base.hasBeenSticky = false;
base.leftOffset = null;
base.topOffset = null;
base.init = function () {
base.setOptions(options);
base.$el.each(function () {
var $this = $(this);
// remove padding on <table> to fix issue #7
$this.css('padding', 0);
base.$originalHeader = $('thead:first', this);
base.$clonedHeader = base.$originalHeader.clone();
$this.trigger('clonedHeader.' + name, [base.$clonedHeader]);
base.$clonedHeader.addClass('tableFloatingHeader');
base.$clonedHeader.css('display', 'none');
base.$originalHeader.addClass('tableFloatingHeaderOriginal');
base.$originalHeader.after(base.$clonedHeader);
base.$printStyle = $('<style type="text/css" media="print">' +
'.tableFloatingHeader{display:none !important;}' +
'.tableFloatingHeaderOriginal{position:static !important;}' +
'</style>');
base.$head.append(base.$printStyle);
});
base.updateWidth();
base.toggleHeaders();
base.bind();
};
base.destroy = function (){
base.$el.unbind('destroyed', base.teardown);
base.teardown();
};
base.teardown = function(){
if (base.isSticky) {
base.$originalHeader.css('position', 'static');
}
$.removeData(base.el, 'plugin_' + name);
base.unbind();
base.$clonedHeader.remove();
base.$originalHeader.removeClass('tableFloatingHeaderOriginal');
base.$originalHeader.css('visibility', 'visible');
base.$printStyle.remove();
base.el = null;
base.$el = null;
};
base.bind = function(){
base.$scrollableArea.on('scroll.' + name, base.toggleHeaders);
if (!base.isWindowScrolling) {
base.$window.on('scroll.' + name + base.id, base.setPositionValues);
base.$window.on('resize.' + name + base.id, base.toggleHeaders);
}
base.$scrollableArea.on('resize.' + name, base.toggleHeaders);
base.$scrollableArea.on('resize.' + name, base.updateWidth);
};
base.unbind = function(){
// unbind window events by specifying handle so we don't remove too much
base.$scrollableArea.off('.' + name, base.toggleHeaders);
if (!base.isWindowScrolling) {
base.$window.off('.' + name + base.id, base.setPositionValues);
base.$window.off('.' + name + base.id, base.toggleHeaders);
}
base.$scrollableArea.off('.' + name, base.updateWidth);
};
base.toggleHeaders = function () {
if (base.$el) {
base.$el.each(function () {
var $this = $(this),
newLeft,
newTopOffset = base.isWindowScrolling ? (
isNaN(base.options.fixedOffset) ?
base.options.fixedOffset.outerHeight() :
base.options.fixedOffset
) :
base.$scrollableArea.offset().top + (!isNaN(base.options.fixedOffset) ? base.options.fixedOffset : 0),
offset = $this.offset(),
scrollTop = base.$scrollableArea.scrollTop() + newTopOffset,
scrollLeft = base.$scrollableArea.scrollLeft(),
scrolledPastTop = base.isWindowScrolling ?
scrollTop > offset.top :
newTopOffset > offset.top,
notScrolledPastBottom = (base.isWindowScrolling ? scrollTop : 0) <
(offset.top + $this.height() - base.$clonedHeader.height() - (base.isWindowScrolling ? 0 : newTopOffset));
if (scrolledPastTop && notScrolledPastBottom) {
newLeft = offset.left - scrollLeft + base.options.leftOffset;
base.$originalHeader.css({
'position': 'fixed',
'margin-top': base.options.marginTop,
'left': newLeft,
'z-index': 3 // #18: opacity bug
});
base.leftOffset = newLeft;
base.topOffset = newTopOffset;
base.$clonedHeader.css('display', '');
if (!base.isSticky) {
base.isSticky = true;
// make sure the width is correct: the user might have resized the browser while in static mode
base.updateWidth();
$this.trigger('enabledStickiness.' + name);
}
base.setPositionValues();
} else if (base.isSticky) {
base.$originalHeader.css('position', 'static');
base.$clonedHeader.css('display', 'none');
base.isSticky = false;
base.resetWidth($('td,th', base.$clonedHeader), $('td,th', base.$originalHeader));
$this.trigger('disabledStickiness.' + name);
}
});
}
};
base.setPositionValues = function () {
var winScrollTop = base.$window.scrollTop(),
winScrollLeft = base.$window.scrollLeft();
if (!base.isSticky ||
winScrollTop < 0 || winScrollTop + base.$window.height() > base.$document.height() ||
winScrollLeft < 0 || winScrollLeft + base.$window.width() > base.$document.width()) {
return;
}
base.$originalHeader.css({
'top': base.topOffset - (base.isWindowScrolling ? 0 : winScrollTop),
'left': base.leftOffset - (base.isWindowScrolling ? 0 : winScrollLeft)
});
};
base.updateWidth = function () {
if (!base.isSticky) {
return;
}
// Copy cell widths from clone
if (!base.$originalHeaderCells) {
base.$originalHeaderCells = $('th,td', base.$originalHeader);
}
if (!base.$clonedHeaderCells) {
base.$clonedHeaderCells = $('th,td', base.$clonedHeader);
}
var cellWidths = base.getWidth(base.$clonedHeaderCells);
base.setWidth(cellWidths, base.$clonedHeaderCells, base.$originalHeaderCells);
// Copy row width from whole table
base.$originalHeader.css('width', base.$clonedHeader.width());
};
base.getWidth = function ($clonedHeaders) {
var widths = [];
$clonedHeaders.each(function (index) {
var width, $this = $(this);
if ($this.css('box-sizing') === 'border-box') {
var boundingClientRect = $this[0].getBoundingClientRect();
if(boundingClientRect.width) {
width = boundingClientRect.width; // #39: border-box bug
} else {
width = boundingClientRect.right - boundingClientRect.left; // ie8 bug: getBoundingClientRect() does not have a width property
}
} else {
var $origTh = $('th', base.$originalHeader);
if ($origTh.css('border-collapse') === 'collapse') {
if (window.getComputedStyle) {
width = parseFloat(window.getComputedStyle(this, null).width);
} else {
// ie8 only
var leftPadding = parseFloat($this.css('padding-left'));
var rightPadding = parseFloat($this.css('padding-right'));
// Needs more investigation - this is assuming constant border around this cell and it's neighbours.
var border = parseFloat($this.css('border-width'));
width = $this.outerWidth() - leftPadding - rightPadding - border;
}
} else {
width = $this.width();
}
}
widths[index] = width;
});
return widths;
};
base.setWidth = function (widths, $clonedHeaders, $origHeaders) {
$clonedHeaders.each(function (index) {
var width = widths[index];
$origHeaders.eq(index).css({
'min-width': width,
'max-width': width
});
});
};
base.resetWidth = function ($clonedHeaders, $origHeaders) {
$clonedHeaders.each(function (index) {
var $this = $(this);
$origHeaders.eq(index).css({
'min-width': $this.css('min-width'),
'max-width': $this.css('max-width')
});
});
};
base.setOptions = function (options) {
base.options = $.extend({}, defaults, options);
base.$window = $(base.options.objWindow);
base.$head = $(base.options.objHead);
base.$document = $(base.options.objDocument);
base.$scrollableArea = $(base.options.scrollableArea);
base.isWindowScrolling = base.$scrollableArea[0] === base.$window[0];
};
base.updateOptions = function (options) {
base.setOptions(options);
// scrollableArea might have changed
base.unbind();
base.bind();
base.updateWidth();
base.toggleHeaders();
};
// Run initializer
base.init();
}
// A plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[name] = function ( options ) {
return this.each(function () {
var instance = $.data(this, 'plugin_' + name);
if (instance) {
if (typeof options === 'string') {
instance[options].apply(instance);
} else {
instance.updateOptions(options);
}
} else if(options !== 'destroy') {
$.data(this, 'plugin_' + name, new Plugin( this, options ));
}
});
};
})(jQuery, window);
</script>
In my jquery-1.8.3.js:6841
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
How to recover this ? Please help.
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'
});*/
});