Fullpage jquery navigation - javascript

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 : )

Related

Drawing rectangles on top of image R shiny

I'd like to elaborate on the accepted answer to this question.
I'm looking at improving the minimal shiny app below (extracted from the accepted answer) with the following features:
1) draw the rectangle + a text label. The label comes from R (input$foo), e.g., from a dropdown. To avoid the edge cases where the labels fall outside the images, labels should be placed inside their rectangles.
2) use a different color for the rectangles and their labels depending on the label
3) ability for the user to delete a rectangle by double-clicking inside it. In the case of multiple matches (overlap, nested), the rectangle with the smallest area should be deleted.
Brownie points for 1): the dropdown could appear next to the cursor like is done here (code here). If possible, the dropdown list should be passed from server.R and not be fixed/hardcoded. The reason is that depending on some user input, a different dropdown could be shown. E.g., we might have one dropdown for fruits c('banana','pineapple','grapefruit'), one dropdown for animals c('raccoon','dog','cat'), etc.
# JS and CSS modified from: https://stackoverflow.com/a/17409472/8099834
css <- "
#canvas {
width:2000px;
height:2000px;
border: 10px solid transparent;
}
.rectangle {
border: 5px solid #FFFF00;
position: absolute;
}
"
js <-
"function initDraw(canvas) {
var mouse = {
x: 0,
y: 0,
startX: 0,
startY: 0
};
function setMousePosition(e) {
var ev = e || window.event; //Moz || IE
if (ev.pageX) { //Moz
mouse.x = ev.pageX + window.pageXOffset;
mouse.y = ev.pageY + window.pageYOffset;
} else if (ev.clientX) { //IE
mouse.x = ev.clientX + document.body.scrollLeft;
mouse.y = ev.clientY + document.body.scrollTop;
}
};
var element = null;
canvas.onmousemove = function (e) {
setMousePosition(e);
if (element !== null) {
element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
}
}
canvas.onclick = function (e) {
if (element !== null) {
var coord = {
left: element.style.left,
top: element.style.top,
width: element.style.width,
height: element.style.height
};
Shiny.onInputChange('rectCoord', coord);
element = null;
canvas.style.cursor = \"default\";
} else {
mouse.startX = mouse.x;
mouse.startY = mouse.y;
element = document.createElement('div');
element.className = 'rectangle'
element.style.left = mouse.x + 'px';
element.style.top = mouse.y + 'px';
canvas.appendChild(element);
canvas.style.cursor = \"crosshair\";
}
}
};
$(document).on('shiny:sessioninitialized', function(event) {
initDraw(document.getElementById('canvas'));
});
"
library(shiny)
ui <- fluidPage(
tags$head(
tags$style(css),
tags$script(HTML(js))
),
fluidRow(
column(width = 6,
# inline is necessary
# ...otherwise we can draw rectangles over entire fluidRow
uiOutput("canvas", inline = TRUE)),
column(
width = 6,
verbatimTextOutput("rectCoordOutput")
)
)
)
server <- function(input, output, session) {
output$canvas <- renderUI({
tags$img(src = "https://www.r-project.org/logo/Rlogo.png")
})
output$rectCoordOutput <- renderPrint({
input$rectCoord
})
}
shinyApp(ui, server)
This solution uses kyamagu's bbox_annotator and is based on demo.html. I'm not familiar with JS, so it's not the prettiest. Limitations are:
Choosing a different image url will remove previous rectangles
I edited the JS a bit to change the rectangle/text color, so you won't be able to pull directly from the original repo
My changes probably broke input_method = "fixed" and "text", I only tested input_method = "select"
ui.R
# Adapted from https://github.com/kyamagu/bbox-annotator/
# Edited original JS to add color_list as an option
# ...should be the same length as labels
# ...and controls the color of the rectangle
# ...will probably be broken for input_method = "fixed" or "text"
# Also added color as a value in each rectangle entry
js <- '
$(document).ready(function() {
// define options to pass to bounding box constructor
var options = {
url: "https://www.r-project.org/logo/Rlogo.svg",
input_method: "select",
labels: [""],
color_list: [""],
onchange: function(entries) {
Shiny.onInputChange("rectCoord", JSON.stringify(entries, null, " "));
}
};
// Initialize the bounding-box annotator.
var annotator = new BBoxAnnotator(options);
// Initialize the reset button.
$("#reset_button").click(function(e) {
annotator.clear_all();
})
// define function to reset the bbox
// ...upon choosing new label category or new url
function reset_bbox(options) {
document.getElementById("bbox_annotator").setAttribute("style", "display:inline-block");
$(".image_frame").remove();
annotator = new BBoxAnnotator(options);
}
// update image url from shiny
Shiny.addCustomMessageHandler("change-img-url", function(url) {
options.url = url;
options.width = null;
options.height = null;
reset_bbox(options);
});
// update colors and categories from shiny
Shiny.addCustomMessageHandler("update-category-list", function(vals) {
options.labels = Object.values(vals);
options.color_list = Object.keys(vals);
reset_bbox(options);
});
// redraw rectangles based on list of entries
Shiny.addCustomMessageHandler("redraw-rects", function(vals) {
var arr = JSON.parse(vals);
arr.forEach(function(rect){
annotator.add_entry(rect);
});
if (annotator.onchange) {
annotator.onchange(annotator.entries);
}
});
});
'
ui <- fluidPage(
tags$head(tags$script(HTML(js)),
tags$head(
tags$script(src = "bbox_annotation.js")
)),
titlePanel("Bounding box annotator demo"),
sidebarLayout(
sidebarPanel(
selectInput(
"img_url",
"URLs",
c(
"https://www.r-project.org/logo/Rlogo.svg",
"https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png"
)
),
selectInput("category_type", "Label Category", c("animals", "fruits")),
div(HTML(
'<input id="reset_button" type="reset" />'
)),
HTML(
'<input id="annotation_data" name="annotation_data" type="hidden" />'
),
hr(),
h4("Entries"),
verbatimTextOutput("rectCoordOutput")
),
mainPanel(div(id = "bbox_annotator", style = "display:inline-block"))
)
)
server.R
server <- function(input, output, session) {
# user choices
output$rectCoordOutput <- renderPrint({
if(!is.null(input$rectCoord)) {
as.data.frame(jsonlite::fromJSON(input$rectCoord))
}
})
# send chosen URL from shiny to JS
observeEvent(input$img_url, {
session$sendCustomMessage("change-img-url", input$img_url)
})
# send chosen category list from shiny to JS
observeEvent(input$category_type, {
vals <- switch(input$category_type,
fruits = list("yellow" = "banana",
"orange" = "pineapple",
"pink" = "grapefruit"),
animals = list("grey" = "raccoon",
"brown" = "dog",
"tan" = "cat")
)
# update category list
session$sendCustomMessage("update-category-list", vals)
# redraw rectangles
session$sendCustomMessage("redraw-rects", input$rectCoord)
})
}
www/bbox_annotation.js
// Generated by CoffeeScript 2.5.0
(function() {
// https://github.com/kyamagu/bbox-annotator/blob/master/bbox_annotator.coffee
// Use coffee-script compiler to obtain a javascript file.
// coffee -c bbox_annotator.coffee
// See http://coffeescript.org/
// BBox selection window.
var BBoxSelector;
BBoxSelector = class BBoxSelector {
// Initializes selector in the image frame.
constructor(image_frame, options) {
if (options == null) {
options = {};
}
options.input_method || (options.input_method = "text");
this.image_frame = image_frame;
this.border_width = options.border_width || 2;
this.selector = $('<div class="bbox_selector"></div>');
this.selector.css({
// rectangle color when dragging
"border": this.border_width + "px dotted rgb(127,255,127)",
"position": "absolute"
});
this.image_frame.append(this.selector);
this.selector.css({
"border-width": this.border_width
});
this.selector.hide();
this.create_label_box(options);
}
// Initializes a label input box.
create_label_box(options) {
var i, label, len, ref;
options.labels || (options.labels = ["object"]);
this.label_box = $('<div class="label_box" style="z-index: 1000"></div>');
this.label_box.css({
"position": "absolute"
});
this.image_frame.append(this.label_box);
switch (options.input_method) {
case 'select':
if (typeof options.labels === "string") {
options.labels = [options.labels];
}
this.label_input = $('<select class="label_input" name="label"></select>');
this.label_box.append(this.label_input);
this.label_input.append($('<option value>choose an item</option>'));
ref = options.labels;
for (i = 0, len = ref.length; i < len; i++) {
label = ref[i];
this.label_input.append('<option value="' + label + '">' + label + '</option>');
}
this.label_input.change(function(e) {
return this.blur();
});
break;
case 'text':
if (typeof options.labels === "string") {
options.labels = [options.labels];
}
this.label_input = $('<input class="label_input" name="label" ' + 'type="text" value>');
this.label_box.append(this.label_input);
this.label_input.autocomplete({
source: options.labels || [''],
autoFocus: true
});
break;
case 'fixed':
if ($.isArray(options.labels)) {
options.labels = options.labels[0];
}
this.label_input = $('<input class="label_input" name="label" type="text">');
this.label_box.append(this.label_input);
this.label_input.val(options.labels);
break;
default:
throw 'Invalid label_input parameter: ' + options.input_method;
}
return this.label_box.hide();
}
// Crop x and y to the image size.
crop(pageX, pageY) {
var point;
return point = {
x: Math.min(Math.max(Math.round(pageX - this.image_frame.offset().left), 0), Math.round(this.image_frame.width() - 1)),
y: Math.min(Math.max(Math.round(pageY - this.image_frame.offset().top), 0), Math.round(this.image_frame.height() - 1))
};
}
// When a new selection is made.
start(pageX, pageY) {
this.pointer = this.crop(pageX, pageY);
this.offset = this.pointer;
this.refresh();
this.selector.show();
$('body').css('cursor', 'crosshair');
return document.onselectstart = function() {
return false;
};
}
// When a selection updates.
update_rectangle(pageX, pageY) {
this.pointer = this.crop(pageX, pageY);
return this.refresh();
}
// When starting to input label.
input_label(options) {
$('body').css('cursor', 'default');
document.onselectstart = function() {
return true;
};
this.label_box.show();
return this.label_input.focus();
}
// Finish and return the annotation.
finish(options) {
var data;
this.label_box.hide();
this.selector.hide();
data = this.rectangle();
data.label = $.trim(this.label_input.val().toLowerCase());
if (options.input_method !== 'fixed') {
this.label_input.val('');
}
return data;
}
// Get a rectangle.
rectangle() {
var rect, x1, x2, y1, y2;
x1 = Math.min(this.offset.x, this.pointer.x);
y1 = Math.min(this.offset.y, this.pointer.y);
x2 = Math.max(this.offset.x, this.pointer.x);
y2 = Math.max(this.offset.y, this.pointer.y);
return rect = {
left: x1,
top: y1,
width: x2 - x1 + 1,
height: y2 - y1 + 1
};
}
// Update css of the box.
refresh() {
var rect;
rect = this.rectangle();
this.selector.css({
left: (rect.left - this.border_width) + 'px',
top: (rect.top - this.border_width) + 'px',
width: rect.width + 'px',
height: rect.height + 'px'
});
return this.label_box.css({
left: (rect.left - this.border_width) + 'px',
top: (rect.top + rect.height + this.border_width) + 'px'
});
}
// Return input element.
get_input_element() {
return this.label_input;
}
};
// Annotator object definition.
this.BBoxAnnotator = class BBoxAnnotator {
// Initialize the annotator layout and events.
constructor(options) {
var annotator, image_element;
annotator = this;
this.annotator_element = $(options.id || "#bbox_annotator");
// allow us to access colors and labels in future steps
this.color_list = options.color_list;
this.label_list = options.labels;
this.border_width = options.border_width || 2;
this.show_label = options.show_label || (options.input_method !== "fixed");
if (options.multiple != null) {
this.multiple = options.multiple;
} else {
this.multiple = true;
}
this.image_frame = $('<div class="image_frame"></div>');
this.annotator_element.append(this.image_frame);
if (options.guide) {
annotator.initialize_guide(options.guide);
}
image_element = new Image();
image_element.src = options.url;
image_element.onload = function() {
options.width || (options.width = image_element.width);
options.height || (options.height = image_element.height);
annotator.annotator_element.css({
"width": (options.width + annotator.border_width) + 'px',
"height": (options.height + annotator.border_width) + 'px',
"padding-left": (annotator.border_width / 2) + 'px',
"padding-top": (annotator.border_width / 2) + 'px',
"cursor": "crosshair",
"overflow": "hidden"
});
annotator.image_frame.css({
"background-image": "url('" + image_element.src + "')",
"width": options.width + "px",
"height": options.height + "px",
"position": "relative"
});
annotator.selector = new BBoxSelector(annotator.image_frame, options);
return annotator.initialize_events(options);
};
image_element.onerror = function() {
return annotator.annotator_element.text("Invalid image URL: " + options.url);
};
this.entries = [];
this.onchange = options.onchange;
}
// Initialize events.
initialize_events(options) {
var annotator, selector, status;
status = 'free';
this.hit_menuitem = false;
annotator = this;
selector = annotator.selector;
this.annotator_element.mousedown(function(e) {
if (!annotator.hit_menuitem) {
switch (status) {
case 'free':
case 'input':
if (status === 'input') {
selector.get_input_element().blur();
}
if (e.which === 1) { // left button
selector.start(e.pageX, e.pageY);
status = 'hold';
}
}
}
annotator.hit_menuitem = false;
return true;
});
$(window).mousemove(function(e) {
var offset;
switch (status) {
case 'hold':
selector.update_rectangle(e.pageX, e.pageY);
}
if (annotator.guide_h) {
offset = annotator.image_frame.offset();
annotator.guide_h.css('top', Math.floor(e.pageY - offset.top) + 'px');
annotator.guide_v.css('left', Math.floor(e.pageX - offset.left) + 'px');
}
return true;
});
$(window).mouseup(function(e) {
switch (status) {
case 'hold':
selector.update_rectangle(e.pageX, e.pageY);
selector.input_label(options);
status = 'input';
if (options.input_method === 'fixed') {
selector.get_input_element().blur();
}
}
return true;
});
selector.get_input_element().blur(function(e) {
var data;
switch (status) {
case 'input':
data = selector.finish(options);
if (data.label) {
// store color with the entry
// ...so we can redraw the rectangle upon changing label category
data.color = annotator.color_list[annotator.label_list.indexOf(data.label)];
annotator.add_entry(data);
if (annotator.onchange) {
annotator.onchange(annotator.entries);
}
}
status = 'free';
}
return true;
});
selector.get_input_element().keypress(function(e) {
switch (status) {
case 'input':
if (e.which === 13) {
selector.get_input_element().blur();
}
}
return e.which !== 13;
});
selector.get_input_element().mousedown(function(e) {
return annotator.hit_menuitem = true;
});
selector.get_input_element().mousemove(function(e) {
return annotator.hit_menuitem = true;
});
selector.get_input_element().mouseup(function(e) {
return annotator.hit_menuitem = true;
});
return selector.get_input_element().parent().mousedown(function(e) {
return annotator.hit_menuitem = true;
});
}
// Add a new entry.
add_entry(entry) {
var annotator, box_element, close_button, text_box;
if (!this.multiple) {
this.annotator_element.find(".annotated_bounding_box").detach();
this.entries.splice(0);
}
this.entries.push(entry);
box_element = $('<div class="annotated_bounding_box"></div>');
box_element.appendTo(this.image_frame).css({
// rectangle color -- when stopped dragging
"border": this.border_width + "px solid " + entry.color,
"position": "absolute",
"top": (entry.top - this.border_width) + "px",
"left": (entry.left - this.border_width) + "px",
"width": entry.width + "px",
"height": entry.height + "px",
// text color when stopped dragging
"color": entry.color,
"font-family": "monospace",
"font-size": "small"
});
close_button = $('<div></div>').appendTo(box_element).css({
"position": "absolute",
"top": "-8px",
"right": "-8px",
"width": "16px",
"height": "0",
"padding": "16px 0 0 0",
"overflow": "hidden",
"color": "#fff",
"background-color": "#030",
"border": "2px solid #fff",
"-moz-border-radius": "18px",
"-webkit-border-radius": "18px",
"border-radius": "18px",
"cursor": "pointer",
"-moz-user-select": "none",
"-webkit-user-select": "none",
"user-select": "none",
"text-align": "center"
});
$("<div></div>").appendTo(close_button).html('×').css({
"display": "block",
"text-align": "center",
"width": "16px",
"position": "absolute",
"top": "-2px",
"left": "0",
"font-size": "16px",
"line-height": "16px",
"font-family": '"Helvetica Neue", Consolas, Verdana, Tahoma, Calibri, ' + 'Helvetica, Menlo, "Droid Sans", sans-serif'
});
text_box = $('<div></div>').appendTo(box_element).css({
"overflow": "hidden"
});
if (this.show_label) {
text_box.text(entry.label);
}
annotator = this;
box_element.hover((function(e) {
return close_button.show();
}), (function(e) {
return close_button.hide();
}));
close_button.mousedown(function(e) {
return annotator.hit_menuitem = true;
});
close_button.click(function(e) {
var clicked_box, index;
clicked_box = close_button.parent(".annotated_bounding_box");
index = clicked_box.prevAll(".annotated_bounding_box").length;
clicked_box.detach();
annotator.entries.splice(index, 1);
return annotator.onchange(annotator.entries);
});
return close_button.hide();
}
// Clear all entries.
clear_all(e) {
this.annotator_element.find(".annotated_bounding_box").detach();
this.entries.splice(0);
return this.onchange(this.entries);
}
// Add crosshair guide.
initialize_guide(options) {
this.guide_h = $('<div class="guide_h"></div>').appendTo(this.image_frame).css({
"border": "1px dotted " + (options.color || '#000'),
"height": "0",
"width": "100%",
"position": "absolute",
"top": "0",
"left": "0"
});
return this.guide_v = $('<div class="guide_v"></div>').appendTo(this.image_frame).css({
"border": "1px dotted " + (options.color || '#000'),
"height": "100%",
"width": "0",
"position": "absolute",
"top": "0",
"left": "0"
});
}
};
}).call(this);

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.

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.

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);
}
});

javascript slideshow pauseonhover

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)

Categories

Resources