Related
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>
I need to have a lightbox image link to another page, in this case it's on tumblr as the permalink page. I tried wrapping the markup of mfp-img div in a href with "{Permalink}" (as per tumblr's api) and then "%url%", but both render exactly the same as inside the quotes, rather than the actual link to the page.
I'm quite familiar with css, but unfortunately my js is lacking. Here's the portion of the code that controls the lightbox image. Where and how should I add the href to the code?
a.magnificPopup.registerModule("image", {
options: {
markup: '<div class="mfp-figure"><div class="mfp-close"></div><div class="mfp-img"></div><div class="mfp-bottom-bar"><div class="mfp-title"></div><div class="mfp-counter"></div></div></div>',
cursor: "mfp-zoom-out-cur",
titleSrc: "title",
verticalFit: !0,
tError: 'The image could not be loaded.'
},
proto: {
initImage: function() {
var a = n.st.image,
c = ".image";
n.types.push("image"), x(g + c, function() {
n.currItem.type === "image" && a.cursor && s.addClass(a.cursor)
}), x(b + c, function() {
a.cursor && s.removeClass(a.cursor), r.off("resize" + j)
}), x("Resize" + c, n.resizeImage), n.isLowIE && x("AfterChange", n.resizeImage)
},
resizeImage: function() {
var a = n.currItem;
if (!a || !a.img) return;
if (n.st.image.verticalFit) {
var b = 0;
n.isLowIE && (b = parseInt(a.img.css("padding-top"), 10) + parseInt(a.img.css("padding-bottom"), 10)), a.img.css("max-height", n.wH - b)
}
},
_onImageHasSize: function(a) {
a.img && (a.hasSize = !0, N && clearInterval(N), a.isCheckingImgSize = !1, z("ImageHasSize", a), a.imgHidden && (n.content && n.content.removeClass("mfp-loading"), a.imgHidden = !1))
},
findImageSize: function(a) {
var b = 0,
c = a.img[0],
d = function(e) {
N && clearInterval(N), N = setInterval(function() {
if (c.naturalWidth > 0) {
n._onImageHasSize(a);
return
}
b > 200 && clearInterval(N), b++, b === 3 ? d(10) : b === 40 ? d(50) : b === 100 && d(500)
}, e)
};
d(1)
},
getImage: function(b, c) {
var d = 0,
e = function() {
b && (b.img[0].complete ? (b.img.off(".mfploader"), b === n.currItem && (n._onImageHasSize(b), n.updateStatus("ready")), b.hasSize = !0, b.loaded = !0, z("ImageLoadComplete")) : (d++, d < 200 ? setTimeout(e, 100) : f()))
},
f = function() {
b && (b.img.off(".mfploader"), b === n.currItem && (n._onImageHasSize(b), n.updateStatus("error", g.tError.replace("%url%", b.src))), b.hasSize = !0, b.loaded = !0, b.loadError = !0)
},
g = n.st.image,
h = c.find(".mfp-img");
if (h.length) {
var i = document.createElement("img");
i.className = "mfp-img", b.img = a(i).on("load.mfploader", e).on("error.mfploader", f), i.src = b.src, h.is("img") && (b.img = b.img.clone()), b.img[0].naturalWidth > 0 && (b.hasSize = !0)
}
return n._parseMarkup(c, {
title: O(b),
img_replaceWith: b.img
}, b), n.resizeImage(), b.hasSize ? (N && clearInterval(N), b.loadError ? (c.addClass("mfp-loading"), n.updateStatus("error", g.tError.replace("%url%", b.src))) : (c.removeClass("mfp-loading"), n.updateStatus("ready")), c) : (n.updateStatus("loading"), b.loading = !0, b.hasSize || (b.imgHidden = !0, c.addClass("mfp-loading"), n.findImageSize(b)), c)
}
}
});
var P, Q = function() {
return P === undefined && (P = document.createElement("p").style.MozTransform !== undefined), P
};
a.magnificPopup.registerModule("zoom", {
options: {
enabled: !1,
easing: "ease-in-out",
duration: 300,
opener: function(a) {
return a.is("img") ? a : a.find("img")
}
},
proto: {
initZoom: function() {
var a = n.st.zoom,
d = ".zoom";
if (!a.enabled || !n.supportsTransition) return;
var e = a.duration,
f = function(b) {
var c = b.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"),
d = "all " + a.duration / 1e3 + "s " + a.easing,
e = {
position: "fixed",
zIndex: 9999,
left: 0,
top: 0,
"-webkit-backface-visibility": "hidden"
},
f = "transition";
return e["-webkit-" + f] = e["-moz-" + f] = e["-o-" + f] = e[f] = d, c.css(e), c
},
g = function() {
n.content.css("visibility", "visible")
},
h, i;
x("BuildControls" + d, function() {
if (n._allowZoom()) {
clearTimeout(h), n.content.css("visibility", "hidden"), image = n._getItemToZoom();
if (!image) {
g();
return
}
i = f(image), i.css(n._getOffset()), n.wrap.append(i), h = setTimeout(function() {
i.css(n._getOffset(!0)), h = setTimeout(function() {
g(), setTimeout(function() {
i.remove(), image = i = null, z("ZoomAnimationEnded")
}, 16)
}, e)
}, 16)
}
}), x(c + d, function() {
if (n._allowZoom()) {
clearTimeout(h), n.st.removalDelay = e;
if (!image) {
image = n._getItemToZoom();
if (!image) return;
i = f(image)
}
i.css(n._getOffset(!0)), n.wrap.append(i), n.content.css("visibility", "hidden"), setTimeout(function() {
i.css(n._getOffset())
}, 16)
}
}), x(b + d, function() {
n._allowZoom() && (g(), i && i.remove())
})
},
_allowZoom: function() {
return n.currItem.type === "image"
},
_getItemToZoom: function() {
return n.currItem.hasSize ? n.currItem.img : !1
},
_getOffset: function(b) {
var c;
b ? c = n.currItem.img : c = n.st.zoom.opener(n.currItem.el || n.currItem);
var d = c.offset(),
e = parseInt(c.css("padding-top"), 10),
f = parseInt(c.css("padding-bottom"), 10);
d.top -= a(window).scrollTop() - e;
var g = {
width: c.width(),
height: (p ? c.innerHeight() : c[0].offsetHeight) - f - e
};
return Q() ? g["-moz-transform"] = g.transform = "translate(" + d.left + "px," + d.top + "px)" : (g.left = d.left, g.top = d.top), g
}
}
});
Here is the portion I tried to edit, both with permalink and %url%, with and without quotations.
a.magnificPopup.registerModule("image", {
options: {
markup: '<div class="mfp-figure"><div class="mfp-close"></div><div class="mfp-img"></div><div class="mfp-bottom-bar"><div class="mfp-title"></div><div class="mfp-counter"></div></div></div>',
cursor: "mfp-zoom-out-cur",
titleSrc: "title",
verticalFit: !0,
tError: 'The image could not be loaded.'
},
!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));
Before I get into details, please take a look at the live example where this problem occurs - http://jsfiddle.net/66HFU/ (Script code at the bottom of this post)
Now if you would click on any image at last row, it would display these. However if you would click on upper row images, below row images are shown.
Further investigation shows that for somewhat reason the letter called function selector elements only get binded with event listener while the firstly called functions selector elements do not.
So, I would like to know is there are any ways to make the function call independent so the latter function call does not override first one (if that would fix the problem, of-course)?
The place where the event function gets bind on the element can be found in function f_AddEvents first lines.
And the the main function calls that are used to initialize Light Box is at the bottom of the code like this:
LightBox.init({
selector: "[data-simplbox='demo1']",
boxId: "simplbox"
});
LightBox.init({
selector: "[data-simplbox='demo2']",
boxId: "simplbox",
imageLoadStart: activityIndicatorOn,
imageLoadEnd: activityIndicatorOff
});
All code:
;(function (window, document, undefined) {
var docElem = document.documentElement;
var DomM = (function() {
var f_ToDOMStyle = function (p_Style) {
return p_Style.replace(/\-[a-z]/g, function (p_Style) {
return p_Style.charAt(1).toUpperCase();
});
};
return {
event: {
set: function (p_Element, p_Events, p_Function) {
var i = 0,
j = 0;
p_Events = p_Events.split(" ");
if (!p_Element.length) {
for (i = 0; i < p_Events.length; i++) {
p_Element.addEventListener(p_Events[i], p_Function, false);
}
} else {
for (i = 0; i < p_Element.length; i++) {
for (j = 0; j < p_Events.length; j++) {
p_Element[i].addEventListener(p_Events[j], p_Function, false);
}
}
}
}
},
css: {
set: function (p_Element, p_Style) {
var j;
if (!p_Element.length) {
for (j in p_Style) {
if (p_Style.hasOwnProperty(j)) {
j = f_ToDOMStyle(j);
p_Element.style[j] = p_Style[j];
}
}
} else {
for (var i = 0; i < p_Element.length; i++) {
for (j in p_Style) {
if (p_Style.hasOwnProperty(j)) {
j = f_ToDOMStyle(j);
p_Element[i].style[j] = p_Style[j];
}
}
}
}
}
}
};
}());
var _LightBox = {
f_MergeObjects: function (p_Original, p_Updates) {
for (var i in p_Updates) {
if (p_Updates.hasOwnProperty(i)) {
p_Original[i] = p_Updates[i];
}
}
return p_Original;
},
f_isFunction: function (p_Function) {
return !!(p_Function && p_Function.constructor && p_Function.call && p_Function.apply);
},
f_Initialize: function (p_Options) {
var base = this;
base.m_Options = base.f_MergeObjects(_LightBox.options, p_Options || {});
base.m_Elements = document.querySelectorAll(base.m_Options.selector);
base.m_ElementsLength = base.m_Elements.length - 1;
base.m_Body = document.getElementsByTagName("body")[0];
base.m_CurrentImageElement = false;
base.m_CurrentImageNumber = 0;
base.m_Direction = 1;
base.m_InProgress = false;
base.m_InstalledImageBox = false;
console.log(base.m_Elements);
// Check if hardware acceleration is supported and check if touch is enabled.
base.f_CheckBrowser();
// Adds events.
base.f_AddEvents();
},
f_CheckBrowser: function () {
var base = this,
isTouch = "ontouchstart" in window || window.navigator.msMaxTouchPoints || navigator.maxTouchPoints || false,
vendors = ["ms", "O", "Moz", "Webkit", "Khtml"],
rootStyle = docElem.style,
hardwareAccelerated = false;
if ("transform" in rootStyle) {
hardwareAccelerated = true;
} else {
while (vendors.length) {
if (vendors.pop() + "Transform" in rootStyle) {
hardwareAccelerated = true;
}
}
}
base.browser = {
"isHardwareAccelerated": hardwareAccelerated,
"isTouch": isTouch
};
},
f_AddEvents: function () {
var base = this;
// Add open image event on images.
for (var i = 0; i < base.m_Elements.length; i++) {
(function (i) {
base.m_Elements[i].addEventListener("click", function (event) {
event.preventDefault();
console.log(base.m_Elements[i]);
if (base.f_isFunction(base.m_Options.onImageStart)) {
base.m_Options.onImageStart();
}
base.f_OpenImage(i);
}, false);
})(i);
}
// Resize event for window.
window.addEventListener("resize", function (event) {
event.preventDefault();
base.f_SetImage();
}, false);
// Add keyboard support.
if (base.m_Options.enableKeyboard) {
var keyBoard = {
left: 37,
right: 39,
esc: 27
};
window.addEventListener("keydown", function (event) {
event.preventDefault();
if (base.m_CurrentImageElement) {
if (base.m_InProgress) {
return false;
}
switch (event.keyCode) {
case keyBoard.left:
// If the previous one is out of target range then go to the last image.
if ((base.m_CurrentImageNumber - 1) < 0) {
base.f_OpenImage(base.m_ElementsLength, "left");
} else {
base.f_OpenImage(base.m_CurrentImageNumber - 1, "left");
}
return false;
case keyBoard.right:
// If the next one is out of target range then go to the first image.
if ((base.m_CurrentImageNumber + 1) > base.m_ElementsLength) {
base.f_OpenImage(0, "right");
} else {
base.f_OpenImage(base.m_CurrentImageNumber + 1, "right");
}
return false;
case keyBoard.esc:
base.f_QuitImage();
return false;
}
}
return false;
}, false);
}
// Add document click event.
if (base.m_Options.quitOnDocumentClick) {
document.body.addEventListener("click", function (event) {
var target = event.target ? event.target : event.srcElement;
event.preventDefault();
if (target && target.id != "imagelightbox" && base.m_CurrentImageElement && !base.m_InProgress && base.m_InstalledImageBox) {
base.f_QuitImage();
return false;
}
return false;
}, false);
}
},
f_OpenImage: function (p_WhichOne, p_Direction) {
var base = this,
newFragment = document.createDocumentFragment(),
newImageElement = document.createElement("img"),
target = base.m_Elements[p_WhichOne].getAttribute("href");
if (base.m_CurrentImageElement) {
base.f_RemoveImage();
}
if (base.f_isFunction(base.m_Options.imageLoadStart)) {
base.m_Options.imageLoadStart();
}
base.m_InProgress = true;
base.m_InstalledImageBox = false;
base.m_Direction = typeof p_Direction === "undefined" ? 1 : p_Direction == "left" ? -1 : 1;
newImageElement.setAttribute("src", target);
newImageElement.setAttribute("alt", "LightBox");
newImageElement.setAttribute("id", base.m_Options.boxId);
newFragment.appendChild(newImageElement);
base.m_Body.appendChild(newFragment);
base.m_CurrentImageElement = document.getElementById(base.m_Options.boxId);
base.m_CurrentImageElement.style.opacity = "0";
base.m_CurrentImageNumber = p_WhichOne;
if (base.m_Options.quitOnImageClick) {
base.f_ImageClickEvent = function (event) {
event.preventDefault();
base.f_QuitImage();
};
base.m_CurrentImageElement.addEventListener("click", base.f_ImageClickEvent, false);
}
if (base.browser.isHardwareAccelerated) {
DomM.css.set(base.m_CurrentImageElement, base.f_AddTransitionSpeed(base.m_Options.animationSpeed));
}
base.f_SetImage();
DomM.css.set(base.m_CurrentImageElement, base.f_doTranslateX(50 * base.m_Direction + "px"));
setTimeout(function () {
if (base.browser.isHardwareAccelerated) {
setTimeout(function () {
DomM.css.set(base.m_CurrentImageElement, base.f_doTranslateX("0px"));
}, 50);
}
if (base.f_isFunction(base.m_Options.imageLoadEnd)) {
base.m_Options.imageLoadEnd();
}
}, 20);
setTimeout(function () {
base.m_InProgress = false;
base.m_InstalledImageBox = true;
}, base.m_Options.animationSpeed - 200);
},
f_SetImage: function () {
var base = this,
screenHeight = window.innerHeight || docElem.offsetHeight,
screenWidth = window.innerWidth || docElem.offsetWidth,
tmpImage = new Image(),
imageWidth, imageHeight, imageSizeRatio;
if (!base.m_CurrentImageElement) {
return;
}
tmpImage.onload = function () {
imageWidth = this.width;
imageHeight = this.height;
imageSizeRatio = imageWidth / imageHeight;
if (Math.floor(screenWidth/imageSizeRatio) > screenHeight) {
imageWidth = screenHeight * imageSizeRatio * 0.7;
imageHeight = screenHeight * 0.7;
} else {
imageWidth = screenWidth * 0.7;
imageHeight = screenWidth / imageSizeRatio * 0.7;
}
DomM.css.set(base.m_CurrentImageElement, {
"top": ((screenHeight - imageHeight) / 2) + "px",
"left": ((screenWidth - imageWidth) / 2) + "px",
"width": Math.floor(imageWidth) + "px",
"height": Math.floor(imageHeight) + "px",
"opacity": 1
});
};
tmpImage.src = base.m_CurrentImageElement.getAttribute("src");
},
f_RemoveImage: function () {
var base = this;
if (base.m_CurrentImageElement) {
if (base.f_isFunction(base.m_Options.quitOnImageClick)) {
base.m_CurrentImageElement.removeEventListener("click", base.f_ImageClickEvent, false);
}
base.m_CurrentImageElement.parentNode.removeChild(base.m_CurrentImageElement);
base.m_CurrentImageElement = false;
}
return false;
},
f_QuitImage: function () {
var base = this;
if (base.m_CurrentImageElement) {
setTimeout(function () {
DomM.css.set(base.m_CurrentImageElement, {
"opacity": 0,
"transition": ("opacity " + base.m_Options.fadeOutSpeed + "ms ease")
});
setTimeout(function () {
base.f_RemoveImage();
if (base.f_isFunction(base.m_Options.onImageQuit)) {
base.m_Options.onImageQuit();
}
}, base.m_Options.fadeOutSpeed);
}, 20);
}
},
f_IsValidSource: function (p_Src) {
return new RegExp().test(p_Src);
},
f_doTranslateX: function (p_Pixels) {
return {
"-webkit-transform": "translateX(" + p_Pixels + ")",
"-moz-transform": "translateX(" + p_Pixels + ")",
"-o-transform": "translateX(" + p_Pixels + ")",
"-ms-transform": "translateX(" + p_Pixels + ")",
"transform": "translateX(" + p_Pixels + ")"
};
},
f_AddTransitionSpeed: function (p_Speed) {
var base = this;
return {
"-webkit-transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease",
"-moz-transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease",
"-o-transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease",
"transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease"
};
}
};
_LightBox.options = {
selector: "[data-imagelightbox]",
boxId: "imagelightbox",
allowedTypes: "png|jpg|jpeg|gif",
quitOnImageClick: true,
quitOnDocumentClick: true,
enableKeyboard: true,
animationSpeed: 750,
fadeInSpeed: 500,
fadeOutSpeed: 200,
imageLoadStart: function () {},
imageLoadEnd: function () {},
onImageQuit: function () {},
onImageStart: function () {}
};
LightBox.init = function (p_Options) {
_LightBox.f_Initialize(p_Options);
};
})(window, document, window.LightBox = window.LightBox || {});
var activityIndicatorOn = function () {
var newE = document.createElement("div"),
newB = document.createElement("div");
newE.setAttribute("id", "imagelightbox-loading");
newE.appendChild(newB);
document.body.appendChild(newE);
},
activityIndicatorOff = function () {
var elE = document.getElementById("imagelightbox-loading");
elE.parentNode.removeChild(elE);
};
LightBox.init({
selector: "[data-simplbox='demo1']",
boxId: "simplbox"
});
LightBox.init({
selector: "[data-simplbox='demo2']",
boxId: "simplbox",
imageLoadStart: activityIndicatorOn,
imageLoadEnd: activityIndicatorOff
});
Your code is almost working. What you handled badly is the fact that you can perform several init. On each init, you overwrite some items, especially with this line :
base.m_Elements = document.querySelectorAll(base.m_Options.selector);
So base.m_Elements will only have the elements of the last init.
( Based on the name 'init' i wonder if the real use case wouldn't be to allow just one call of init... )
Quick-fix is to do one single init with :
LightBox.init({
selector: "[data-simplbox='demo1'],[data-simplbox='demo2']",
boxId: "simplbox"
});
(erase the two calls to init)
And here it works.
http://jsfiddle.net/gamealchemist/66HFU/1/
So i guess either you want to support several init, or (easier to maintain in fact), throw exception on multiple init and expect the lib user to write the right selector in the single init call.
Edit : Super quick fix for your issue : rather than having LightBox as a singleton, have it as a Class :
function LightBox( initArguments ) {
// something like what was done in init
}
LightBox.prototype = {
f_RemoveImage : function() {
} ,
f_OpenImage : function( ..., ... ) {
} ,
...
}
then you can call with no issue :
var demo1LB = new LightBox({ selector: "[data-simplbox='demo1']",
boxId: "simplbox" });
var demo2LB = new LightBox({ selector: "[data-simplbox='demo2']",
boxId: "simplbox" });
I'm trying to implement an infinite scroll in a div with filtering option, as well, filtering should work when user stops typing in the box.
Html:
<div class="span2" style="margin-top: 50px;">
<input id="Search" class="input-mysize" />
<div id="listNav" style="height: 370px; border: 1px solid; overflow: auto; margin-right: 20px; width: 90%;">
</div>
</div>
JS in Html:
$(function() {
function onSuccess(row, container) {
container.append('<div style="border:1px solid; cursor: hand; cursor: pointer;" >' +
'<table border="0">' +
'<tr>' +
'<td id="Location' + row.Id + '">'+
'<b>Name: </b>' + row.Name + '</br >' + '<b>Address: </b>' + row.Address + '' +
'</td>' +
'<td onclick="locationDetails(' + row.Id + ')"> > </td>' +
'</tr>' +
'</table>' +
'</div>');
var tdId = "Location" + row.Id;
var element = $('#' + tdId);
$(element).click(function() {
google.maps.event.trigger(arrMarkers[row.Id], 'click');
});
};
//...
$('#listNav').empty();
$('#listNav').jScroller("/Dashboard/GetClients", {
numberOfRowsToRetrieve: 7,
onSuccessCallback: onSuccess,
onErrorCallback: function () {
alert("error");
}
});
//...
$('#Search').keyup(function(){
clearTimeout(typingTimer);
if ($('#myInput').val) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
function doneTyping () {
startInt = startInt + 5;
$('#listNav').empty();
$('#listNav').unbind();
$('#listNav').jScroller("/Dashboard/GetClients", {
numberOfRowsToRetrieve: 7,
start : startInt,
locationFilter: $('#Search').val(),
onSuccessCallback: onSuccess,
onErrorCallback: function () {
alert("error");
}
});
};
});
rest of JS (based on jScroller plug in):
(function ($) {
"use strict";
jQuery.fn.jScroller = function (store, parameters) {
var defaults = {
numberOfRowsToRetrieve: 10,
locationFilter: '',
onSuccessCallback: function (row, container) { },
onErrorCallback: function (thrownError) { window.alert('An error occurred while trying to retrive data from store'); },
onTimeOutCallback: function () { },
timeOut: 3 * 1000,
autoIncreaseTimeOut: 1000,
retryOnTimeOut: false,
loadingButtonText: 'Loading...',
loadMoreButtonText: 'Load more',
fullListText: 'There is no more items to show',
extraParams: null
};
var options = jQuery.extend(defaults, parameters);
var list = jQuery(this),
end = false,
loadingByScroll = true;
var ajaxParameters;
if (options.extraParams === null) {
ajaxParameters = {
start: 0,
numberOfRowsToRetrieve: options.numberOfRowsToRetrieve,
locationFilter: options.locationFilter
};
}
else {
ajaxParameters = {
start: 0,
numberOfRowsToRetrieve: options.numberOfRowsToRetrieve,
locationFilter: option.locationFilter,
extraParams: options.extraParams
};
}
list.html('');
function loadItems() {
preLoad();
jQuery.ajax({
url: store,
type: "POST",
data: ajaxParameters,
timeOut: options.timeOut,
success: function (response) {
list.find("#jscroll-loading").remove();
if (response.Success === false) {
options.onErrorCallback(list, response.Message);
return;
}
for (var i = 0; i < response.data.length; i++) {
if (end === false) {
options.onSuccessCallback(response.data[i], list);
}
}
if (loadingByScroll === false) {
if (end === false) {
list.append('<div><a class="jscroll-loadmore">' + options.loadMoreButtonText + '</a></div>');
}
}
ajaxParameters.start = ajaxParameters.start + options.numberOfRowsToRetrieve;
if (ajaxParameters.start >= response.total) {
end = true;
list.find('#jscroll-fulllist').remove();
list.find(".jscroll-loadmore").parent("div").remove();
}
},
error: function (xhr, ajaxOptions, thrownError) {
if (thrownError === 'timeout') {
options.onTimeOutCallback();
if (options.retryOnTimeOut) {
options.timeOut = options.timeOut + (1 * options.autoIncreaseTimeOut);
loadItems();
}
}
else {
options.onErrorCallback(thrownError);
}
}
});
}
function preLoad() {
if (list.find("#jscroll-loading").length === 0) {
list.find(".jscroll-loadmore").parent("div").remove();
list.append('<a id="jscroll-loading">' + options.loadingButtonText + '</a>');
}
}
//called when doneTyping is called and first time page loaded
jQuery(document).ready(function () {
loadItems();
});
//called when user scrolls down in a div
$('#listNav').bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
loadItems();
}
});
};
})(jQuery);
It's mostly working, but at some cases when user stops typing, the
jQuery(document).ready(function () {
loadItems();
});
and
$('#listNav').bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
loadItems();
}
});
are both called instead of just first one, adding bad html to the div. Most cases only jQuery(document).ready is called, which is what i need.
As well why is jQuery(document).ready() is called every time the doneTyping() is called ? I though it should be called only the first time the page is loaded after DOM is ready.
I assume that your JS code in your HTML starts with a $(document).ready({}), so there would be no need to add $(document).ready({}) inside your plugin. Just call loadItems(); without the document ready event.