I wanted to use this kind of Photo Collage on my Website: Seamless Photo Collage by AutomaticImageMontage
so I downloaded it and pasted the code to my Website..
it works but sometimes when the page loads the white background goes transparent on the whole page transperent background
I'm using Parallax and Bootstrap, sometimes the parallax isn't working properly too.
I have tried to set the background to white in CSS but nothing.. sometimes it loads normally but sometimes goes transparent,
I have checked the console too but it showes only
jquery.montage.min.js:1 Uncaught TypeError: Cannot read property 'apply' of undefined
now i really dont have any idea how to fix it.
please help :(
Javascript CSS and HTML
(function(window, $, undefined) {
Array.max = function(array) {
return Math.max.apply(Math, array)
};
Array.min = function(array) {
return Math.min.apply(Math, array)
};
var $event = $.event,
resizeTimeout;
$event.special.smartresize = {
setup: function() {
$(this).bind("resize", $event.special.smartresize.handler)
},
teardown: function() {
$(this).unbind("resize", $event.special.smartresize.handler)
},
handler: function(event, execAsap) {
var context = this,
args = arguments;
event.type = "smartresize";
if (resizeTimeout) {
clearTimeout(resizeTimeout)
}
resizeTimeout = setTimeout(function() {
jQuery.event.handle.apply(context, args)
}, execAsap === "execAsap" ? 0 : 50)
}
};
$.fn.smartresize = function(fn) {
return fn ? this.bind("smartresize", fn) : this.trigger("smartresize", ["execAsap"])
};
$.fn.imagesLoaded = function(callback) {
var $images = this.find('img'),
len = $images.length,
_this = this,
blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
function triggerCallback() {
callback.call(_this, $images)
}
function imgLoaded() {
if (--len <= 0 && this.src !== blank) {
setTimeout(triggerCallback);
$images.unbind('load error', imgLoaded)
}
}
if (!len) {
triggerCallback()
}
$images.bind('load error', imgLoaded).each(function() {
if (this.complete || this.complete === undefined) {
var src = this.src;
this.src = blank;
this.src = src
}
});
return this
};
$.Montage = function(options, element) {
this.element = $(element).show();
this.cache = {};
this.heights = new Array();
this._create(options)
};
$.Montage.defaults = {
liquid: true,
margin: 1,
minw: 70,
minh: 20,
maxh: 250,
alternateHeight: false,
alternateHeightRange: {
min: 100,
max: 300
},
fixedHeight: null,
minsize: false,
fillLastRow: false
};
$.Montage.prototype = {
_getImageWidth: function($img, h) {
var i_w = $img.width(),
i_h = $img.height(),
r_i = i_h / i_w;
return Math.ceil(h / r_i)
},
_getImageHeight: function($img, w) {
var i_w = $img.width(),
i_h = $img.height(),
r_i = i_h / i_w;
return Math.ceil(r_i * w)
},
_chooseHeight: function() {
if (this.options.minsize) {
return Array.min(this.heights)
}
var result = {},
max = 0,
res, val, min;
for (var i = 0, total = this.heights.length; i < total; ++i) {
var val = this.heights[i],
inc = (result[val] || 0) + 1;
if (val < this.options.minh || val > this.options.maxh) continue;
result[val] = inc;
if (inc >= max) {
max = inc;
res = val
}
}
for (var i in result) {
if (result[i] === max) {
val = i;
min = min || val;
if (min < this.options.minh) min = null;
else if (min > val) min = val;
if (min === null) min = val
}
}
if (min === undefined) min = this.heights[0];
res = min;
return res
},
_stretchImage: function($img) {
var prevWrapper_w = $img.parent().width(),
new_w = prevWrapper_w + this.cache.space_w_left,
crop = {
x: new_w,
y: this.theHeight
};
var new_image_w = $img.width() + this.cache.space_w_left,
new_image_h = this._getImageHeight($img, new_image_w);
this._cropImage($img, new_image_w, new_image_h, crop);
this.cache.space_w_left = this.cache.container_w;
if (this.options.alternateHeight) this.theHeight = Math.floor(Math.random() * (this.options.alternateHeightRange.max - this.options.alternateHeightRange.min + 1) + this.options.alternateHeightRange.min)
},
_updatePrevImage: function($nextimg) {
var $prevImage = this.element.find('img.montage:last');
this._stretchImage($prevImage);
this._insertImage($nextimg)
},
_insertImage: function($img) {
var new_w = this._getImageWidth($img, this.theHeight);
if (this.options.minsize && !this.options.alternateHeight) {
if (this.cache.space_w_left <= this.options.margin * 2) {
this._updatePrevImage($img)
} else {
if (new_w > this.cache.space_w_left) {
var crop = {
x: this.cache.space_w_left,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left = this.cache.container_w;
$img.addClass('montage')
} else {
var crop = {
x: new_w,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left -= new_w;
$img.addClass('montage')
}
}
} else {
if (new_w < this.options.minw) {
if (this.options.minw > this.cache.space_w_left) {
this._updatePrevImage($img)
} else {
var new_w = this.options.minw,
new_h = this._getImageHeight($img, new_w),
crop = {
x: new_w,
y: this.theHeight
};
this._cropImage($img, new_w, new_h, crop);
this.cache.space_w_left -= new_w;
$img.addClass('montage')
}
} else {
if (new_w > this.cache.space_w_left && this.cache.space_w_left < this.options.minw) {
this._updatePrevImage($img)
} else if (new_w > this.cache.space_w_left && this.cache.space_w_left >= this.options.minw) {
var crop = {
x: this.cache.space_w_left,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left = this.cache.container_w;
if (this.options.alternateHeight) this.theHeight = Math.floor(Math.random() * (this.options.alternateHeightRange.max - this.options.alternateHeightRange.min + 1) + this.options.alternateHeightRange.min);
$img.addClass('montage')
} else {
var crop = {
x: new_w,
y: this.theHeight
};
this._cropImage($img, new_w, this.theHeight, crop);
this.cache.space_w_left -= new_w;
$img.addClass('montage')
}
}
}
},
_cropImage: function($img, w, h, cropParam) {
var dec = this.options.margin * 2;
var $wrapper = $img.parent('a');
this._resizeImage($img, w, h);
$img.css({
left: -(w - cropParam.x) / 2 + 'px',
top: -(h - cropParam.y) / 2 + 'px'
});
$wrapper.addClass('am-wrapper').css({
width: cropParam.x - dec + 'px',
height: cropParam.y + 'px',
margin: this.options.margin
})
},
_resizeImage: function($img, w, h) {
$img.css({
width: w + 'px',
height: h + 'px'
})
},
_reload: function() {
var new_el_w = this.element.width();
if (new_el_w !== this.cache.container_w) {
this.element.hide();
this.cache.container_w = new_el_w;
this.cache.space_w_left = new_el_w;
var instance = this;
instance.$imgs.removeClass('montage').each(function(i) {
instance._insertImage($(this))
});
if (instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w) {
instance._stretchImage(instance.$imgs.eq(instance.totalImages - 1))
}
instance.element.show()
}
},
_create: function(options) {
this.options = $.extend(true, {}, $.Montage.defaults, options);
var instance = this,
el_w = instance.element.width();
instance.$imgs = instance.element.find('img');
instance.totalImages = instance.$imgs.length;
if (instance.options.liquid) $('html').css('overflow-y', 'scroll');
if (!instance.options.fixedHeight) {
instance.$imgs.each(function(i) {
var $img = $(this),
img_w = $img.width();
if (img_w < instance.options.minw && !instance.options.minsize) {
var new_h = instance._getImageHeight($img, instance.options.minw);
instance.heights.push(new_h)
} else {
instance.heights.push($img.height())
}
})
}
instance.theHeight = (!instance.options.fixedHeight && !instance.options.alternateHeight) ? instance._chooseHeight() : instance.options.fixedHeight;
if (instance.options.alternateHeight) instance.theHeight = Math.floor(Math.random() * (instance.options.alternateHeightRange.max - instance.options.alternateHeightRange.min + 1) + instance.options.alternateHeightRange.min);
instance.cache.container_w = el_w;
instance.cache.space_w_left = el_w;
instance.$imgs.each(function(i) {
instance._insertImage($(this))
});
if (instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w) {
instance._stretchImage(instance.$imgs.eq(instance.totalImages - 1))
}
$(window).bind('smartresize.montage', function() {
instance._reload()
})
},
add: function($images, callback) {
var $images_stripped = $images.find('img');
this.$imgs = this.$imgs.add($images_stripped);
this.totalImages = this.$imgs.length;
this._add($images, callback)
},
_add: function($images, callback) {
var instance = this;
$images.find('img').each(function(i) {
instance._insertImage($(this))
});
if (instance.options.fillLastRow && instance.cache.space_w_left !== instance.cache.container_w) instance._stretchImage(instance.$imgs.eq(instance.totalImages - 1));
if (callback) callback.call($images)
},
destroy: function(callback) {
this._destroy(callback)
},
_destroy: function(callback) {
this.$imgs.removeClass('montage').css({
position: '',
width: '',
height: '',
left: '',
top: ''
}).unwrap();
if (this.options.liquid) $('html').css('overflow', '');
this.element.unbind('.montage').removeData('montage');
$(window).unbind('.montage');
if (callback) callback.call()
},
option: function(key, value) {
if ($.isPlainObject(key)) {
this.options = $.extend(true, this.options, key)
}
}
};
var logError = function(message) {
if (this.console) {
console.error(message)
}
};
$.fn.montage = function(options) {
if (typeof options === 'string') {
var args = Array.prototype.slice.call(arguments, 1);
this.each(function() {
var instance = $.data(this, 'montage');
if (!instance) {
logError("cannot call methods on montage prior to initialization; " + "attempted to call method '" + options + "'");
return
}
if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
logError("no such method '" + options + "' for montage instance");
return
}
instance[options].apply(instance, args)
})
} else {
this.each(function() {
var instance = $.data(this, 'montage');
if (instance) {
instance.option(options || {});
instance._reload()
} else {
$.data(this, 'montage', new $.Montage(options, this))
}
})
}
return this
}
})(window, jQuery);
.am-wrapper{
float:left;
position:relative;
overflow:hidden;
}
.am-wrapper img{
position:absolute;
outline:none;
}
<div class="container">
<div id="am-container" class="am-container"><img src="images/1.jpg"><img src="images/2.jpg"><img src="images/3.jpg"><img src="images/4.jpg"><img src="images/5.jpg"><img src="images/6.jpg"><img src="images/7.jpg"><img src="images/8.jpg"><img src="images/9.jpg"><img src="images/10.jpg"><img src="images/11.jpg"><img src="images/12.jpg"><img src="images/13.jpg"><img src="images/14.jpg"><img src="images/15.jpg"><img src="images/16.jpg"><img src="images/17.jpg"><img src="images/18.jpg"><img src="images/19.jpg">
</div>
</div>
<script type="text/javascript">
$(function() {
var $container = $('#am-container'),
$imgs = $container.find('img').hide(),
totalImgs = $imgs.length,
cnt = 0;
$imgs.each(function(i) {
var $img = $(this);
$('<img/>').load(function() {
++cnt;
if( cnt === totalImgs ) {
$imgs.show();
$container.montage({
fillLastRow : false,
alternateHeight : false,
alternateHeightRange : {
min : 90,
max : 100
}
});
}
}).attr('src',$img.attr('src'));
});
});
</script>
Related
I'm trying to crop image using jquery cropping box . Cropbox
This is working fine with Large squre image but not working fine with ing to small and rectangle img. I am trying to modify the library.
KINDLY REVIEW ON THE LINE NO 230 . js-cropbox.js
(function() {
// helper functions
function is_touch_device() {
return 'ontouchstart' in window || // works on most browsers
'onmsgesturechange' in window; // works on ie10
}
function fill(value, target, container) {
if (value + target < container)
value = container - target;
return value > 0 ? 0 : value;
}
function uri2blob(dataURI) {
var uriComponents = dataURI.split(',');
var byteString = atob(uriComponents[1]);
var mimeString = uriComponents[0].split(':')[1].split(';')[0];
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++)
ia[i] = byteString.charCodeAt(i);
return new Blob([ab], { type: mimeString });
}
var pluginName = 'cropbox';
function factory($) {
function Crop($image, options) {
this.width = null;
this.height = null;
this.img_width = null;
this.img_height = null;
this.img_left = 0;
this.img_top = 0;
this.minPercent = null;
this.options = options;
this.$image = $image;
this.$image.hide().prop('draggable', false).addClass('cropImage').wrap('<div class="cropFrame" />'); // wrap image in frame;
this.$frame = this.$image.parent();
this.init();
}
Crop.prototype = {
init: function () {
var self = this;
var defaultControls = $('<div/>', { 'class' : 'cropControls' })
.append($('<span>Drag to crop</span>'))
.append($('<a/>', { 'class' : 'cropZoomIn' }).on('click', $.proxy(this.zoomIn, this)))
.append($('<a/>', { 'class' : 'cropZoomOut' }).on('click', $.proxy(this.zoomOut, this)));
this.$frame.append(this.options.controls || defaultControls);
this.updateOptions();
if (typeof $.fn.hammer === 'function' || typeof Hammer !== 'undefined') {
var hammerit, dragData;
if (typeof $.fn.hammer === 'function')
hammerit = this.$image.hammer();
else
hammerit = Hammer(this.$image.get(0));
hammerit.on('touch', function(e) {
e.gesture.preventDefault();
}).on("dragleft dragright dragup dragdown", function(e) {
if (!dragData)
dragData = {
startX: self.img_left,
startY: self.img_top,
};
dragData.dx = e.gesture.deltaX;
dragData.dy = e.gesture.deltaY;
e.gesture.preventDefault();
e.gesture.stopPropagation();
self.drag.call(self, dragData, true);
}).on('release', function(e) {
e.gesture.preventDefault();
dragData = null;
self.update.call(self);
}).on('doubletap', function(e) {
e.gesture.preventDefault();
self.zoomIn.call(self);
}).on('pinchin', function (e) {
e.gesture.preventDefault();
self.zoomOut.call(self);
}).on('pinchout', function (e) {
e.gesture.preventDefault();
self.zoomIn.call(self);
});
} else {
this.$image.on('mousedown.' + pluginName, function(e1) {
var dragData = {
startX: self.img_left,
startY: self.img_top,
};
e1.preventDefault();
$(document).on('mousemove.' + pluginName, function (e2) {
dragData.dx = e2.pageX - e1.pageX;
dragData.dy = e2.pageY - e1.pageY;
self.drag.call(self, dragData, true);
}).on('mouseup.' + pluginName, function() {
self.update.call(self);
$(document).off('mouseup.' + pluginName);
$(document).off('mousemove.' + pluginName);
});
});
}
if ($.fn.mousewheel) {
this.$image.on('mousewheel.' + pluginName, function (e) {
e.preventDefault();
if (e.deltaY < 0)
self.zoomIn.call(self);
else
self.zoomOut.call(self);
});
}
},
updateOptions: function () {
var self = this;
self.img_top = 0;
self.img_left = 0;
self.$image.css({width: '', left: self.img_left, top: self.img_top});
self.$frame.width(self.options.width).height(self.options.height);
self.$frame.off('.' + pluginName);
self.$frame.removeClass('hover');
if (self.options.showControls === 'always' || self.options.showControls === 'auto' && is_touch_device())
self.$frame.addClass('hover');
else if (self.options.showControls !== 'never') {
self.$frame.on('mouseenter.' + pluginName, function () { self.$frame.addClass('hover'); });
self.$frame.on('mouseleave.' + pluginName, function () { self.$frame.removeClass('hover'); });
}
// Image hack to get width and height on IE
var img = new Image();
img.src = self.$image.attr('src');
img.onload = function () {
self.width = img.width;
self.height = img.height;
img.src = '';
img.onload = null;
self.percent = undefined;
self.fit.call(self);
if (self.options.result)
self.setCrop.call(self, self.options.result);
else
self.zoom.call(self, self.minPercent);
self.$image.fadeIn('fast');
};
},
remove: function () {
var hammerit;
if (typeof $.fn.hammer === 'function')
hammerit = this.$image.hammer();
else if (typeof Hammer !== 'undefined')
hammerit = Hammer(this.$image.get(0));
if (hammerit)
hammerit.off('mousedown dragleft dragright dragup dragdown release doubletap pinchin pinchout');
this.$frame.off('.' + pluginName);
this.$image.off('.' + pluginName);
this.$image.css({width: '', left: '', top: ''});
this.$image.removeClass('cropImage');
this.$image.removeData('cropbox');
this.$image.insertAfter(this.$frame);
this.$frame.removeClass('cropFrame');
this.$frame.removeAttr('style');
this.$frame.empty();
this.$frame.hide();
},
fit: function () {
var widthRatio = this.options.width / this.width,
heightRatio = this.options.height / this.height;
this.minPercent = (widthRatio >= heightRatio) ? widthRatio : heightRatio;
},
setCrop: function (result) {
this.percent = Math.max(this.options.width/result.cropW, this.options.height/result.cropH);
this.img_width = Math.ceil(this.width*this.percent);
this.img_height = Math.ceil(this.height*this.percent);
this.img_left = -Math.floor(result.cropX*this.percent);
this.img_top = -Math.floor(result.cropY*this.percent);
this.$image.css({ width: this.img_width, left: this.img_left, top: this.img_top });
this.update();
},
zoom: function(percent) {
var old_percent = this.percent;
this.percent = Math.max(this.minPercent, Math.min(this.options.maxZoom, percent));
this.img_width = Math.ceil(this.width * this.percent);
this.img_height = Math.ceil(this.height * this.percent);
if (old_percent) {
var zoomFactor = this.percent / old_percent;
this.img_left = fill((1 - zoomFactor) * this.options.width / 2 + zoomFactor * this.img_left, this.img_width, this.options.width);
this.img_top = fill((1 - zoomFactor) * this.options.height / 2 + zoomFactor * this.img_top, this.img_height, this.options.height);
} else {
this.img_left = fill((this.options.width - this.img_width) / 2, this.img_width, this.options.width);
this.img_top = fill((this.options.height - this.img_height) / 2, this.img_height, this.options.height);
}
this.$image.css({ width: this.img_width, left: this.img_left, top: this.img_top });
this.update();
},
zoomIn: function() {
this.zoom(this.percent + (1 - this.minPercent) / (this.options.zoom - 1 || 1));
},
zoomOut: function() {
this.zoom(this.percent - (1 - this.minPercent) / (this.options.zoom - 1 || 1));
},
drag: function(data, skipupdate) {
this.img_left = fill(data.startX + data.dx, this.img_width, this.options.width);
this.img_top = fill(data.startY + data.dy, this.img_height, this.options.height);
this.$image.css({ left: this.img_left, top: this.img_top });
if (skipupdate)
this.update();
},
update: function() {
this.result = {
cropX: -Math.ceil(this.img_left / this.percent),
cropY: -Math.ceil(this.img_top / this.percent),
cropW: Math.floor(this.options.width / this.percent),
cropH: Math.floor(this.options.height / this.percent),
stretch: this.minPercent > 1
};
this.$image.trigger(pluginName, [this.result, this]);
},
getDataURL: function () {
var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d');
var sourceX = this.result.cropX;
var sourceY = this.result.cropY;
var sourceWidth = this.result.cropW;
var sourceHeight = this.result.cropH;
var destWidth = this.options.width;
var destHeight = this.options.height;
var destX = this.result.cropX;
var destY = this.result.cropX;
console.log(this);
canvas.height=this.result.cropW;
canvas.height=this.result.cropH;
//ctx.drawImage(this.$image.get(0), sourceX, sourceY, sourceWidth, sourceHeight, 0 , 0 , destWidth, destHeight);
ctx.drawImage(this.$image.get(0), this.result.cropX, this.result.cropY, this.result.cropW, this.result.cropH, 0, 0, this.options.width, this.options.height);
return canvas.toDataURL();
},
getBlob: function () {
return uri2blob(this.getDataURL());
},
};
$.fn[pluginName] = function(options) {
return this.each(function() {
var inst = $.data(this, pluginName);
if (!inst) {
var opts = $.extend({}, $.fn[pluginName].defaultOptions, options);
$.data(this, pluginName, new Crop($(this), opts));
} else if (options) {
$.extend(inst.options, options);
inst.updateOptions();
}
});
};
$.fn[pluginName].defaultOptions = {
width: 200,
height: 200,
zoom: 10,
maxZoom: 1,
controls: null,
showControls: 'auto'
};
}
if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
factory(require("jquery"));
else if (typeof define === "function" && define.amd)
define(["jquery"], factory);
else
factory(window.jQuery || window.Zepto);
})();
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.2.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/hammer.js/1.0.5/hammer.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.js"></script>
<script src="jquery.cropbox.js"></script>
<link type="text/css" media="screen" rel="stylesheet" href="http://acornejo.github.io/jquery-cropbox/jquery.cropbox.css">
<script type="text/javascript">
$(function () {
$("#browse").on("change",function(){
var getCropImg=this;
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
function imageIsLoaded(e) {
$('#cropimage').attr('src', e.target.result);
};
$('#cropimage').cropbox({
width: 300,
height: 300
}).on('cropbox', function(e, data,img ) {
var url=img.getDataURL();
$('#preview').attr("src",url);
});
});
</script>
<input type="file" id="browse"></input>
<img id="cropimage" crossorigin="anonymous" alt="" src="http://css375.gaanacdn.com/images/gaana-beta-logo-v2.png" />
<div id="results"></div>
<img id="preview">
I'm trying to load my landing page but it is not loading my .vegas function in my custom.js file. The vegas function is created in the file jquery.vegas.js. This seems to be the problem, so how do I change the order of how the scripts are called within my Rails app in the asset pipeline? Can I change the order of how it is called in the application.js file?
Custom.js file where the .vegas function is being called
(function($){
// Preloader
$(window).load(function() {
$('#status').fadeOut();
$('#preloader').delay(350).fadeOut('slow');
$('body').delay(350).css({'overflow':'visible'});
});
$(document).ready(function() {
// Image background
$.vegas({
src:'assets/images/bg1.jpg'
});
$.vegas('overlay', {
src:'assets/images/06.png'
});
var countdown = $('.countdown-time');
createTimeCicles();
$(window).on('resize', windowSize);
function windowSize(){
countdown.TimeCircles().destroy();
createTimeCicles();
countdown.on('webkitAnimationEnd mozAnimationEnd oAnimationEnd animationEnd', function() {
countdown.removeClass('animated bounceIn');
});
}
Application.js file
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
Jquery.vegas.js file where the vegas function resides(At the very bottom)
(function($) {
var $background = $("<img />").addClass("vegas-background"), $overlay = $("<div />").addClass("vegas-overlay"), $loading = $("<div />").addClass("vegas-loading"), $current = $(), paused = null, backgrounds = [], step = 0, delay = 5e3, walk = function() {}, timer,
methods = {
init: function(settings) {
var options = {
src: getBackground(),
align: "center",
valign: "center",
fade: 0,
loading: true,
load: function() {},
complete: function() {}
};
$.extend(options, $.vegas.defaults.background, settings);
if (options.loading) {
loading();
}
var $new = $background.clone();
$new.css({
position: "fixed",
left: "0px",
top: "0px"
}).bind("load", function() {
if ($new == $current) {
return;
}
$(window).bind("load resize.vegas", function(e) {
resize($new, options);
});
if ($current.is("img")) {
$current.stop();
$new.hide().insertAfter($current).fadeIn(options.fade, function() {
$(".vegas-background").not(this).remove();
$("body").trigger("vegascomplete", [ this, step - 1 ]);
options.complete.apply($new, [ step - 1 ]);
});
} else {
$new.hide().prependTo("body").fadeIn(options.fade, function() {
$("body").trigger("vegascomplete", [ this, step - 1 ]);
options.complete.apply(this, [ step - 1 ]);
});
}
$current = $new;
resize($current, options);
if (options.loading) {
loaded();
}
$("body").trigger("vegasload", [ $current.get(0), step - 1 ]);
options.load.apply($current.get(0), [ step - 1 ]);
if (step) {
$("body").trigger("vegaswalk", [ $current.get(0), step - 1 ]);
options.walk.apply($current.get(0), [ step - 1 ]);
}
}).attr("src", options.src);
return $.vegas;
},
destroy: function(what) {
if (!what || what == "background") {
$(".vegas-background, .vegas-loading").remove();
$(window).unbind("*.vegas");
$current = $();
}
if (!what || what == "overlay") {
$(".vegas-overlay").remove();
}
clearInterval(timer);
return $.vegas;
},
overlay: function(settings) {
var options = {
src: null,
opacity: null
};
$.extend(options, $.vegas.defaults.overlay, settings);
$overlay.remove();
$overlay.css({
margin: "0",
padding: "0",
position: "fixed",
left: "0px",
top: "0px",
width: "100%",
height: "100%"
});
if (options.src === false) {
$overlay.css("backgroundImage", "none");
}
if (options.src) {
$overlay.css("backgroundImage", "url(" + options.src + ")");
}
if (options.opacity) {
$overlay.css("opacity", options.opacity);
}
$overlay.prependTo("body");
return $.vegas;
},
slideshow: function(settings, keepPause) {
var options = {
step: step,
delay: delay,
preload: false,
loading: true,
backgrounds: backgrounds,
walk: walk
};
$.extend(options, $.vegas.defaults.slideshow, settings);
if (options.backgrounds != backgrounds) {
if (!settings.step) {
options.step = 0;
}
if (!settings.walk) {
options.walk = function() {};
}
if (options.preload) {
$.vegas("preload", options.backgrounds);
}
}
backgrounds = options.backgrounds;
delay = options.delay;
step = options.step;
walk = options.walk;
clearInterval(timer);
if (!backgrounds.length) {
return $.vegas;
}
var doSlideshow = function() {
if (step < 0) {
step = backgrounds.length - 1;
}
if (step >= backgrounds.length || !backgrounds[step - 1]) {
step = 0;
}
var settings = backgrounds[step++];
settings.walk = options.walk;
settings.loading = options.loading;
if (typeof settings.fade == "undefined") {
settings.fade = options.fade;
}
if (settings.fade > options.delay) {
settings.fade = options.delay;
}
$.vegas(settings);
};
doSlideshow();
if (!keepPause) {
paused = false;
$("body").trigger("vegasstart", [ $current.get(0), step - 1 ]);
}
if (!paused) {
timer = setInterval(doSlideshow, options.delay);
}
return $.vegas;
},
next: function() {
var from = step;
if (step) {
$.vegas("slideshow", {
step: step
}, true);
$("body").trigger("vegasnext", [ $current.get(0), step - 1, from - 1 ]);
}
return $.vegas;
},
previous: function() {
var from = step;
if (step) {
$.vegas("slideshow", {
step: step - 2
}, true);
$("body").trigger("vegasprevious", [ $current.get(0), step - 1, from - 1 ]);
}
return $.vegas;
},
jump: function(s) {
var from = step;
if (step) {
$.vegas("slideshow", {
step: s
}, true);
$("body").trigger("vegasjump", [ $current.get(0), step - 1, from - 1 ]);
}
return $.vegas;
},
stop: function() {
var from = step;
step = 0;
paused = null;
clearInterval(timer);
$("body").trigger("vegasstop", [ $current.get(0), from - 1 ]);
return $.vegas;
},
pause: function() {
paused = true;
clearInterval(timer);
$("body").trigger("vegaspause", [ $current.get(0), step - 1 ]);
return $.vegas;
},
get: function(what) {
if (what === null || what == "background") {
return $current.get(0);
}
if (what == "overlay") {
return $overlay.get(0);
}
if (what == "step") {
return step - 1;
}
if (what == "paused") {
return paused;
}
},
preload: function(backgrounds) {
var cache = [];
for (var i in backgrounds) {
if (backgrounds[i].src) {
var cacheImage = document.createElement("img");
cacheImage.src = backgrounds[i].src;
cache.push(cacheImage);
}
}
return $.vegas;
}
};
function resize($img, settings) {
var options = {
align: "center",
valign: "center"
};
$.extend(options, settings);
if ($img.height() === 0) {
$img.load(function() {
resize($(this), settings);
});
return;
}
var vp = getViewportSize(), ww = vp.width, wh = vp.height, iw = $img.width(), ih = $img.height(), rw = wh / ww, ri = ih / iw, newWidth, newHeight, newLeft, newTop, properties;
if (rw > ri) {
newWidth = wh / ri;
newHeight = wh;
} else {
newWidth = ww;
newHeight = ww * ri;
}
properties = {
width: newWidth + "px",
height: newHeight + "px",
top: "auto",
bottom: "auto",
left: "auto",
right: "auto"
};
if (!isNaN(parseInt(options.valign, 10))) {
properties.top = 0 - (newHeight - wh) / 100 * parseInt(options.valign, 10) + "px";
} else if (options.valign == "top") {
properties.top = 0;
} else if (options.valign == "bottom") {
properties.bottom = 0;
} else {
properties.top = (wh - newHeight) / 2;
}
if (!isNaN(parseInt(options.align, 10))) {
properties.left = 0 - (newWidth - ww) / 100 * parseInt(options.align, 10) + "px";
} else if (options.align == "left") {
properties.left = 0;
} else if (options.align == "right") {
properties.right = 0;
} else {
properties.left = (ww - newWidth) / 2;
}
$img.css(properties);
}
function loading() {
$loading.prependTo("body").fadeIn();
}
function loaded() {
$loading.fadeOut("fast", function() {
$(this).remove();
});
}
function getBackground() {
if ($("body").css("backgroundImage")) {
return $("body").css("backgroundImage").replace(/url\("?(.*?)"?\)/i, "$1");
}
}
function getViewportSize() {
var elmt = window, prop = "inner";
if (!("innerWidth" in window)) {
elmt = document.documentElement || document.body;
prop = "client";
}
return {
width: elmt[prop + "Width"],
height: elmt[prop + "Height"]
};
}
$.vegas = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === "object" || !method) {
return methods.init.apply(this, arguments);
} else {
$.error("Method " + method + " does not exist");
}
};
$.vegas.defaults = {
background: {},
slideshow: {},
overlay: {}
};
})(jQuery);
The assets are compiled alphabetically in the pipeline. So you could either rename the files to compile in the order you like, or you can remove
//= require_tree .
in your application.js and require all of your assets manually in the order you choose. Hopefully that helps a little.
I have a watch looking at my sliders model and when I want to set one of the properties to visible or enabled it doesn't seem to want to fire the watch changed event. If I click the button it should hide or disable the handle and it does not. If I drag another handle the updateDOM is called and the handle is then hidden or disabled. Not sure what I am doing incorrectly here.
scope.$watch('sliders', function(oldValue, newValue) {
console.log('sliders Update: ', oldValue, ' : ', newValue);
updateDOM();
});
Here is a working plunk: http://plnkr.co/edit/I3A9H8qTs0z4CVaYnyJZ?p=preview
'use strict';
angular.module('angularMultiSlider', [])
.directive('multiSliderKey', function($compile) {
return {
restrict: 'EA',
transclude: true,
scope: {
displayFilter: '#',
sliders : '=ngModel'
},
link: function(scope, element) {
var sliderStr = '';
if (scope.displayFilter === undefined) scope.displayFilter = '';
var filterExpression = scope.displayFilter === '' ? '' : ' | ' + scope.displayFilter;
angular.forEach(scope.sliders, function(slider, key){
var colorKey = slider.color ? '<span style="background-color:' + slider.color + ';"></span> ' : '';
sliderStr += '<div class="key">' + colorKey + '{{ sliders[' + key.toString() + '].title }} <strong>{{ sliders[' + key.toString() + '].value ' + filterExpression + '}}</strong></div>';
});
var sliderControls = angular.element('<div class="angular-multi-slider-key">' + sliderStr + '</div>');
element.append(sliderControls);
$compile(sliderControls)(scope);
}
}
})
.directive('multiSlider', function($compile, $filter) {
var events = {
mouse: {
start: 'mousedown',
move: 'mousemove',
end: 'mouseup'
},
touch: {
start: 'touchstart',
move: 'touchmove',
end: 'touchend'
}
};
function roundStep(value, precision, step, floor) {
var remainder = (value - floor) % step;
var steppedValue = remainder > (step / 2) ? value + step - remainder : value - remainder;
var decimals = Math.pow(10, precision);
var roundedValue = steppedValue * decimals / decimals;
return parseFloat(roundedValue.toFixed(precision));
}
function offset(element, position) {
return element.css({
left: position
});
}
function pixelize(position) {
return parseInt(position) + 'px';
}
function contain(value) {
if (isNaN(value)) return value;
return Math.min(Math.max(0, value), 100);
}
function overlaps(b1, b2, offsetTop) {
function comparePositions(p1, p2) {
var r1 = p1[0] < p2[0] ? p1 : p2;
var r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
}
var posB1 = [[ b1.offsetLeft, b1.offsetLeft + b1.offsetWidth ], [ offsetTop, offsetTop - b1.scrollTop + b1.offsetHeight ]],
posB2 = [[ b2.offsetLeft, b2.offsetLeft + b2.offsetWidth ], [ b2.offsetTop, b2.offsetTop - b2.scrollTop + b2.offsetHeight ]];
return comparePositions( posB1[0], posB2[0] ) && comparePositions( posB1[1], posB2[1] );
}
return {
restrict: 'EA',
require: '?ngModel',
scope: {
floor: '#',
ceiling: '#',
step: '#',
precision: '#',
bubbles: '#',
displayFilter: '#',
sliders: '=ngModel'
},
template :
'<div class="bar"></div>',
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
//base copy to see if sliders returned to original
var original;
ngModel.$render = function() {
original = angular.copy(scope.sliders);
};
element.addClass('angular-multi-slider');
// DOM Components
if (scope.displayFilter === undefined) scope.displayFilter = '';
var filterExpression = scope.displayFilter === '' ? '' : ' | ' + scope.displayFilter;
var sliderStr = '<div class="limit floor">{{ floor ' + filterExpression + ' }}</div>' +
'<div class="limit ceiling">{{ ceiling ' + filterExpression + '}}</div>';
angular.forEach(scope.sliders, function(slider, key){
sliderStr += '<div class="handle"></div><div class="bubble">{{ sliders[' + key.toString() + '].title }}{{ sliders[' + key.toString() + '].value ' + filterExpression + ' }}</div>';
});
var sliderControls = angular.element(sliderStr);
element.append(sliderControls);
$compile(sliderControls)(scope);
var children = element.children();
var bar = angular.element(children[0]),
ngDocument = angular.element(document),
floorBubble = angular.element(children[1]),
ceilBubble = angular.element(children[2]),
bubbles = [],
handles = [];
angular.forEach(scope.sliders, function(slider, key) {
handles.push(angular.element(children[(key * 2) + 3]));
bubbles.push(angular.element(children[(key * 2) + 4]));
});
// Control Dimensions Used for Calculations
var handleHalfWidth = 0,
barWidth = 0,
minOffset = 0,
maxOffset = 0,
minValue = 0,
maxValue = 0,
valueRange = 0,
offsetRange = 0,
bubbleTop = undefined,
bubbleHeight = undefined,
handleTop = undefined,
handleHeight = undefined;
if (scope.step === undefined) scope.step = 10;
if (scope.floor === undefined) scope.floor = 0;
if (scope.ceiling === undefined) scope.ceiling = 500;
if (scope.precision === undefined) scope.precision = 2;
if (scope.bubbles === undefined) scope.bubbles = false;
var bindingsSet = false;
var updateCalculations = function() {
scope.floor = roundStep(parseFloat(scope.floor), parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
scope.ceiling = roundStep(parseFloat(scope.ceiling), parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
angular.forEach(scope.sliders, function(slider) {
slider.value = roundStep(parseFloat(slider.value), parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
});
handleHalfWidth = handles[0][0].offsetWidth / 2;
barWidth = bar[0].offsetWidth;
minOffset = 0;
maxOffset = barWidth - handles[0][0].offsetWidth;
minValue = parseFloat(scope.floor);
maxValue = parseFloat(scope.ceiling);
valueRange = maxValue - minValue;
offsetRange = maxOffset - minOffset;
};
var updateDOM = function () {
updateCalculations();
var percentOffset = function (offset) {
return contain(((offset - minOffset) / offsetRange) * 100);
};
var percentValue = function (value) {
return contain(((value - minValue) / valueRange) * 100);
};
var pixelsToOffset = function (percent) {
return pixelize(percent * offsetRange / 100);
};
var setHandles = function () {
offset(ceilBubble, pixelize(barWidth - ceilBubble[0].offsetWidth));
angular.forEach(scope.sliders, function(slider,key){
if (slider.color) {
handles[key].css({'background-color': slider.color});
}
if (slider.value >= minValue && slider.value <= maxValue) {
offset(handles[key], pixelsToOffset(percentValue(slider.value)));
offset(bubbles[key], pixelize(handles[key][0].offsetLeft - (bubbles[key][0].offsetWidth / 2) + handleHalfWidth));
handles[key].css({'display': 'block'});
if ('' + scope.bubbles === 'true') {
bubbles[key].css({'display': 'block'});
}
} else {
handles[key].css({'display': 'none'});
bubbles[key].css({'display': 'none'});
}
if (slider.hasOwnProperty("visible") && slider.visible === false) {
handles[key].css({'display': 'none'});
bubbles[key].css({'display': 'none'});
}
if (slider.hasOwnProperty("enabled") && slider.enabled === false) {
handles[key].addClass('disabled');
bubbles[key].addClass('disabled');
} else {
handles[key].removeClass('disabled');
bubbles[key].removeClass('disabled');
}
});
};
var resetBubbles = function() {
if (scope.sliders.length > 1) {
//timeout must be longer than css animation for proper bubble collision detection
for (var i = 0; i < scope.sliders.length; i++) {
(function (index) {
setTimeout(function () {
overlapCheck(index);
}, i * 150);
})(i);
}
}
};
var overlapCheck = function(currentRef) {
var safeAtLevel = function(cRef, level) {
for (var x = 0; x < scope.sliders.length; x++) {
if (x != cRef && overlaps(bubbles[cRef][0], bubbles[x][0], (bubbleTop * level))) {
return safeAtLevel(cRef, level + 1);
}
}
return level;
};
if (scope.sliders.length > 1) {
var safeLevel = safeAtLevel(currentRef, 1) - 1;
handles[currentRef].css({top: pixelize((-1 * (safeLevel * bubbleHeight)) + handleTop), height: pixelize(handleHeight + (bubbleHeight * safeLevel)), 'z-index': 99-safeLevel});
bubbles[currentRef].css({top: pixelize(bubbleTop - (bubbleHeight * safeLevel))});
}
};
var bind = function (handle, bubble, currentRef, events) {
var onEnd = function () {
handle.removeClass('grab');
bubble.removeClass('grab');
if (!(''+scope.bubbles === 'true')) {
bubble.removeClass('active');
}
ngDocument.unbind(events.move);
ngDocument.unbind(events.end);
if (angular.equals(scope.sliders, original)) {
ngModel.$setPristine();
}
//Move possible elevated bubbles back down if one below it moved.
resetBubbles();
scope.$apply();
};
var onMove = function (event) {
// Suss out which event type we are capturing and get the x value
var eventX = 0;
if (event.clientX !== undefined) {
eventX = event.clientX;
}
else if ( event.touches !== undefined && event.touches.length) {
eventX = event.touches[0].clientX;
}
else if ( event.originalEvent !== undefined &&
event.originalEvent.changedTouches !== undefined &&
event.originalEvent.changedTouches.length) {
eventX = event.originalEvent.changedTouches[0].clientX;
}
var newOffset = Math.max(Math.min((eventX - element[0].getBoundingClientRect().left - handleHalfWidth), maxOffset), minOffset),
newPercent = percentOffset(newOffset),
newValue = minValue + (valueRange * newPercent / 100.0);
newValue = roundStep(newValue, parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
scope.sliders[currentRef].value = newValue;
setHandles();
overlapCheck(currentRef);
ngModel.$setDirty();
scope.$apply();
};
var onStart = function (event) {
if (scope.sliders[currentRef].hasOwnProperty("enabled") && scope.sliders[currentRef].enabled === false) {
bubble.addClass('disabled');
handle.addClass('disabled');
return;
}
updateCalculations();
bubble.addClass('active grab');
handle.addClass('active grab');
setHandles();
event.stopPropagation();
event.preventDefault();
ngDocument.bind(events.move, onMove);
return ngDocument.bind(events.end, onEnd);
};
handle.bind(events.start, onStart);
};
var setBindings = function () {
var method, i;
var inputTypes = ['touch', 'mouse'];
for (i = 0; i < inputTypes.length; i++) {
method = inputTypes[i];
angular.forEach(scope.sliders, function(slider, key){
bind(handles[key], bubbles[key], key, events[method]);
if (scope.sliders[key].hasOwnProperty("enabled") && scope.sliders[key].enabled === false) {
handles[key].addClass('disabled');
bubbles[key].addClass('disabled');
}
});
}
bindingsSet = true;
};
if (!bindingsSet) {
setBindings();
// Timeout needed because bubbles offsetWidth is incorrect during initial rendering of html elements
setTimeout( function() {
if ('' + scope.bubbles === 'true') {
angular.forEach(bubbles, function (bubble) {
bubble.addClass('active');
});
}
updateCalculations();
setHandles();
//Get Default sizes of bubbles and handles, assuming each are equal, calculated from css
handleTop = handleTop === undefined ? handles[0][0].offsetTop : handleTop;
handleHeight = handleHeight === undefined ? handles[0][0].offsetHeight : handleHeight;
bubbleTop = bubbleTop === undefined ? bubbles[0][0].offsetTop : bubbleTop;
bubbleHeight = bubbleHeight === undefined ? bubbles[0][0].offsetHeight + 7 : bubbleHeight ; //add 7px bottom margin to the bubble offset for handle
resetBubbles();
}, 10);
}
};
// Watch Models based on mode
scope.$watch('sliders', function(oldValue, newValue) {
console.log('sliders Update: ', oldValue, ' : ', newValue);
updateDOM();
});
scope.$watch('ceiling', function() {
bindingsSet = false;
updateDOM();
});
scope.$watch('floor', function() {
bindingsSet = false;
updateDOM();
});
// Update on Window resize
window.addEventListener('resize', updateDOM);
}
}
});
I found the solution here: How to deep watch an array in angularjs? Deep watch /property watch.
$scope.$watch('columns', function() {
// some value in the array has changed
}, true); // watching properties
i have this page http://kreditmoney.ch/de/kreditantrag/index.php
Slider at right side can not work at IE9 and older version. I fixed error at IE11.
I assume that, the error is in this code:
.........
else {
this.fireEvent('onChange', this.step);
this.bkg.style.clip = "rect(0px "+ (parseInt(this.drag.value.now[this.z]) +3) + "px 10px 0px)"
........
This is full code:
var SliderMoj = new Class({
options: {
onChange: Class.empty,
onComplete: Class.empty,
onTick: function(pos){
this.moveKnob.setStyle(this.p, pos);
},
start: 0,
end: 100,
offset: 0,
knobheight: 20,
knobwidth: 14,
mode: 'horizontal',
clip_w:0,
clip_l:0,
isinit:true,
snap: false,
range: false,
numsteps:null
},
initialize: function(el, knob,bkg, options, maxknob) {
this.setOptions(options);
this.element = $(el);
this.knob = $(knob);
this.previousChange = this.previousEnd = this.step = -1;
this.bkg = $(bkg);
if(this.options.steps==null){
this.options.steps = this.options.end - this.options.start;
}
if(maxknob!=null)
this.maxknob = $(maxknob);
//else
// this.element.addEvent('mousedown', this.clickedElement.bindWithEvent(this));
var mod, offset;
switch(this.options.mode){
case 'horizontal':
this.z = 'x';
this.p = 'left';
mod = {'x': 'left', 'y': false};
offset = 'offsetWidth';
break;
case 'vertical':
this.z = 'y';
this.p = 'top';
mod = {'x': false, 'y': 'top'};
offset = 'offsetHeight';
}
this.max = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
this.half = this.knob[offset]/2;
this.full = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
this.min = $chk(this.options.range[0]) ? this.options.range[0] : 0;
this.getPos = this.element['get' + this.p.capitalize()].bind(this.element);
this.knob.setStyle('position', 'relative').setStyle(this.p, - this.options.offset);
this.range = this.max - this.min;
this.steps = this.options.steps || this.full;
this.stepSize = Math.abs(this.range) / this.steps;
this.stepWidth = this.stepSize * this.full / Math.abs(this.range) ;
if(maxknob != null) {
this.maxPreviousChange = -1;
this.maxPreviousEnd = -1;
this.maxstep = this.options.end;
this.maxknob.setStyle('position', 'relative').setStyle(this.p, + this.max - this.options.offset).setStyle('bottom', this.options.knobheight);
}
var lim = {};
//status = this.z
lim[this.z] = [- this.options.offset, this.max - this.options.offset];
//lim[this.z] = [100, this.max - this.options.offset];
this.drag = new Drag(this.knob, {
limit: lim,
modifiers: mod,
snap: 0,
onStart: function(){
this.draggedKnob();
}.bind(this),
onDrag: function(){
this.draggedKnob();
}.bind(this),
onComplete: function(){
this.draggedKnob();
this.end();
}.bind(this)
});
if(maxknob != null) {
this.maxdrag = new Drag(this.maxknob, {
limit: lim,
modifiers: mod,
snap: 0,
onStart: function(){
this.draggedKnob(1);
}.bind(this),
onDrag: function(){
this.draggedKnob(1);
}.bind(this),
onComplete: function(){
this.draggedKnob(1);
this.end();
}.bind(this)
});
}
if (this.options.snap) {
//this.drag.options.grid = Math.ceil(this.stepWidth);
this.drag.options.grid = (this.full)/this.options.numsteps ;
this.drag.options.limit[this.z][1] = this.full;
//this.drag.options.grid = this.drag.options.grid - (this.knob[offset]/this.options.numsteps);
status = "GRID - " + this.drag.options.grid + " , full = " + this.full// DEBUG
}
if (this.options.initialize) this.options.initialize.call(this);
},
setMin: function(stepMin){
this.step = stepMin.limit(this.options.start, this.options.end);
this.checkStep();
this.end();
this.moveKnob = this.knob;
this.bkg.style.clip = "rect(0px "+ (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)";
status =this.bkg.style.clip + " vl= " + parseInt(this.toPosition(this.step)) ; //Debug
this.fireEvent('onTick', this.toPosition(this.step));
return this;
},
setMax: function(stepMax){
this.maxstep = stepMax.limit(this.options.start, this.options.end);
this.checkStep(1);
this.end();
this.moveKnob = this.maxknob;
var w= Math.abs(this.toPosition(this.step)- this.toPosition(this.maxstep)) + 3 ;
var r = parseInt(this.clip_l + w);
this.bkg.style.clip = "rect(0px "+ r + "px 10px "+ this.clip_l + "px)";
this.fireEvent('onTick', this.toPosition(this.maxstep));
// For Init Only
if(this.options.isinit){
var lim = {}; var mi,mx;
mi = - this.options.offset;
mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
lim[this.z] = [mi, mx];
this.drag.options.limit = lim;
this.options.isinit = false;
}
return this;
},
clickedElement: function(event){
var position = event.page[this.z] - this.getPos() - this.half;
position = position.limit(-this.options.offset, this.max -this.options.offset);
this.step = this.toStep(position);
//this.moveKnob = this.knob;
this.bkg.style.clip = "rect(0px "+ (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)"
//status =this.bkg.style.clip; //Debug
this.checkStep();
this.end();
this.fireEvent('onTick', position);
},
draggedKnob: function(mx){
var lim = {}; var mi,mx;
if(mx==null) {
this.step = this.toStep(this.drag.value.now[this.z]);
this.checkStep();
}else {
this.maxstep = this.toStep(this.maxdrag.value.now[this.z]);
this.checkStep(1);
}
},
checkStep: function(mx){
var lim = {}; var mi,mx;
var limm = {};
if(mx==null) {if (this.previousChange != this.step){this.previousChange = this.step;}}
else {if (this.maxPreviousChange != this.maxstep){this.maxPreviousChange = this.maxstep;}}
if(this.maxknob!=null) {
mi = - this.options.offset;
mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
//mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset ;
lim[this.z] = [mi, mx];
this.drag.options.limit = lim;
mi = parseInt(this.knob.getStyle('left'))-this.options.offset+22;
//mi = parseInt(this.knob.getStyle('left'))-this.options.offset;
mx= this.max - this.options.offset;
limm[this.z] = [mi, mx];
this.maxdrag.options.limit = limm;
if(this.step < this.maxstep){
this.fireEvent('onChange', { minpos: this.step, maxpos: this.maxstep });
//this.clip_l = parseInt(this.knob.getStyle('left'));
}
else{
this.fireEvent('onChange', { minpos: this.maxstep, maxpos: this.step });
//this.clip_l = (parseInt(this.maxknob.getStyle('left')) + 10) ;
}
this.clip_l = parseInt(this.knob.getStyle('left')) + 10;
//var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left'))) + 3;
var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left')));
//if(w > 3) w = w+3;
var r = parseInt(this.clip_l + w);
this.bkg.style.clip = "rect(0px "+ r + "px 10px "+ this.clip_l + "px)"
//status =this.bkg.style.clip + " w= " + w //Debug
}else {
this.fireEvent('onChange', this.step);
this.bkg.style.clip = "rect(0px "+ (parseInt(this.drag.value.now[this.z]) +3) + "px 10px 0px)"
}
},
end: function(){
if (this.previousEnd !== this.step || (this.maxknob != null && this.maxPreviousEnd != this.maxstep)) {
this.previousEnd = this.step;
if(this.maxknob != null) {
this.maxPreviousEnd = this.maxstep;
if(this.step < this.maxstep)
this.fireEvent('onComplete', { minpos: this.step + '', maxpos: this.maxstep + '' });
else
this.fireEvent('onComplete', { minpos: this.maxstep + '', maxpos: this.step + '' });
}else{
this.fireEvent('onComplete', this.step + '');
}
}
},
toStep: function(position){
return Math.round((position + this.options.offset) / this.max * this.options.steps) + this.options.start;
},
toPosition: function(step){
return (this.max * step / this.options.steps) - (this.max * this.options.start / this.options.steps) - this.options.offset;
}
});
SliderMoj.implement(new Events);
SliderMoj.implement(new Options);
Best regards,
Nemanja
I found solution for this problem.
The code should look like this:
'var SliderMoj = new
Class({
options: {
onChange: Class.empty,
onComplete: Class.empty,
onTick: function(pos){
this.moveKnob.setStyle(this.p, pos);
},
start: 0,
end: 100,
offset: 0,
knobheight: 20,
knobwidth: 14,
mode: 'horizontal',
clip_w:0,
clip_l:0,
isinit:true,
snap: false,
range: false,
numsteps:null
},
initialize: function(el, knob,bkg, options, maxknob) {
this.setOptions(options);
this.element = $(el);
this.knob = $(knob);
this.previousChange = this.previousEnd = this.step = -1;
this.bkg = $(bkg);
if(this.options.steps==null){
this.options.steps = this.options.end - this.options.start;
}
if(maxknob!=null)
this.maxknob = $(maxknob);
//else
// this.element.addEvent('mousedown', this.clickedElement.bindWithEvent(this));
var mod, offset;
switch(this.options.mode){
case 'horizontal':
this.z = 'x';
this.p = 'left';
mod = {'x': 'left', 'y': false};
offset = 'offsetWidth';
break;
case 'vertical':
this.z = 'y';
this.p = 'top';
mod = {'x': false, 'y': 'top'};
offset = 'offsetHeight';
}
this.max = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
this.half = this.knob[offset]/2;
this.full = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
this.min = $chk(this.options.range[0]) ? this.options.range[0] : 0;
this.getPos = this.element['get' + this.p.capitalize()].bind(this.element);
this.knob.setStyle('position', 'relative').setStyle(this.p, - this.options.offset);
this.range = this.max - this.min;
this.steps = this.options.steps || this.full;
this.stepSize = Math.abs(this.range) / this.steps;
this.stepWidth = this.stepSize * this.full / Math.abs(this.range) ;
if(maxknob != null) {
this.maxPreviousChange = -1;
this.maxPreviousEnd = -1;
this.maxstep = this.options.end;
this.maxknob.setStyle('position', 'relative').setStyle(this.p, + this.max - this.options.offset).setStyle('bottom', this.options.knobheight);
}
var lim = {};
//status = this.z
lim[this.z] = [- this.options.offset, this.max - this.options.offset];
//lim[this.z] = [100, this.max - this.options.offset];
this.drag = new Drag(this.knob, {
limit: lim,
modifiers: mod,
snap: 0,
onStart: function(){
this.draggedKnob();
}.bind(this),
onDrag: function(){
this.draggedKnob();
}.bind(this),
onComplete: function(){
this.draggedKnob();
this.end();
}.bind(this)
});
if(maxknob != null) {
this.maxdrag = new Drag(this.maxknob, {
limit: lim,
modifiers: mod,
snap: 0,
onStart: function(){
this.draggedKnob(1);
}.bind(this),
onDrag: function(){
this.draggedKnob(1);
}.bind(this),
onComplete: function(){
this.draggedKnob(1);
this.end();
}.bind(this)
});
}
if (this.options.snap) {
//this.drag.options.grid = Math.ceil(this.stepWidth);
this.drag.options.grid = (this.full)/this.options.numsteps ;
this.drag.options.limit[this.z][1] = this.full;
//this.drag.options.grid = this.drag.options.grid - (this.knob[offset]/this.options.numsteps);
status = "GRID - " + this.drag.options.grid + " , full = " + this.full// DEBUG
}
if (this.options.initialize) this.options.initialize.call(this);
},
setMin: function(stepMin){
this.step = stepMin.limit(this.options.start, this.options.end);
this.checkStep();
this.end();
this.moveKnob = this.knob;
this.bkg.style.clip = "rect(0px "+ (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)";
status =this.bkg.style.clip + " vl= " + parseInt(this.toPosition(this.step)) ; //Debug
this.fireEvent('onTick', this.toPosition(this.step));
return this;
},
setMax: function(stepMax){
this.maxstep = stepMax.limit(this.options.start, this.options.end);
this.checkStep(1);
this.end();
this.moveKnob = this.maxknob;
var w= Math.abs(this.toPosition(this.step)- this.toPosition(this.maxstep)) + 3 ;
var r = parseInt(this.clip_l + w);
this.bkg.style.clip = "rect(0px "+ r + "px 10px "+ this.clip_l + "px)";
this.fireEvent('onTick', this.toPosition(this.maxstep));
// For Init Only
if(this.options.isinit){
var lim = {}; var mi,mx;
mi = - this.options.offset;
mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
lim[this.z] = [mi, mx];
this.drag.options.limit = lim;
this.options.isinit = false;
}
return this;
},
clickedElement: function(event){
var position = event.page[this.z] - this.getPos() - this.half;
position = position.limit(-this.options.offset, this.max -this.options.offset);
this.step = this.toStep(position);
//this.moveKnob = this.knob;
this.bkg.style.clip = "rect(0px "+ (parseInt(this.toPosition(this.step)) +3) + "px 10px 0px)"
//status =this.bkg.style.clip; //Debug
this.checkStep();
this.end();
this.fireEvent('onTick', position);
},
draggedKnob: function(mx){
var lim = {}; var mi,mx;
if(mx==null) {
this.step = this.toStep(this.drag.value.now[this.z]);
this.checkStep();
}else {
this.maxstep = this.toStep(this.maxdrag.value.now[this.z]);
this.checkStep(1);
}
},
checkStep: function(mx){
var lim = {}; var mi,mx;
var limm = {};
if(mx==null) {if (this.previousChange != this.step){this.previousChange = this.step;}}
else {if (this.maxPreviousChange != this.maxstep){this.maxPreviousChange = this.maxstep;}}
if(this.maxknob!=null) {
mi = - this.options.offset;
mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset-4 ;
//mx= parseInt(this.maxknob.getStyle('left')) - this.options.offset ;
lim[this.z] = [mi, mx];
this.drag.options.limit = lim;
mi = parseInt(this.knob.getStyle('left'))-this.options.offset+22;
//mi = parseInt(this.knob.getStyle('left'))-this.options.offset;
mx= this.max - this.options.offset;
limm[this.z] = [mi, mx];
this.maxdrag.options.limit = limm;
if(this.step < this.maxstep){
this.fireEvent('onChange', { minpos: this.step, maxpos: this.maxstep });
//this.clip_l = parseInt(this.knob.getStyle('left'));
}
else{
this.fireEvent('onChange', { minpos: this.maxstep, maxpos: this.step });
//this.clip_l = (parseInt(this.maxknob.getStyle('left')) + 10) ;
}
this.clip_l = parseInt(this.knob.getStyle('left')) + 10;
//var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left'))) + 3;
var w = Math.abs(parseInt(this.knob.getStyle('left')) - parseInt(this.maxknob.getStyle('left')));
//if(w > 3) w = w+3;
var r = parseInt(this.clip_l + w);
this.bkg.style.clip = "rect(0px "+ r + "px 10px "+ this.clip_l + "px)"
//status =this.bkg.style.clip + " w= " + w //Debug
}else {
this.fireEvent('onChange', this.step);
this.bkg.style.clip = "rect(0px "+ (parseInt(this.drag.value.now[this.z]) +3) + "px 10px 0px)"
}
},
end: function(){
if (this.previousEnd !== this.step || (this.maxknob != null && this.maxPreviousEnd != this.maxstep)) {
this.previousEnd = this.step;
if(this.maxknob != null) {
this.maxPreviousEnd = this.maxstep;
if(this.step < this.maxstep)
this.fireEvent('onComplete', { minpos: this.step + '', maxpos: this.maxstep + '' });
else
this.fireEvent('onComplete', { minpos: this.maxstep + '', maxpos: this.step + '' });
}else{
this.fireEvent('onComplete', this.step + '');
}
}
},
toStep: function(position){
return Math.round((position + this.options.offset) / this.max * this.options.steps) + this.options.start;
},
toPosition: function(step){
return (this.max * step / this.options.steps) - (this.max * this.options.start / this.options.steps) - this.options.offset;
}
});'
#kiran-rs
I have a circle that has a menu with objects positioned in a circle inside the circle. When the user drags their finger in any direction the circle spins along with the finger, however, when the user is spinning the wheel and happens to touch one of the objects inside (serves as a link) the circle "brakes" and stops spinning. I need to cancel the event bubble. I know I need to use event.stopPropagation and deal with the capture inside the event handler but I am having issues implementing this with a jQuery plugin (Touchy) that I found.
*MAKE SURE YOU ARE VIEWING IN CHROME WITH THE OVERRIDES SET TO EMULATE TOUCH EVENTS AND THAT THE DEVELOPER CONSOLE IS OPEN Command+Option+i on Mac!!! *
http://jsfiddle.net/ymtV3/
*MAKE SURE YOU ARE VIEWING IN CHROME WITH THE OVERRIDES SET TO EMULATE TOUCH EVENTS AND THAT THE DEVELOPER CONSOLE IS OPEN Command+Option+i on Mac!!! *
<div id="wheelMenu">
<div id="wheel">
<ul class="items">
<li class="flashOff"><span>Flash</span></li>
<li class="sceneOff"><span>Scene</span></li>
<li class="hdrOff"><span>Hdr</span></li>
<li class="panoramaOff"><span>Pana</span></li>
<li class="resolutionOff"><span>Resolu</span></li>
<li class="reviewOff"><span>Review</span></li>
<li class="continuousShootingOff"><span>Contin</span></li>
<li class="dropBoxOff"><span>DropBox</span></li>
<li class="timerOff"><span>Timer</span></li>
</ul>
</div>
</div>
(function ($) {
$.touchyOptions = {
useDelegation: false,
rotate: {
preventDefault: {
start: true,
move: true,
end: true
},
stopPropagation: {
start: true,
move: true,
end: true
},
requiredTouches: 1,
data: {},
proxyEvents: ["TouchStart", "TouchMove", "GestureChange", "TouchEnd"]
}
};
var proxyHandlers = {
handleTouchStart: function (e) {
var eventType = this.context,
$target = getTarget(e, eventType);
if ($target) {
var event = e.originalEvent,
touches = event.targetTouches,
camelDataName = 'touchy' + eventType.charAt(0).toUpperCase() + eventType.slice(1),
data = $target.data(camelDataName),
settings = data.settings;
if (settings.preventDefault.start) {
event.preventDefault();
}
if (settings.stopPropagation.start) {
event.stopPropagation();
}
if (touches.length === settings.requiredTouches) {
switch (eventType) {
case 'rotate':
if (touches.length === 1) {
ensureSingularStartData(data, touches, e.timeStamp);
console.log(eventType);
console.log(touches);
console.log(data);
} else {
var points = getTwoTouchPointData(e);
data.startPoint = {
"x": points.centerX,
"y": points.centerY
};
data.startDate = e.timeStamp;
}
var startPoint = data.startPoint;
$target.trigger('touchy-rotate', ['start', $target, {
"startPoint": startPoint,
"movePoint": startPoint,
"lastMovePoint": startPoint,
"velocity": 0,
"degrees": 0
}]);
break;
}
}
}
},
handleTouchMove: function (e) {
var eventType = this.context,
$target = getTarget(e, eventType);
if ($target) {
var event = e.originalEvent,
touches = event.targetTouches,
camelDataName = 'touchy' + eventType.charAt(0).toUpperCase() + eventType.slice(1),
data = $target.data(camelDataName),
settings = data.settings;
if (settings.preventDefault.move) {
event.preventDefault();
}
if (settings.stopPropagation.move) {
event.stopPropagation();
}
if (touches.length === settings.requiredTouches) {
switch (eventType) {
case 'rotate':
var lastMovePoint,
lastMoveDate,
movePoint,
moveDate,
lastMoveDate,
distance,
ms,
velocity,
targetPageCoords,
centerCoords,
radians,
degrees,
lastDegrees,
degreeDelta;
lastMovePoint = data.lastMovePoint = data.movePoint || data.startPoint;
lastMoveDate = data.lastMoveDate = data.moveDate || data.startDate;
movePoint = data.movePoint = {
"x": touches[0].pageX,
"y": touches[0].pageY
};
moveDate = data.moveDate = e.timeStamp;
if (touches.length === 1) {
targetPageCoords = data.targetPageCoords = data.targetPageCoords || getViewOffset(e.target);
centerCoords = data.centerCoords = data.centerCoords || {
"x": targetPageCoords.x + ($target.width() * 0.5),
"y": targetPageCoords.y + ($target.height() * 0.5)
};
} else {
var points = getTwoTouchPointData(e);
centerCoords = data.centerCoords = {
"x": points.centerX,
"y": points.centerY
};
if (hasGestureChange()) {
break;
}
}
radians = Math.atan2(movePoint.y - centerCoords.y, movePoint.x - centerCoords.x);
lastDegrees = data.lastDegrees = data.degrees;
degrees = data.degrees = radians * (180 / Math.PI);
degreeDelta = lastDegrees ? degrees - lastDegrees : 0;
ms = moveDate - lastMoveDate;
velocity = data.velocity = ms === 0 ? 0 : degreeDelta / ms;
$target.trigger('touchy-rotate', ['move', $target, {
"startPoint": data.startPoint,
"startDate": data.startDate,
"movePoint": movePoint,
"lastMovePoint": lastMovePoint,
"centerCoords": centerCoords,
"degrees": degrees,
"degreeDelta": degreeDelta,
"velocity": velocity
}]);
break;
}
}
}
},
handleGestureChange: function (e) {
var eventType = this.context,
$target = getTarget(e, eventType);
if ($target) {
var $target = $(e.target),
event = e.originalEvent,
touches = event.touches,
camelDataName = 'touchy' + eventType.charAt(0).toUpperCase() + eventType.slice(1),
data = $target.data(camelDataName);
if (data.preventDefault.move) {
event.preventDefault();
}
if (settings.stopPropagation.move) {
event.stopPropagation();
}
switch (eventType) {
case 'rotate':
var lastDegrees = data.lastDegrees = data.degrees,
degrees = data.degrees = event.rotation,
degreeDelta = lastDegrees ? degrees - lastDegrees : 0,
ms = data.moveDate - data.lastMoveDate,
velocity = data.velocity = ms === 0 ? 0 : degreeDelta / ms;
$target.trigger('touchy-rotate', ['move', $target, {
"startPoint": data.startPoint,
"startDate": data.startDate,
"movePoint": data.movePoint,
"lastMovePoint": data.lastMovePoint,
"centerCoords": data.centerCoords,
"degrees": degrees,
"degreeDelta": degreeDelta,
"velocity": velocity
}]);
break;
}
}
},
handleTouchEnd: function (e) {
var eventType = this.context,
$target = getTarget(e, eventType);
if ($target) {
var event = e.originalEvent,
camelDataName = 'touchy' + eventType.charAt(0).toUpperCase() + eventType.slice(1),
data = $target.data(camelDataName),
settings = data.settings;
if (settings.preventDefault.end) {
event.preventDefault();
}
if (settings.stopPropagation.end) {
event.stopPropagation();
}
switch (eventType) {
case 'rotate':
var degreeDelta = data.lastDegrees ? data.degrees - data.lastDegrees : 0;
$target.trigger('touchy-rotate', ['end', $target, {
"startPoint": data.startPoint,
"startDate": data.startDate,
"movePoint": data.movePoint,
"lastMovePoint": data.lastMovePoint,
"degrees": data.degrees,
"degreeDelta": degreeDelta,
"velocity": data.velocity
}]);
$.extend(data, {
"startPoint": null,
"startDate": null,
"movePoint": null,
"moveDate": null,
"lastMovePoint": null,
"lastMoveDate": null,
"targetPageCoords": null,
"centerCoords": null,
"degrees": null,
"lastDegrees": null,
"velocity": null
});
break;
}
}
}
},
ensureSingularStartData = function (data, touches, timeStamp) {
if (!data.startPoint) {
data.startPoint = {
"x": touches[0].pageX,
"y": touches[0].pageY
}
}
if (!data.startDate) {
data.startDate = timeStamp;
}
},
hasGestureChange = function () {
return (typeof window.ongesturechange == "object");
},
getTarget = function (e, eventType) {
var $delegate,
$target = false,
i = 0,
len = boundElems[eventType].length
if ($.touchyOptions.useDelegation) {
for (; i < len; i += 1) {
$delegate = $(boundElems[eventType][i]).has(e.target);
if ($delegate.length > 0) {
$target = $delegate;
break;
}
}
} else if (boundElems[eventType] && boundElems[eventType].index(e.target) != -1) {
$target = $(e.target)
}
return $target;
},
getViewOffset = function (node, singleFrame) {
function addOffset(node, coords, view) {
var p = node.offsetParent;
coords.x += node.offsetLeft - (p ? p.scrollLeft : 0);
coords.y += node.offsetTop - (p ? p.scrollTop : 0);
if (p) {
if (p.nodeType == 1) {
var parentStyle = view.getComputedStyle(p, '');
if (parentStyle.position != 'static') {
coords.x += parseInt(parentStyle.borderLeftWidth);
coords.y += parseInt(parentStyle.borderTopWidth);
if (p.localName == 'TABLE') {
coords.x += parseInt(parentStyle.paddingLeft);
coords.y += parseInt(parentStyle.paddingTop);
} else if (p.localName == 'BODY') {
var style = view.getComputedStyle(node, '');
coords.x += parseInt(style.marginLeft);
coords.y += parseInt(style.marginTop);
}
} else if (p.localName == 'BODY') {
coords.x += parseInt(parentStyle.borderLeftWidth);
coords.y += parseInt(parentStyle.borderTopWidth);
}
var parent = node.parentNode;
while (p != parent) {
coords.x -= parent.scrollLeft;
coords.y -= parent.scrollTop;
parent = parent.parentNode;
}
addOffset(p, coords, view);
}
} else {
if (node.localName == 'BODY') {
var style = view.getComputedStyle(node, '');
coords.x += parseInt(style.borderLeftWidth);
coords.y += parseInt(style.borderTopWidth);
var htmlStyle = view.getComputedStyle(node.parentNode, '');
coords.x -= parseInt(htmlStyle.paddingLeft);
coords.y -= parseInt(htmlStyle.paddingTop);
}
if (node.scrollLeft) coords.x += node.scrollLeft;
if (node.scrollTop) coords.y += node.scrollTop;
var win = node.ownerDocument.defaultView;
if (win && (!singleFrame && win.frameElement)) addOffset(win.frameElement, coords, win);
}
}
......seee the rest on the JS Fiddle