javascript slideshow pauseonhover - javascript

my question is really simple and something can help a lot of people out there,
I want my slideshow to NOT stop when someone hover over it,
I was able to do it for one of my sites, by accessing the .js (nivooSlider.js) and adding to the list of options: the "false" value to the pauseOnHover option (pauseOnHover: false,)
and that did it! ...
Now I'm also trying to get the same result in another of my websites that is currently using rokSlider, which does not have that option by default, so i'm wondering, if i go to the options list and simple add this options+value ... Do you think that will work?
Regards
var Slideshow = new Class({
version: '3.0.3',
options: {
captions: true,
showTitleCaption: true,
classes: ['prev', 'next', 'active'],
duration: [2000, 4000],
path: '/',
navigation: false,
pan: 100,
resize: true,
thumbnailre: [/\./, 't.'],
transition: Fx.Transitions.Sine.easeInOut,
type: 'fade',
zoom: 50,
loadingDiv: true,
removeDiv: true
},
styles: {
caps: {
div: {
opacity: 0,
position: 'absolute',
width: '100%',
margin: 0,
left: 0,
bottom: 0,
height: 40,
background: '#333',
color: '#fff',
textIndent: 0
},
h2: {
color: 'red',
padding: 0,
fontSize: '80%',
margin: 0,
margin: '2px 5px',
fontWeight: 'bold'
},
p: {
padding: 0,
fontSize: '60%',
margin: '2px 5px',
color: '#eee'
}
}
},
initialize: function(el, options) {
this.setOptions($merge({
onClick: this.onClick.bind(this)
}, options));
if(!this.options.images) return;
this.options.pan = this.mask(this.options.pan);
this.options.zoom = this.mask(this.options.zoom);
this.el = $(el).empty();
this.caps = {
div: new Element('div', {
styles: this.styles.caps.div,
'class': 'captionDiv'
}),
h2: new Element('h2', {
styles: this.styles.caps.h2,
'class': 'captionTitle'
}),
p: new Element('p', {
styles: this.styles.caps.p,
'class': 'captionDescription'
})
};
this.fx = [];
var trash = new ImageLoader(this.el, this.options.images, {
loadingDiv: this.options.loadingDiv,
onComplete: this.start.bind(this),
path: this.options.path,
removeDiv: this.options.removeDiv
});
},
start: function() {
this.imgs = $A(arguments);
this.a = this.imgs[0].clone().set({
styles: {
display: 'block',
position: 'absolute',
left: 0,
'top': 0,
zIndex: 1
}
}).injectInside(this.el);
var obj = this.a.getCoordinates();
this.height = this.options.height || obj.height;
this.width = this.options.width || obj.width;
this.el.setStyles({
display: 'block',
position: 'relative',
width: this.width
});
this.el.empty();
this.el.adopt((new Element('div', {
events: {
'click': this.onClick.bind(this)
},
styles: {
display: 'block',
overflow: 'hidden',
position: 'relative',
width: this.width,
height: this.height
}
})).adopt(this.a));
this.resize(this.a, obj);
this.b = this.a.clone().setStyle('opacity', 0).injectAfter(this.a);
this.timer = [0, 0];
this.navigation();
this.direction = 'left';
this.curr = [0,0];
$(document.body).adopt(new Element('div', {
id: 'hiddenDIV',
styles: {
visibility: 'hidden',
height: 0,
width: 0,
overflow: 'hidden',
opacity: 0
}
}));
this.loader = this.imgs[0];
$('hiddenDIV').adopt(this.loader);
this.load();
},
load: function(fast) {
if ($time() > this.timer[0]) {
this.img = (this.curr[1] % 2) ? this.b : this.a;
this.img.setStyles({
opacity: 0,
width: 'auto',
height: 'auto',
zIndex: this.curr[1]
});
var url = this.options.images[this.curr[0]].url;
this.img.setStyle('cursor', (url != '#' && url != '') ? 'pointer' : 'default');
this.img.setProperties({
src: this.loader.src,
title: this.loader.title,
alt: this.loader.alt
});
this.resize(this.img, this.loader);
if(fast){
this.img.setStyles({
top: 0,
left: 0,
opacity: 1
});
this.captions();
this.loaded();
return;
}
this.captions();
this[this.options.type.test(/push|wipe/) ? 'swipe' : 'kens']();
this.loaded();
} else {
this.timeout = this.load.delay(100, this);
}
},
loaded: function() {
if(this.ul) {
this.ul.getElements('a[name]').each(function(a, i) {
a[(i === this.curr[0] ? 'add' : 'remove') + 'Class'](this.options.classes[2]);
}, this);
}
this.direction = 'left';
this.curr[0] = (this.curr[0] + 1) % this.imgs.length;
this.curr[1]++;
this.timer[0] = $time() + this.options.duration[1] + (this.options.type.test(/fade|push|wipe/) ? this.options.duration[0] : 0);
this.timer[1] = $time() + this.options.duration[0];
this.loader = this.imgs[this.curr[0]];
$('hiddenDIV').empty().adopt(this.loader);
this.load();
},
kens: function() {
this.img.setStyles({
bottom: 'auto',
right: 'auto',
left: 'auto',
top: 'auto'
});
var arr = ['left top', 'right top', 'left bottom', 'right bottom'].getRandom().split(' ');
arr.each(function(p) {
this.img.setStyle(p, 0);
}, this);
var zoom = this.options.type.test(/zoom|combo/) ? this.zoom() : {};
var pan = this.options.type.test(/pan|combo/) ? this.pan(arr) : {};
this.fx.push(this.img.effect('opacity', {duration: this.options.duration[0]}).start(1));
this.fx.push(this.img.effects({duration: this.options.duration[0] + this.options.duration[1]}).start($merge(zoom, pan)));
},
zoom: function() {
var n = Math.max(this.width / this.loader.width, this.height / this.loader.height);
var z = (this.options.zoom === 'rand') ? Math.random() + 1 : (this.options.zoom.toInt() / 100.0) + 1;
var eh = Math.ceil(this.loader.height * n);
var ew = Math.ceil(this.loader.width * n);
var sh = (eh * z).toInt();
var sw = (ew * z).toInt();
return {height: [sh, eh], width: [sw, ew]};
},
pan: function(arr) {
var ex = this.width - this.img.width, ey = this.height - this.img.height;
var p = this.options.pan === 'rand' ? Math.random() : Math.abs((this.options.pan.toInt() / 100) - 1);
var sx = (ex * p).toInt(), sy = (ey * p).toInt();
var x = this.width / this.loader.width > this.height / this.loader.height;
var obj = {};
obj[arr[x ? 1 : 0]] = x ? [sy, ey] : [sx, ex];
return obj;
},
swipe: function() {
var arr, p0 = {}, p1 = {}, x;
this.img.setStyles({
left: 'auto',
right: 'auto',
opacity: 1
}).setStyle(this.direction, this.width);
if(this.options.type === 'wipe') {
this.fx.push(this.img.effect(this.direction, {
duration: this.options.duration[0],
transition: this.options.transition
}).start(0));
} else {
arr = [this.img, this.curr[1] % 2 ? this.a : this.b];
p0[this.direction] = [this.width, 0];
p1[this.direction] = [0, -this.width];
if(arr[1].getStyle(this.direction) === 'auto') {
x = this.width - arr[1].getStyle('width').toInt();
arr[1].setStyle(this.direction, x);
arr[1].setStyle(this.direction === 'left' ? 'right' : 'left', 'auto');
p1[this.direction][0] = x;
}
this.fx.push(new Fx.Elements(arr, {
duration: this.options.duration[0],
transition: this.options.transition
}).start({
'0': p0,
'1': p1
}));
}
},
captions: function(img) {
img = img || this.img;
if(!this.options.captions || (!img.title && !img.alt)) return;
this.el.getFirst().adopt(this.caps.div.adopt(this.caps.h2, this.caps.p));
(function () {
if (this.options.showTitleCaption) this.caps.h2.setHTML(img.title);
this.caps.p.setHTML(img.alt);
this.caps.div.setStyle('zIndex', img.getStyle('zIndex')*2 || 10);
this.capsHeight = this.capsHeight || this.options.captionHeight || this.caps.div.offsetHeight;
var fx = this.caps.div.effects().set({'height': 0}).start({
opacity: 0.7,
height: this.capsHeight
});
(function(){
fx.start({
opacity: 0,
height: 0
});
}).delay(1.00*(this.options.duration[1] - this.options.duration[0]));
}).delay(0.75*(this.options.duration[0]), this);
},
navigation: function() {
if(!this.options.navigation) return;
var i, j, atemp;
var fast = this.options.navigation.test(/fast/) ;
this.ul = new Element('ul');
var li = new Element('li'), a = new Element('a');
if (this.options.navigation.test(/arrows/)) {
this.ul.adopt(li.clone()
.adopt(a.clone()
.addClass(this.options.classes[0])
.addEvent('click', function() {
if (fast || $time() > this.timer[1]) {
$clear(this.timeout);
// Clear the FX array only for fast navigation since this stops combo effects
if(fast) {
this.fx.each(function(fx) {
fx.time = 0;
fx.options.duration = 0;
fx.stop(true);
});
}
this.direction = 'right';
this.curr[0] = (this.curr[0] < 2) ? this.imgs.length - (2 - this.curr[0]) : this.curr[0] - 2;
this.timer = [0];
this.loader = this.imgs[this.curr[0]];
this.load(fast);
}
}.bind(this))
)
);
}
if (this.options.navigation.test(/arrows\+|thumbnails/)) {
for (i = 0, j = this.imgs.length; i < j; i++) {
atemp = a.clone().setProperty('name', i);
if (this.options.navigation.test(/thumbnails/)) atemp.setStyle('background-image', 'url(' + this.imgs[i].src + ')');
if(i === 0) a.className = this.options.classes[2];
atemp.onclick = function(i) {
if(fast || $time() > this.timer[1]) {
$clear(this.timeout);
if (fast) {
this.fx.each(function(fx) {
fx.time = 0;
fx.options.duration = 0;
fx.stop(true);
});
}
this.direction = (i < this.curr[0] || this.curr[0] === 0) ? 'right' : 'left';
this.curr[0] = i;
this.timer = [0];
this.loader = this.imgs[this.curr[0]];
this.load(fast);
}
}.pass(i, this);
this.ul.adopt(li.clone().adopt(atemp));
}
}
if (this.options.navigation.test(/arrows/)) {
this.ul.adopt(li.clone()
.adopt(a.clone()
.addClass(this.options.classes[1])
.addEvent('click', function() {
if (fast || $time() > this.timer[1]) {
$clear(this.timeout);
// Clear the FX array only for fast navigation since this stops combo effects
if (fast) {
this.fx.each(function(fx) {
fx.time = 0;
fx.options.duration = 0;
fx.stop(true);
});
}
this.timer = [0];
this.load(fast);
}
}.bind(this))
)
);
}
this.ul.injectInside(this.el);
},
onClick: function(e) {
e = new Event(e).stop();
var cur = this.curr[1] % this.imgs.length;
var index = this.curr[1] == 0 ? 1 : cur == 0 ? this.imgs.length : cur;
var url = this.options.images[index - 1].url;
if(url == '#' || url == '') return;
window.location.href = url;
},
mask: function(val, set, lower, higher) {
if(val != 'rand') {
val = val.toInt();
val = isNaN(val) || val < lower || val > higher ? set : val;
}
return val;
},
resize: function(obj, to) {
var n;
if(this.options.resize) {
n = Math.max(this.width / to.width, this.height / to.height);
obj.setStyles({
height: Math.ceil(to.height*n),
width: Math.ceil(to.width*n)
});
}
}
});
Slideshow.implement(new Options);
/**
*
*
*
*/
var ImageLoader = new Class({
version:'.5-olmo-ver',
options: {
loadingDiv : false,
loadingPrefix : 'loading images: ',
loadingSuffix : '',
path : '',
removeDiv : true
},
initialize: function(container, sources, options){
this.setOptions(options);
this.loadingDiv = (this.options.loadingDiv) ? $(container) : false;
this.images = [];
this.index = 0;
this.total = sources.length;
if(this.loadingDiv) {
this.loadingText = new Element('div').injectInside(this.loadingDiv);
this.progressBar = new Element('div', {
styles: {
width: 100,
padding: 1,
margin: '5px auto',
textAlign: 'left',
overflow: 'hidden',
border: 'solid 1px #333'
}
}).adopt(new Element('div', {
styles: {
width: '0%',
height: 10,
backgroundColor: '#333'
}
})).injectInside(this.loadingDiv);
}
this.loadImages.delay(200, this, [sources]);
},
reset: function() {
this.index = 0;
if(this.loadingDiv) {
this.progressBar.getFirst().setStyle('width', '0%');
this.loadingText.setHTML(this.options.loadingPrefix);
}
},
loadImages: function(sources) {
var self = this;
this.reset();
this.images = [];
this.sources = sources;
this.timer = setInterval(this.loadProgress.bind(this), 100);
for(var i = 0, j = sources.length; i < j; i++) {
this.images[i] = new Asset.image((this.sources[i].path || this.options.path) + this.sources[i].file, {
title: self.sources[i].title,
alt: self.sources[i].desc,
'onload' : function(){ self.index++; },
'onerror' : function(){ self.index++; self.images.splice(i,1); },
'onabort' : function(){ self.index++; self.images.splice(i,1); }
});
}
},
loadProgress: function() {
if(this.loadingDiv) {
this.loadingText.setHTML(this.options.loadingPrefix + this.index + '/' + this.total + this.options.loadingSuffix);
this.progressBar.getFirst().setStyle('width', (!this.total ? 0 : this.index.toInt()*100 / this.total) + '%');
}
if(this.index >= this.total) {
this.loadComplete();
}
},
loadComplete: function(){
$clear(this.timer);
if(this.loadingDiv) {
this.loadingText.setHTML('Loading Complete');
if(this.options.removeDiv) {
this.loadingText.empty().remove();
this.progressBar.empty().remove();
}
}
this.fireEvent('onComplete', this.images);
},
cancel: function(){
$clear(this.timer);
}
});
ImageLoader.implement(new Events, new Options);

If the slider stops on mouseover event, you can try:
$('#sliderSelector').mouseover(function (event) {
event.stopPropagation();
event.preventDefault();
});
or:
$('#sliderSelector').mouseover(function () {
return false;
});
If the function in the plugin is only stoping the slider, then it should work. If there's more behind it will probably fail.
If this is not working: can you provide plugin code? (I coudnt't find it using google)

Related

Rater.js - Half stars instead of full stars for progress

Hy there! I plan to use Rater.js in my project and so far I am happy with the library. There is only one issue I can't resolve alone. Pls. take a look at
https://jsfiddle.net/herbert_hinterberger/r1cgnpt3/.
At the very bottom of the script, I defined step_size: 1.
(".rating").rate();
//or for example
var options = {
max_value: 5,
step_size: 1,
}
Now I would expect that when I hover over the stars, only full stars are selected. But still, half stars are selected too. Any Idea what I a doing wrong?
In your example code, you are calling $(".rating").rate(); without options (line number 499).
After commenting it, you will end-up with something like below
/*
* A highly customizable rating widget that supports images, utf8 glyphs and other html elements!
* https://github.com/auxiliary/rater
*/
; (function ($, window) {
$.fn.textWidth = function () {
var html_calc = $('<span>' + $(this).html() + '</span>');
html_calc.css('font-size', $(this).css('font-size')).hide();
html_calc.prependTo('body');
var width = html_calc.width();
html_calc.remove();
if (width == 0) {
var total = 0;
$(this).eq(0).children().each(function () {
total += $(this).textWidth();
});
return total;
}
return width;
};
$.fn.textHeight = function () {
var html_calc = $('<span>' + $(this).html() + '</span>');
html_calc.css('font-size', $(this).css('font-size')).hide();
html_calc.prependTo('body');
var height = html_calc.height();
html_calc.remove();
return height;
};
/*
* IE8 doesn't support isArray!
*/
Array.isArray = function (obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
/*
* Utf-32 isn't supported by default, so we have to use Utf-8 surrogates
*/
String.prototype.getCodePointLength = function () {
return this.length - this.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g).length + 1;
};
String.fromCodePoint = function () {
var chars = Array.prototype.slice.call(arguments);
for (var i = chars.length; i-- > 0;) {
var n = chars[i] - 0x10000;
if (n >= 0)
chars.splice(i, 1, 0xD800 + (n >> 10), 0xDC00 + (n & 0x3FF));
}
return String.fromCharCode.apply(null, chars);
};
/*
* Starting the plugin itself
*/
$.fn.rate = function (options) {
if (options === undefined || typeof options === 'object') {
return this.each(function () {
if (!$.data(this, "rate")) {
$.data(this, "rate", new Rate(this, options));
}
});
}
else if (typeof options === 'string') {
var args = arguments;
var returns;
this.each(function () {
var instance = $.data(this, "rate");
if (instance instanceof Rate && typeof instance[options] === 'function') {
returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
}
if (options === 'destroy') {
// Unbind all events and empty the plugin data from instance
$(instance.element).off();
$.data(this, 'rate', null);
}
});
return returns !== undefined ? returns : this;
}
};
function Rate(element, options) {
this.element = element;
this.settings = $.extend({}, $.fn.rate.settings, options);
this.set_faces = {}; // value, symbol pairs
this.build();
}
Rate.prototype.build = function () {
this.layers = {};
this.value = 0;
this.raise_select_layer = false;
if (this.settings.initial_value) {
this.value = this.settings.initial_value;
}
if ($(this.element).attr("data-rate-value")) {
this.value = $(this.element).attr("data-rate-value");
}
/*
* Calculate the selected width based on the initial value
*/
var selected_width = this.value / this.settings.max_value * 100;
/*
* Let's support single strings as symbols as well as objects
*/
if (typeof this.settings.symbols[this.settings.selected_symbol_type] === 'string') {
var symbol = this.settings.symbols[this.settings.selected_symbol_type];
this.settings.symbols[this.settings.selected_symbol_type] = {};
this.settings.symbols[this.settings.selected_symbol_type]['base'] = symbol;
this.settings.symbols[this.settings.selected_symbol_type]['selected'] = symbol;
this.settings.symbols[this.settings.selected_symbol_type]['hover'] = symbol;
}
/*
* Making the three main layers (base, select, hover)
*/
var base_layer = this.addLayer("base-layer", 100, this.settings.symbols[
this.settings.selected_symbol_type]["base"], true);
var select_layer = this.addLayer("select-layer", selected_width,
this.settings.symbols[this.settings.selected_symbol_type]["selected"], true);
var hover_layer = this.addLayer("hover-layer", 0, this.settings.symbols[
this.settings.selected_symbol_type]["hover"], false);
/* var face_layer = this.addLayer("face-layer", 1, this.settings
.symbols[this.settings.face_layer_symbol_type][0], true); */
this.layers["base_layer"] = base_layer;
this.layers["select_layer"] = select_layer;
this.layers["hover_layer"] = hover_layer;
/*
* Bind the container to some events
*/
$(this.element).on("mousemove", $.proxy(this.hover, this));
$(this.element).on("click", $.proxy(this.select, this));
$(this.element).on("mouseleave", $.proxy(this.mouseout, this));
/*
* Set the main element as unselectable
*/
$(this.element).css({
"-webkit-touch-callout": "none",
"-webkit-user-select": "none",
"-khtml-user-select": "none",
"-moz-user-select": "none",
"-ms-user-select": "none",
"user-select": "none",
});
/*
* Update custom input field if provided
*/
if (this.settings.hasOwnProperty("update_input_field_name")) {
this.settings.update_input_field_name.val(this.value);
}
}
/*
* Function to add a layer
*/
Rate.prototype.addLayer = function (layer_name, visible_width, symbol, visible) {
var layer_body = "<div>";
for (var i = 0; i < this.settings.max_value; i++) {
if (Array.isArray(symbol)) {
if (this.settings.convert_to_utf8) {
symbol[i] = String.fromCodePoint(symbol[i]);
}
layer_body += "<span>" + (symbol[i]) + "</span>";
}
else {
if (this.settings.convert_to_utf8) {
symbol = String.fromCodePoint(symbol);
}
layer_body += "<span>" + symbol + "</span>";
}
}
layer_body += "</div>";
var layer = $(layer_body).addClass("rate-" + layer_name).appendTo(this.element);
$(layer).css({
width: visible_width + "%",
height: $(layer).children().eq(0).textHeight(),
overflow: 'hidden',
position: 'absolute',
top: 0,
display: visible ? 'block' : 'none',
'white-space': 'nowrap'
});
$(this.element).css({
width: $(layer).textWidth() + "px",
height: $(layer).height(),
position: 'relative',
cursor: this.settings.cursor,
});
return layer;
}
Rate.prototype.updateServer = function () {
if (this.settings.url != undefined) {
$.ajax({
url: this.settings.url,
type: this.settings.ajax_method,
data: $.extend({}, { value: this.getValue() }, this.settings.additional_data),
success: $.proxy(function (data) {
$(this.element).trigger("updateSuccess", [data]);
}, this),
error: $.proxy(function (jxhr, msg, err) {
$(this.element).trigger("updateError", [jxhr, msg, err]);
}, this)
});
}
}
Rate.prototype.getValue = function () {
return this.value;
}
Rate.prototype.hover = function (ev) {
var pad = parseInt($(this.element).css("padding-left").replace("px", ""));
var x = ev.pageX - $(this.element).offset().left - pad;
var val = this.toValue(x, true);
if (val != this.value) {
this.raise_select_layer = false;
}
if (!this.raise_select_layer && !this.settings.readonly) {
var visible_width = this.toWidth(val);
this.layers.select_layer.css({ display: 'none' });
if (!this.settings.only_select_one_symbol) {
this.layers.hover_layer.css({
width: visible_width + "%",
display: 'block'
});
}
else {
var index_value = Math.floor(val);
this.layers.hover_layer.css({
width: "100%",
display: 'block'
});
this.layers.hover_layer.children("span").css({
visibility: 'hidden',
});
this.layers.hover_layer.children("span").eq(index_value != 0 ? index_value - 1 : 0).css({
visibility: 'visible',
});
}
}
}
/*
* Event for when a rating has been selected (clicked)
*/
Rate.prototype.select = function (ev) {
if (!this.settings.readonly) {
var old_value = this.getValue();
var pad = parseInt($(this.element).css("padding-left").replace("px", ""));
var x = ev.pageX - $(this.element).offset().left - pad;
var selected_width = this.toWidth(this.toValue(x, true));
this.setValue(this.toValue(selected_width));
this.raise_select_layer = true;
}
}
Rate.prototype.mouseout = function () {
this.layers.hover_layer.css({ display: 'none' });
this.layers.select_layer.css({ display: 'block' });
}
/*
* Takes a width (px) and returns the value it resembles
*/
Rate.prototype.toWidth = function (val) {
return val / this.settings.max_value * 100;
}
/*
* Takes a value and calculates the width of the selected/hovered layer
*/
Rate.prototype.toValue = function (width, in_pixels) {
var val;
if (in_pixels) {
val = width / this.layers.base_layer.textWidth() * this.settings.max_value;
}
else {
val = width / 100 * this.settings.max_value;
}
// Make sure the division doesn't cause some small numbers added by
// comparing to a small arbitrary number.
var temp = val / this.settings.step_size;
if (temp - Math.floor(temp) < 0.00005) {
val = Math.round(val / this.settings.step_size) * this.settings.step_size;
}
val = (Math.ceil(val / this.settings.step_size)) * this.settings.step_size;
val = val > this.settings.max_value ? this.settings.max_value : val;
return val;
}
Rate.prototype.getElement = function (layer_name, index) {
return $(this.element).find(".rate-" + layer_name + " span").eq(index - 1);
}
Rate.prototype.getLayers = function () {
return this.layers;
}
Rate.prototype.setFace = function (value, face) {
this.set_faces[value] = face;
}
Rate.prototype.setAdditionalData = function (data) {
this.settings.additional_data = data;
}
Rate.prototype.getAdditionalData = function () {
return this.settings.additional_data;
}
Rate.prototype.removeFace = function (value) {
delete this.set_faces[value];
}
Rate.prototype.setValue = function (value) {
if (!this.settings.readonly) {
if (value < 0) {
value = 0;
}
else if (value > this.settings.max_value) {
value = this.settings.max_value;
}
var old_value = this.getValue();
this.value = value;
/*
* About to change event, should support prevention later
*/
var change_event = $(this.element).trigger("change", {
"from": old_value,
"to": this.value
});
/*
* Set/Reset faces
*/
$(this.element).find(".rate-face").remove();
$(this.element).find("span").css({
visibility: 'visible'
});
var index_value = Math.ceil(this.value);
if (this.set_faces.hasOwnProperty(index_value)) {
var face = "<div>" + this.set_faces[index_value] + "</div>";
var base_layer_element = this.getElement('base-layer', index_value);
var select_layer_element = this.getElement('select-layer', index_value);
var hover_layer_element = this.getElement('hover-layer', index_value);
var left_pos = base_layer_element.textWidth() * (index_value - 1)
+ (base_layer_element.textWidth() - $(face).textWidth()) / 2;
$(face).appendTo(this.element).css({
display: 'inline-block',
position: 'absolute',
left: left_pos,
}).addClass("rate-face");
base_layer_element.css({
visibility: 'hidden'
});
select_layer_element.css({
visibility: 'hidden'
});
hover_layer_element.css({
visibility: 'hidden'
});
}
/*
* Set styles based on width and value
*/
if (!this.settings.only_select_one_symbol) {
var width = this.toWidth(this.value);
this.layers.select_layer.css({
display: 'block',
width: width + "%",
height: this.layers.base_layer.css("height")
});
this.layers.hover_layer.css({
display: 'none',
height: this.layers.base_layer.css("height")
});
}
else {
var width = this.toWidth(this.settings.max_value);
this.layers.select_layer.css({
display: 'block',
width: width + "%",
height: this.layers.base_layer.css("height")
});
this.layers.hover_layer.css({
display: 'none',
height: this.layers.base_layer.css("height")
});
this.layers.select_layer.children("span").css({
visibility: 'hidden',
});
this.layers.select_layer.children("span").eq(index_value != 0 ? index_value - 1 : 0).css({
visibility: 'visible',
});
}
// Update the data-rate-value attribute
$(this.element).attr("data-rate-value", this.value);
if (this.settings.change_once) {
this.settings.readonly = true;
}
this.updateServer();
/*
* After change event
*/
var change_event = $(this.element).trigger("afterChange", {
"from": old_value,
"to": this.value
});
/*
* Update custom input field if provided
*/
if (this.settings.hasOwnProperty("update_input_field_name")) {
this.settings.update_input_field_name.val(this.value);
}
}
}
Rate.prototype.increment = function () {
this.setValue(this.getValue() + this.settings.step_size);
}
Rate.prototype.decrement = function () {
this.setValue(this.getValue() - this.settings.step_size);
}
$.fn.rate.settings = {
max_value: 5,
step_size: 0.5,
initial_value: 0,
symbols: {
utf8_star: {
base: '\u2606',
hover: '\u2605',
selected: '\u2605',
},
utf8_hexagon: {
base: '\u2B21',
hover: '\u2B22',
selected: '\u2B22',
},
hearts: '♥',
fontawesome_beer: '<i class="fa fa-beer"></i>',
fontawesome_star: {
base: '<i class="fa fa-star-o"></i>',
hover: '<i class="fa fa-star"></i>',
selected: '<i class="fa fa-star"></i>',
},
utf8_emoticons: {
base: [0x1F625, 0x1F613, 0x1F612, 0x1F604],
hover: [0x1F625, 0x1F613, 0x1F612, 0x1F604],
selected: [0x1F625, 0x1F613, 0x1F612, 0x1F604],
},
},
selected_symbol_type: 'utf8_star', // Must be a key from symbols
convert_to_utf8: false,
cursor: 'default',
readonly: false,
change_once: false, // Determines if the rating can only be set once
only_select_one_symbol: false, // If set to true, only selects the hovered/selected symbol and nothing prior to it
ajax_method: 'POST',
additional_data: {}, // Additional data to send to the server
//update_input_field_name = some input field set by the user
};
}(jQuery, window));
//$(".rating").rate();
//or for example
var options = {
max_value: 5,
step_size: 1,
}
$(".rating").rate(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rating" data-rate-value=6></div>
You are specifying the options at an earlier stage in your code.
See here:
$.fn.rate.settings = {
max_value: 5,
step_size: 0.5,
I tested in your fiddle and it works when updated to 1 step_size.

How to draw an 1/16th inch by 1/16th inch grid using FabricJS

I'm integrating FabricJS into my angular application. I've managed to get the canvas down and automatically adding a figure into the canvas.
My goals are to make the figure 8inches by 8inches and to add a grid that has dynamic grid height and width (lets say 1/16th inch x 1/16inch).
Here are my problems:
1. When adding the figure, I cannot set the figure height and width in inches. I can only use a number. How can I use a different unit for this? I used cssOnly: true for the canvas but I cant seem to figure it out for the figure.
addFigure(figure) {
let add: any;
switch (figure) {
case 'rectangle':
add = new fabric.Rect({
width: 500, height: 500, left: 150, top: 10, angle: 0, opacity: .3,
fill: '#3f51b5'
});
break;
case 'square':
add = new fabric.Rect({
width: 200, height: 200, left: 0, top: 0, angle: 0, opacity: .15,
fill: '#4caf50'
});
break;
case 'triangle':
add = new fabric.Triangle({
width: 100, height: 100, left: 10, top: 10, fill: '#2196f3'
});
break;
case 'circle':
add = new fabric.Circle({
radius: 50, left: 10, top: 10, fill: '#ff5722'
});
break;
}
this.extend(add, this.randomId());
console.log(add);
this.canvas.add(add);
// this.selectItemAfterAdded(add);
}
The figure height displays 200 but it appears incorrect. Here is an example of the above figure as a square. Notice the 200 width is correct but the height does not seem right seeing as the canvas is 6inches by 6inches. The height extends pass the bottom of the canvas.
Notice the grid above. Im having the same problem. Here is my code for grid which I pulled from Adding grid over Fabric.js canvas . The problem I'm having is I have no idea how to make this grid evenly 1/16th inch 1/16th inch given this is an 8in by 8in canvas.
onst gridGroup = new fabric.Group([], {left: 0, top: 0});
const gridSize = 16;
const gridWidth = 400;
const gridHeight = 400;
const lineOption = {stroke: 'rgba(0,0,0,.4)', strokeWidth: 1, selectable: false, strokeDashArray: [3, 3]};
for (let i = Math.ceil(gridWidth / gridSize); i--;) {
this.canvas.add( new fabric.Line([gridSize * i, 0, gridSize * i, gridHeight], lineOption) );
}
for (let i = Math.ceil(gridHeight / gridSize); i--;) {
this.canvas.add( new fabric.Line([0, gridSize * i, gridWidth, gridSize * i], lineOption) );
}
this.canvas.add(gridGroup);
Here is the entire component for review. Is there something I'm doing wrong in the setup?
// private canvas: any;
uploading = false;
uploaded = false;
pdfUrl = '';
canvas: any;
props: any = {
canvasFill: '#ffffff',
canvasImage: '',
id: null,
opacity: null,
fill: null,
fontSize: null,
lineHeight: null,
charSpacing: null,
fontWeight: null,
fontStyle: null,
textAlign: null,
fontFamily: null,
TextDecoration: ''
};
textString: string;
url = '';
size: any = {
width: '6in',
height: '6in'
};
json: any;
globalEditor = false;
textEditor = false;
imageEditor = false;
figureEditor = false;
selected: any;
constructor(
private router: Router,
private userService: UserService,
private fileService: FileService
) { }
ngOnInit() {
this.getActive();
// this.activateCanvas();
//setup front side canvas
this.canvas = new fabric.Canvas('canvas', {
hoverCursor: 'pointer',
selection: true,
selectionBorderColor: 'blue'
});
this.canvas.on({
'object:moving': (e) => { },
'object:modified': (e) => { },
'object:selected': (e) => {
const selectedObject = e.target;
this.selected = selectedObject
selectedObject.hasRotatingPoint = true;
selectedObject.transparentCorners = false;
// selectedObject.cornerColor = 'rgba(255, 87, 34, 0.7)';
this.resetPanels();
if (selectedObject.type !== 'group' && selectedObject) {
this.getId();
this.getOpacity();
switch (selectedObject.type) {
case 'rect':
case 'circle':
case 'triangle':
this.figureEditor = true;
this.getFill();
break;
case 'i-text':
this.textEditor = true;
this.getLineHeight();
this.getCharSpacing();
this.getBold();
this.getFontStyle();
this.getFill();
this.getTextDecoration();
this.getTextAlign();
this.getFontFamily();
break;
case 'image':
break;
}
}
},
'selection:cleared': (e) => {
this.selected = null;
this.resetPanels();
}
});
this.canvas.setWidth(this.size.width, {cssOnly: true});
this.canvas.setHeight(this.size.height, {cssOnly: true});
this.addFigure('square');
const gridGroup = new fabric.Group([], {left: 0, top: 0});
const gridSize = 16;
const gridWidth = 400;
const gridHeight = 400;
const lineOption = {stroke: 'rgba(0,0,0,.4)', strokeWidth: 1, selectable: false, strokeDashArray: [3, 3]};
for (let i = Math.ceil(gridWidth / gridSize); i--;) {
this.canvas.add( new fabric.Line([gridSize * i, 0, gridSize * i, gridHeight], lineOption) );
}
for (let i = Math.ceil(gridHeight / gridSize); i--;) {
this.canvas.add( new fabric.Line([0, gridSize * i, gridWidth, gridSize * i], lineOption) );
}
this.canvas.add(gridGroup);
// for ( let x = 1; x < ( this.canvas.width / gridsize); x++) {
// this.canvas.add(new fabric.Line([cellWidth * x, 0, cellWidth * x, 800],
// { stroke: '#000000', strokeWidth: 1, selectable: false}));
// this.canvas.add(new fabric.Line([0, cellWidth * x, 800, cellWidth * x],
// { stroke: '#000000', strokeWidth: 1, selectable: false}));
// }
// get references to the html canvas element & its context
// this.canvas.on('mouse:down', (e) => {
// let canvasElement: any = document.getElementById('canvas');
// console.log(canvasElement)
// });
}
/*------------------------Block elements------------------------*/
//Block "Size"
changeSize(event: any) {
this.canvas.setWidth(this.size.width);
this.canvas.setHeight(this.size.height);
}
//Block "Add text"
addText() {
let textString = this.textString;
let text = new fabric.IText(textString, {
left: 10,
top: 10,
fontFamily: 'helvetica',
angle: 0,
fill: '#000000',
scaleX: 0.5,
scaleY: 0.5,
fontWeight: '',
hasRotatingPoint: true
});
this.extend(text, this.randomId());
this.canvas.add(text);
this.selectItemAfterAdded(text);
this.textString = '';
}
//Block "Add images"
getImgPolaroid(event: any) {
let el = event.target;
fabric.Image.fromURL(el.src, (image) => {
image.set({
left: 10,
top: 10,
angle: 0,
padding: 10,
cornersize: 10,
hasRotatingPoint: true,
peloas: 12
});
// image.setWidth(150);
// image.setHeight(150);
this.extend(image, this.randomId());
this.canvas.add(image);
this.selectItemAfterAdded(image);
});
}
//Block "Upload Image"
addImageOnCanvas(url) {
if (url) {
fabric.Image.fromURL(url, (image) => {
image.set({
left: 10,
top: 10,
angle: 0,
// scaleX: 200,
// scaleY: 200,
padding: 10,
cornersize: 10,
hasRotatingPoint: true
});
image.scale(0.2);
// image.setWidth(200);
// image.height = 200;
// image.width = 200;
this.extend(image, this.randomId());
this.canvas.add(image);
this.selectItemAfterAdded(image);
});
}
}
readUrl(event) {
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.onload = (e) => {
this.url = e.target['result'];
};
reader.readAsDataURL(event.target.files[0]);
}
}
removeWhite(url) {
this.url = '';
}
//Block "Add figure"
addFigure(figure) {
let add: any;
switch (figure) {
case 'rectangle':
add = new fabric.Rect({
width: 500, height: 500, left: 150, top: 10, angle: 0, opacity: .3,
fill: '#3f51b5'
});
break;
case 'square':
add = new fabric.Rect({
width: 200, height: 200, left: 0, top: 0, angle: 0, opacity: .4,
fill: '#4caf50'
});
break;
case 'triangle':
add = new fabric.Triangle({
width: 100, height: 100, left: 10, top: 10, fill: '#2196f3'
});
break;
case 'circle':
add = new fabric.Circle({
radius: 50, left: 10, top: 10, fill: '#ff5722'
});
break;
}
this.extend(add, this.randomId());
console.log(add);
this.canvas.add(add);
// this.selectItemAfterAdded(add);
}
/*Canvas*/
cleanSelect() {
this.canvas.discardActiveObject();
}
selectItemAfterAdded(obj) {
this.canvas.discardActiveObject();
this.canvas.setActiveObject(obj);
}
setCanvasFill() {
if (!this.props.canvasImage) {
this.canvas.backgroundColor = this.props.canvasFill;
this.canvas.renderAll();
}
}
extend(obj, id) {
obj.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
id: id
});
};
})(obj.toObject);
}
setCanvasImage() {
let self = this;
if (this.props.canvasImage) {
this.canvas.setBackgroundColor({ source: this.props.canvasImage, repeat: 'repeat' }, function () {
// self.props.canvasFill = '';
self.canvas.renderAll();
});
}
}
randomId() {
return Math.floor(Math.random() * 999999) + 1;
}
/*------------------------Global actions for element------------------------*/
getActiveStyle(styleName, object) {
object = object || this.canvas.getActiveObject();
if (!object) {return '';}
return (object.getSelectionStyles && object.isEditing)
? (object.getSelectionStyles()[styleName] || '')
: (object[styleName] || '');
}
setActiveStyle(styleName, value, object) {
object = object || this.canvas.getActiveObject();
if (!object) {return '';}
if (object.setSelectionStyles && object.isEditing) {
let style = {};
style[styleName] = value;
object.setSelectionStyles(style);
object.setCoords();
} else {
object.set(styleName, value);
}
object.setCoords();
this.canvas.renderAll();
}
getActiveProp(name) {
let object = this.canvas.getActiveObject();
if (!object) {return '';}
return object[name] || '';
}
setActiveProp(name, value) {
const object = this.canvas.getActiveObject();
if (!object) {return ''};
object.set(name, value).setCoords();
this.canvas.renderAll();
}
clone() {
const activeObject = this.canvas.getActiveObject(),
activeGroup = this.canvas.getActiveGroup();
if (activeObject) {
let clone;
switch (activeObject.type) {
case 'rect':
clone = new fabric.Rect(activeObject.toObject());
break;
case 'circle':
clone = new fabric.Circle(activeObject.toObject());
break;
case 'triangle':
clone = new fabric.Triangle(activeObject.toObject());
break;
case 'i-text':
clone = new fabric.IText('', activeObject.toObject());
break;
case 'image':
clone = fabric.util.object.clone(activeObject);
break;
}
if (clone) {
clone.set({ left: 10, top: 10 });
this.canvas.add(clone);
this.selectItemAfterAdded(clone);
}
}
}
getId() {
this.props.id = this.canvas.getActiveObject().toObject().id;
}
setId() {
const val = this.props.id;
const complete = this.canvas.getActiveObject().toObject();
console.log(complete);
this.canvas.getActiveObject().toObject = () => {
complete.id = val;
return complete;
};
}
getOpacity() {
this.props.opacity = this.getActiveStyle('opacity', null) * 100;
}
setOpacity() {
this.setActiveStyle('opacity', +this.props.opacity / 100, null);
}
getFill() {
this.props.fill = this.getActiveStyle('fill', null);
}
setFill() {
this.setActiveStyle('fill', this.props.fill, null);
}
getLineHeight() {
this.props.lineHeight = this.getActiveStyle('lineHeight', null);
}
setLineHeight() {
this.setActiveStyle('lineHeight', parseFloat(this.props.lineHeight), null);
}
getCharSpacing() {
this.props.charSpacing = this.getActiveStyle('charSpacing', null);
}
setCharSpacing() {
this.setActiveStyle('charSpacing', this.props.charSpacing, null);
}
getFontSize() {
this.props.fontSize = this.getActiveStyle('fontSize', null);
}
setFontSize() {
this.setActiveStyle('fontSize', +this.props.fontSize, null);
}
getBold() {
this.props.fontWeight = this.getActiveStyle('fontWeight', null);
}
setBold() {
this.props.fontWeight = !this.props.fontWeight;
this.setActiveStyle('fontWeight', this.props.fontWeight ? 'bold' : '', null);
}
getFontStyle() {
this.props.fontStyle = this.getActiveStyle('fontStyle', null);
}
setFontStyle() {
this.props.fontStyle = !this.props.fontStyle;
this.setActiveStyle('fontStyle', this.props.fontStyle ? 'italic' : '', null);
}
getTextDecoration() {
this.props.TextDecoration = this.getActiveStyle('textDecoration', null);
}
setTextDecoration(value) {
let iclass = this.props.TextDecoration;
if (iclass.includes(value)) {
iclass = iclass.replace(RegExp(value, 'g'), '');
} else {
iclass += ` ${value}`
}
this.props.TextDecoration = iclass;
this.setActiveStyle('textDecoration', this.props.TextDecoration, null);
}
hasTextDecoration(value) {
return this.props.TextDecoration.includes(value);
}
getTextAlign() {
this.props.textAlign = this.getActiveProp('textAlign');
}
setTextAlign(value) {
this.props.textAlign = value;
this.setActiveProp('textAlign', this.props.textAlign);
}
getFontFamily() {
this.props.fontFamily = this.getActiveProp('fontFamily');
}
setFontFamily() {
this.setActiveProp('fontFamily', this.props.fontFamily);
}
/*System*/
removeSelected() {
let activeObject = this.canvas.getActiveObject(),
activeGroup = this.canvas.getActiveGroup();
if (activeObject) {
this.canvas.remove(activeObject);
// this.textString = '';
} else if (activeGroup) {
let objectsInGroup = activeGroup.getObjects();
this.canvas.discardActiveGroup();
let self = this;
objectsInGroup.forEach(function (object) {
self.canvas.remove(object);
});
}
}
bringToFront() {
let activeObject = this.canvas.getActiveObject(),
activeGroup = this.canvas.getActiveGroup();
if (activeObject) {
activeObject.bringToFront();
// activeObject.opacity = 1;
}
else if (activeGroup) {
let objectsInGroup = activeGroup.getObjects();
this.canvas.discardActiveGroup();
objectsInGroup.forEach((object) => {
object.bringToFront();
});
}
}
sendToBack() {
const activeObject = this.canvas.getActiveObject(),
activeGroup = this.canvas.getActiveGroup();
if (activeObject) {
activeObject.sendToBack();
// activeObject.opacity = 1;
} else if (activeGroup) {
const objectsInGroup = activeGroup.getObjects();
this.canvas.discardActiveGroup();
objectsInGroup.forEach((object) => {
object.sendToBack();
});
}
}
confirmClear() {
if (confirm('Are you sure?')) {
this.canvas.clear();
}
}
rasterize() {
if (!fabric.Canvas.supports('toDataURL')) {
alert('This browser doesn\'t provide means to serialize canvas to an image');
} else {
console.log(this.canvas.toDataURL('png'))
//window.open(this.canvas.toDataURL('png'));
let image = new Image();
image.src = this.canvas.toDataURL('png')
let w = window.open('');
w.document.write(image.outerHTML);
}
}
rasterizeSVG() {
console.log(this.canvas.toSVG())
// window.open(
// 'data:image/svg+xml;utf8,' +
// encodeURIComponent(this.canvas.toSVG()));
// console.log(this.canvas.toSVG())
// let image = new Image();
// image.src = this.canvas.toSVG()
const w = window.open('');
w.document.write(this.canvas.toSVG());
}
saveCanvasToJSON() {
const json = JSON.stringify(this.canvas);
localStorage.setItem('Kanvas', json);
console.log('json');
console.log(json);
}
loadCanvasFromJSON() {
const CANVAS = localStorage.getItem('Kanvas');
console.log('CANVAS');
console.log(CANVAS);
// and load everything from the same json
this.canvas.loadFromJSON(CANVAS, () => {
console.log('CANVAS untar');
console.log(CANVAS);
// making sure to render canvas at the end
this.canvas.renderAll();
// and checking if object's "name" is preserved
console.log('this.canvas.item(0).name');
console.log(this.canvas);
});
}
rasterizeJSON() {
this.json = JSON.stringify(this.canvas, null, 2);
}
resetPanels() {
this.textEditor = false;
this.imageEditor = false;
this.figureEditor = false;
}
In summary, I'm looking to use a 1/16th inch x 1/16th inch (possibly dynamic) grid on an 8inch by 8inch canvas and add a figure that is also an even square inside this canvas.
For anyone having this same problem. It seems that the cssOnly boolean param option Im passing is not a solution for actually scaling the canvas to inches.
Here's how I resolved.
1) I now have an input that allows the user to manually enter in their PPI given the information on this url - http://dpi.lv/
2) I save that PPI
3) I created a method calcPixels(inches: number) which uses pixels = inches * ppi to calculate the number of pixels needed
4) I use that method across the application for all widths, heights, grid lines and etc.
This gives me a to scale 7in by 7inch grid line. Its a little less automated but if you save the PPI, the user only has to enter it once!
New result

Uncaught type error: .vegas is not a function

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.

Fullpage jquery navigation

Good day guys. I got a small question here.
kindly check this link
http://www.thepetedesign.com/demos/fullpagenav_demo.html
How can I make the transition of hovering out be more smoother more like this
http://outdatedbrowser.com/
I'm a designer and know just a tiny bit about jquery but I think the smoothness can be inserted here?
.mouseleave(function() {
if (!li.find(".fpn_wrap").hasClass("fpn_clicked")) {
$(this).removeClass("active")
el.recalculate(settings, width);
el.find(".fpn_wrap").finish().css({width: "100%"})
}
});
here's the full code
!function($){
var defaults = {
columns: 5,
selector: "> li",
hover_size: "30%",
animateDuration: 500,
animateFrom: "left",
clickable: true,
afterClicked: null
};
$.fn.recalculate = function(settings, width) {
var el = $(this),
active = false,
total = el.find(settings.selector).length,
last_pos = 0,
total_width = 0;
if(el.find(".fpn_li.active").length > 0) {
el.find(".fpn_li.active").css({
width: settings.hover_size
});
var small_width = (100 - parseFloat(settings.hover_size))/(settings.columns - 1)
el.find(".fpn_li:not(.active)").css({
width: small_width + "%"
});
el.find(settings.selector).each(function( index, value ) {
if ($(this).prev(".fpn_li").length > 0) {
if($(this).prev(".fpn_li").hasClass("active")) {
var w = settings.hover_size
} else {
var w = small_width
}
var left = total_width + parseFloat(w)
$(this).finish().animate({
left: left + "%"
}, settings.animateDuration, function() {
$(this).css({
left: left + "%"
});
})
total_width = total_width + parseFloat(w)
}
});
} else {
el.find(settings.selector).each(function( index, value ) {
$(this).finish().animate({
width: width + "%",
left: (width * index) + "%"
}, settings.animateDuration);
});
}
}
function determineDirection($el, pos){
var w = $el.width(),
middle = $el.offset().left + w/2;
return (pos.pageX > middle ? 0 : 1);
}
$.fn.fullpagenav = function(options){
var settings = $.extend({}, defaults, options),
el = $(this),
width = 100 / settings.columns;
el.addClass("fullpagenav").find(settings.selector).addClass("fpn_li")
el.parent().addClass("fpn_body")
el.find(settings.selector).each(function( index, value ) {
var li = $(this);
li.css({
width: width + "%",
left: (width * index) + "%"
});
li.wrapInner("<div class='fpn_wrap'></div>")
if (settings.clickable == true && li.data("link")) {
li.css({cursor: "pointer"}).click(function(e) {
if (!li.find(".fpn_wrap").hasClass("fpn_clicked")) {
li.find(".fpn_wrap > img").css({
margin: 0,
padding: 0,
left: 0,
maxHeight: "inherit"
}).animate({
width: "100%"
})
li.find(".fpn_wrap").addClass("fpn_clicked").css({position: "fixed", "z-index": 99}).finish().animate({
width: "100%", top: 0, left: 0
}, settings.animationDuration, function() {
e.preventDefault()
if (typeof settings.afterClicked == 'function') return settings.afterClicked(li.data("link"));
window.location.href = li.data("link");
});
} else {
li.find(".fpn_wrap").removeClass("fpn_clicked").finish().animate({
width: "0%", top: 0, left: 0, height: "0%"
}, settings.animationDuration, function() {
$(this).attr("style","").find("> img").attr("style","")
})
}
});
}
li.mouseenter(function(e) {
if (!li.find(".fpn_wrap").hasClass("fpn_clicked")) {
$(this).finish().addClass("active")
el.recalculate(settings, width);
if (settings.animateFrom == "auto") {
if(determineDirection(li, e) == 1) {
$(this).find(".fpn_wrap").finish().css({ float: "left"}).animate({width: el.find(".fpn_li.active").width()}, settings.animateDuration)
} else {
$(this).find(".fpn_wrap").finish().css({ float: "right"}).animate({width: el.find(".fpn_li.active").width()}, settings.animateDuration)
}
} else {
$(this).find(".fpn_wrap").finish().css({ float: settings.animateFrom}).animate({width: el.find(".fpn_li.active").width()}, settings.animateDuration)
}
}
}).mouseleave(function() {
if (!li.find(".fpn_wrap").hasClass("fpn_clicked")) {
$(this).removeClass("active")
el.recalculate(settings, width);
el.find(".fpn_wrap").finish().css({width: "100%"})
}
});
});
}
}(window.jQuery);
Thanks : )

JS carrousel stop when mouse over

I run a real estate site and I have a property carrousel, I would like to modify this JS in order to stop the carrousel when user over with mouse.
Code:
var Ticker = new Class({
setOptions: function (options) {
this.options = Object.extend({
speed: 5000,
delay: 5000,
direction: 'vertical',
onComplete: Class.empty,
onStart: Class.empty
}, options || {});
},
initialize: function (el, options) {
this.setOptions(options);
this.el = $(el);
this.items = this.el.getElements('li');
var w = 0;
var h = 0;
if (this.options.direction.toLowerCase() == 'horizontal') {
h = this.el.getSize().size.y;
this.items.each(function (li, index) {
w += li.getSize().size.x;
});
} else {
w = this.el.getSize().size.x;
this.items.each(function (li, index) {
h += li.getSize().size.y;
});
}
this.el.setStyles({
position: 'absolute',
top: 0,
left: 0,
width: w,
height: h
});
this.fx = new Fx.Styles(this.el, {
duration: this.options.speed,
onComplete: function () {
var i = (this.current == 0) ? this.items.length : this.current;
this.items[i - 1].injectInside(this.el);
this.el.setStyles({
left: 0,
top: 0
});
}.bind(this)
});
this.current = 0;
this.next();
},
next: function () {
this.current++;
if (this.current >= this.items.length) this.current = 0;
var pos = this.items[this.current];
this.fx.start({
top: -pos.offsetTop,
left: -pos.offsetLeft
});
this.next.bind(this).delay(this.options.delay + this.options.speed);
}
});
var hor = new Ticker('TickerVertical', {
speed: 1000,
delay: 4000,
direction: 'horizontal'
});
This version of mootools is really really old (1.1 isn't it? ) So the solution is something like this (not tested):
var Ticker = new Class({
setOptions: function (options) {
this.options = Object.extend({
speed: 5000,
delay: 5000,
direction: 'vertical',
onComplete: Class.empty,
onStart: Class.empty
}, options || {});
},
initialize: function (el, options) {
this.setOptions(options);
this.el = $(el);
//set a flag according to the mouse in/out events:
var self = this;
this.el.addEvents({
'mouseenter': function(){
self.elementHover = true;
},
'mouseleave': function(){
self.elementHover = false;
}
})
this.items = this.el.getElements('li');
var w = 0;
var h = 0;
if (this.options.direction.toLowerCase() == 'horizontal') {
h = this.el.getSize().size.y;
this.items.each(function (li, index) {
w += li.getSize().size.x;
});
} else {
w = this.el.getSize().size.x;
this.items.each(function (li, index) {
h += li.getSize().size.y;
});
}
this.el.setStyles({
position: 'absolute',
top: 0,
left: 0,
width: w,
height: h
});
this.fx = new Fx.Styles(this.el, {
duration: this.options.speed,
onComplete: function () {
var i = (this.current == 0) ? this.items.length : this.current;
this.items[i - 1].injectInside(this.el);
this.el.setStyles({
left: 0,
top: 0
});
}.bind(this)
});
this.current = 0;
this.next();
},
next: function () {
if(!this.elementHover){ //check here the flag mouse in/out
this.current++;
if (this.current >= this.items.length) this.current = 0;
var pos = this.items[this.current];
this.fx.start({
top: -pos.offsetTop,
left: -pos.offsetLeft
});
}
this.next.bind(this).delay(this.options.delay + this.options.speed);
}
});

Categories

Resources