I am creating a form that includes a budget slider with the following code
<div class="budget_slider">
<input type="range" name="budget" min="1" max="12" step="1" value="0" data-orientation="horizontal" onchange="getVals(this, 'budget');" style="position: absolute; width: 1px; height: 1px; overflow: hidden; opacity: 0;"><div class="rangeslider rangeslider--horizontal" id="js-rangeslider-0"><div class="rangeslider__fill" style="width: 10px;"></div><div class="rangeslider__handle" style="left: 0px;"></div></div><span>1</span>
</div>
It is a slider that goes from 1 to 12. When the slider hits 12, I want the value to show "12+" and not just "12". That is: when the slider is in any value between 1 and 11, just show that number, but the next value should be 12+, indicating that the client is willing to buy 12 or more items. Is there any way I can do that?
This is the rangeslider.js file:
/*! rangeslider.js - v2.3.0 | (c) 2016 #andreruffert | MIT license | https://github.com/andreruffert/rangeslider.js */
(function(factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function($) {
'use strict';
// Polyfill Number.isNaN(value)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === 'number' && value !== value;
};
/**
* Range feature detection
* #return {Boolean}
*/
function supportsRange() {
var input = document.createElement('input');
input.setAttribute('type', 'range');
return input.type !== 'text';
}
var pluginName = 'rangeslider',
pluginIdentifier = 0,
hasInputRangeSupport = supportsRange(),
defaults = {
polyfill: true,
orientation: 'horizontal',
rangeClass: 'rangeslider',
disabledClass: 'rangeslider--disabled',
activeClass: 'rangeslider--active',
horizontalClass: 'rangeslider--horizontal',
verticalClass: 'rangeslider--vertical',
fillClass: 'rangeslider__fill',
handleClass: 'rangeslider__handle',
startEvent: ['mousedown', 'touchstart', 'pointerdown'],
moveEvent: ['mousemove', 'touchmove', 'pointermove'],
endEvent: ['mouseup', 'touchend', 'pointerup']
},
constants = {
orientation: {
horizontal: {
dimension: 'width',
direction: 'left',
directionStyle: 'left',
coordinate: 'x'
},
vertical: {
dimension: 'height',
direction: 'top',
directionStyle: 'bottom',
coordinate: 'y'
}
}
};
/**
* Delays a function for the given number of milliseconds, and then calls
* it with the arguments supplied.
*
* #param {Function} fn [description]
* #param {Number} wait [description]
* #return {Function}
*/
function delay(fn, wait) {
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(function(){ return fn.apply(null, args); }, wait);
}
/**
* Returns a debounced function that will make sure the given
* function is not triggered too much.
*
* #param {Function} fn Function to debounce.
* #param {Number} debounceDuration OPTIONAL. The amount of time in milliseconds for which we will debounce the function. (defaults to 100ms)
* #return {Function}
*/
function debounce(fn, debounceDuration) {
debounceDuration = debounceDuration || 100;
return function() {
if (!fn.debouncing) {
var args = Array.prototype.slice.apply(arguments);
fn.lastReturnVal = fn.apply(window, args);
fn.debouncing = true;
}
clearTimeout(fn.debounceTimeout);
fn.debounceTimeout = setTimeout(function(){
fn.debouncing = false;
}, debounceDuration);
return fn.lastReturnVal;
};
}
/**
* Check if a `element` is visible in the DOM
*
* #param {Element} element
* #return {Boolean}
*/
function isHidden(element) {
return (
element && (
element.offsetWidth === 0 ||
element.offsetHeight === 0 ||
// Also Consider native `<details>` elements.
element.open === false
)
);
}
/**
* Get hidden parentNodes of an `element`
*
* #param {Element} element
* #return {[type]}
*/
function getHiddenParentNodes(element) {
var parents = [],
node = element.parentNode;
while (isHidden(node)) {
parents.push(node);
node = node.parentNode;
}
return parents;
}
/**
* Returns dimensions for an element even if it is not visible in the DOM.
*
* #param {Element} element
* #param {String} key (e.g. offsetWidth …)
* #return {Number}
*/
function getDimension(element, key) {
var hiddenParentNodes = getHiddenParentNodes(element),
hiddenParentNodesLength = hiddenParentNodes.length,
inlineStyle = [],
dimension = element[key];
// Used for native `<details>` elements
function toggleOpenProperty(element) {
if (typeof element.open !== 'undefined') {
element.open = (element.open) ? false : true;
}
}
if (hiddenParentNodesLength) {
for (var i = 0; i < hiddenParentNodesLength; i++) {
// Cache style attribute to restore it later.
inlineStyle[i] = hiddenParentNodes[i].style.cssText;
// visually hide
if (hiddenParentNodes[i].style.setProperty) {
hiddenParentNodes[i].style.setProperty('display', 'block', 'important');
} else {
hiddenParentNodes[i].style.cssText += ';display: block !important';
}
hiddenParentNodes[i].style.height = '0';
hiddenParentNodes[i].style.overflow = 'hidden';
hiddenParentNodes[i].style.visibility = 'hidden';
toggleOpenProperty(hiddenParentNodes[i]);
}
// Update dimension
dimension = element[key];
for (var j = 0; j < hiddenParentNodesLength; j++) {
// Restore the style attribute
hiddenParentNodes[j].style.cssText = inlineStyle[j];
toggleOpenProperty(hiddenParentNodes[j]);
}
}
return dimension;
}
/**
* Returns the parsed float or the default if it failed.
*
* #param {String} str
* #param {Number} defaultValue
* #return {Number}
*/
function tryParseFloat(str, defaultValue) {
var value = parseFloat(str);
return Number.isNaN(value) ? defaultValue : value;
}
/**
* Capitalize the first letter of string
*
* #param {String} str
* #return {String}
*/
function ucfirst(str) {
return str.charAt(0).toUpperCase() + str.substr(1);
}
/**
* Plugin
* #param {String} element
* #param {Object} options
*/
function Plugin(element, options) {
this.$window = $(window);
this.$document = $(document);
this.$element = $(element);
this.options = $.extend( {}, defaults, options );
this.polyfill = this.options.polyfill;
this.orientation = this.$element[0].getAttribute('data-orientation') || this.options.orientation;
this.onInit = this.options.onInit;
this.onSlide = this.options.onSlide;
this.onSlideEnd = this.options.onSlideEnd;
this.DIMENSION = constants.orientation[this.orientation].dimension;
this.DIRECTION = constants.orientation[this.orientation].direction;
this.DIRECTION_STYLE = constants.orientation[this.orientation].directionStyle;
this.COORDINATE = constants.orientation[this.orientation].coordinate;
// Plugin should only be used as a polyfill
if (this.polyfill) {
// Input range support?
if (hasInputRangeSupport) { return false; }
}
this.identifier = 'js-' + pluginName + '-' +(pluginIdentifier++);
this.startEvent = this.options.startEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
this.moveEvent = this.options.moveEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
this.endEvent = this.options.endEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
this.toFixed = (this.step + '').replace('.', '').length - 1;
this.$fill = $('<div class="' + this.options.fillClass + '" />');
this.$handle = $('<div class="' + this.options.handleClass + '" />');
this.$range = $('<div class="' + this.options.rangeClass + ' ' + this.options[this.orientation + 'Class'] + '" id="' + this.identifier + '" />').insertAfter(this.$element).prepend(this.$fill, this.$handle);
// visually hide the input
this.$element.css({
'position': 'absolute',
'width': '1px',
'height': '1px',
'overflow': 'hidden',
'opacity': '0'
});
// Store context
this.handleDown = $.proxy(this.handleDown, this);
this.handleMove = $.proxy(this.handleMove, this);
this.handleEnd = $.proxy(this.handleEnd, this);
this.init();
// Attach Events
var _this = this;
this.$window.on('resize.' + this.identifier, debounce(function() {
// Simulate resizeEnd event.
delay(function() { _this.update(false, false); }, 300);
}, 20));
this.$document.on(this.startEvent, '#' + this.identifier + ':not(.' + this.options.disabledClass + ')', this.handleDown);
// Listen to programmatic value changes
this.$element.on('change.' + this.identifier, function(e, data) {
if (data && data.origin === _this.identifier) {
return;
}
var value = e.target.value,
pos = _this.getPositionFromValue(value);
_this.setPosition(pos);
});
}
Plugin.prototype.init = function() {
this.update(true, false);
if (this.onInit && typeof this.onInit === 'function') {
this.onInit();
}
};
Plugin.prototype.update = function(updateAttributes, triggerSlide) {
updateAttributes = updateAttributes || false;
if (updateAttributes) {
this.min = tryParseFloat(this.$element[0].getAttribute('min'), 0);
this.max = tryParseFloat(this.$element[0].getAttribute('max'), 100);
this.value = tryParseFloat(this.$element[0].value, Math.round(this.min + (this.max-this.min)/2));
this.step = tryParseFloat(this.$element[0].getAttribute('step'), 1);
}
this.handleDimension = getDimension(this.$handle[0], 'offset' + ucfirst(this.DIMENSION));
this.rangeDimension = getDimension(this.$range[0], 'offset' + ucfirst(this.DIMENSION));
this.maxHandlePos = this.rangeDimension - this.handleDimension;
this.grabPos = this.handleDimension / 2;
this.position = this.getPositionFromValue(this.value);
// Consider disabled state
if (this.$element[0].disabled) {
this.$range.addClass(this.options.disabledClass);
} else {
this.$range.removeClass(this.options.disabledClass);
}
this.setPosition(this.position, triggerSlide);
};
Plugin.prototype.handleDown = function(e) {
e.preventDefault();
this.$document.on(this.moveEvent, this.handleMove);
this.$document.on(this.endEvent, this.handleEnd);
// add active class because Firefox is ignoring
// the handle:active pseudo selector because of `e.preventDefault();`
this.$range.addClass(this.options.activeClass);
// If we click on the handle don't set the new position
if ((' ' + e.target.className + ' ').replace(/[\n\t]/g, ' ').indexOf(this.options.handleClass) > -1) {
return;
}
var pos = this.getRelativePosition(e),
rangePos = this.$range[0].getBoundingClientRect()[this.DIRECTION],
handlePos = this.getPositionFromNode(this.$handle[0]) - rangePos,
setPos = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);
this.setPosition(setPos);
if (pos >= handlePos && pos < handlePos + this.handleDimension) {
this.grabPos = pos - handlePos;
}
};
Plugin.prototype.handleMove = function(e) {
e.preventDefault();
var pos = this.getRelativePosition(e);
var setPos = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);
this.setPosition(setPos);
};
Plugin.prototype.handleEnd = function(e) {
e.preventDefault();
this.$document.off(this.moveEvent, this.handleMove);
this.$document.off(this.endEvent, this.handleEnd);
this.$range.removeClass(this.options.activeClass);
// Ok we're done fire the change event
this.$element.trigger('change', { origin: this.identifier });
if (this.onSlideEnd && typeof this.onSlideEnd === 'function') {
this.onSlideEnd(this.position, this.value);
}
};
Plugin.prototype.cap = function(pos, min, max) {
if (pos < min) { return min; }
if (pos > max) { return max; }
return pos;
};
Plugin.prototype.setPosition = function(pos, triggerSlide) {
var value, newPos;
if (triggerSlide === undefined) {
triggerSlide = true;
}
// Snapping steps
value = this.getValueFromPosition(this.cap(pos, 0, this.maxHandlePos));
newPos = this.getPositionFromValue(value);
// Update ui
this.$fill[0].style[this.DIMENSION] = (newPos + this.grabPos) + 'px';
this.$handle[0].style[this.DIRECTION_STYLE] = newPos + 'px';
this.setValue(value);
// Update globals
this.position = newPos;
this.value = value;
if (triggerSlide && this.onSlide && typeof this.onSlide === 'function') {
this.onSlide(newPos, value);
}
};
// Returns element position relative to the parent
Plugin.prototype.getPositionFromNode = function(node) {
var i = 0;
while (node !== null) {
i += node.offsetLeft;
node = node.offsetParent;
}
return i;
};
Plugin.prototype.getRelativePosition = function(e) {
// Get the offset DIRECTION relative to the viewport
var ucCoordinate = ucfirst(this.COORDINATE),
rangePos = this.$range[0].getBoundingClientRect()[this.DIRECTION],
pageCoordinate = 0;
if (typeof e.originalEvent['client' + ucCoordinate] !== 'undefined') {
pageCoordinate = e.originalEvent['client' + ucCoordinate];
}
else if (
e.originalEvent.touches &&
e.originalEvent.touches[0] &&
typeof e.originalEvent.touches[0]['client' + ucCoordinate] !== 'undefined'
) {
pageCoordinate = e.originalEvent.touches[0]['client' + ucCoordinate];
}
else if(e.currentPoint && typeof e.currentPoint[this.COORDINATE] !== 'undefined') {
pageCoordinate = e.currentPoint[this.COORDINATE];
}
return pageCoordinate - rangePos;
};
Plugin.prototype.getPositionFromValue = function(value) {
var percentage, pos;
percentage = (value - this.min)/(this.max - this.min);
pos = (!Number.isNaN(percentage)) ? percentage * this.maxHandlePos : 0;
return pos;
};
Plugin.prototype.getValueFromPosition = function(pos) {
var percentage, value;
percentage = ((pos) / (this.maxHandlePos || 1));
value = this.step * Math.round(percentage * (this.max - this.min) / this.step) + this.min;
return Number((value).toFixed(this.toFixed));
};
Plugin.prototype.setValue = function(value) {
if (value === this.value && this.$element[0].value !== '') {
return;
}
// Set the new value and fire the `input` event
this.$element
.val(value)
.trigger('input', { origin: this.identifier });
};
Plugin.prototype.destroy = function() {
this.$document.off('.' + this.identifier);
this.$window.off('.' + this.identifier);
this.$element
.off('.' + this.identifier)
.removeAttr('style')
.removeData('plugin_' + pluginName);
// Remove the generated markup
if (this.$range && this.$range.length) {
this.$range[0].parentNode.removeChild(this.$range[0]);
}
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function(options) {
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var $this = $(this),
data = $this.data('plugin_' + pluginName);
// Create a new instance.
if (!data) {
$this.data('plugin_' + pluginName, (data = new Plugin(this, options)));
}
// Make it possible to access methods from public.
// e.g `$element.rangeslider('method');`
if (typeof options === 'string') {
data[options].apply(data, args);
}
});
};
return 'rangeslider.js is available in jQuery context e.g $(selector).rangeslider(options);';
}));
Thank you in advance!
I'm not 100% sure what exactly I am looking at above, but I won't be a jerk and vote down your question lol. Here's the basic idea of what you are trying to accomplish:
Create a condition in your JavaScript that applies to the numeric value of your range slider. If it's equal to 12 to set it equal to a string equal to "12+". This is pseudo code, but the basic idea would be:
if (numericValue == 12)
{displayedValue = "12+"}
If your range slider won't display a string value and requires and integer, then create a div tag with your "+" next to your numeric value and adjust it's visibility based on the value of your slider being equal to 12.
I would recommend not using the open source code you have above unless you absolutely have to. There is already a default range slider available in HTML that you can customize:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range
Avoid open source projects where possible unless it's something you can't live without that isn't readily available.
Always sucks being a beginner, but hang in there, and it'll come together. Hope this gets you moving in the right direction.
Related
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.
So I have a div where I change the background images with a script. I simplified everything here: https://inmeditas.satsang-hamburg.de/test.html
Unfortunately about 10% of the time I get an error in Firefox which looks like this:
So far everything seems to work fine in Chrome and other browsers. Here is the code as snippet:
/*!
* jQuery.BgSwitcher
*
* #version 0.4.3
* #author rewish <rewish.org#gmail.com>
* #license MIT License (https://github.com/rewish/jquery-bgswitcher/blob/master/LICENSE.md)
* #link https://github.com/rewish/jquery-bgswitcher
*/
(function($) {
'use strict';
var loadedImages = {},
slice = Array.prototype.slice,
toString = Object.prototype.toString,
corners = ['Top', 'Right', 'Bottom', 'Left'],
backgroundProperties = [
'Attachment', 'Color', 'Image', 'Repeat',
'Position', 'Size', 'Clip', 'Origin'
];
$.fn.bgswitcher = function() {
var args = arguments,
instanceKey = BgSwitcher.keys.instance;
return this.each(function() {
var instance = $.data(this, instanceKey);
if (!instance) {
instance = new BgSwitcher(this);
$.data(this, instanceKey, instance);
}
instance.dispatch.apply(instance, args);
});
};
// Backward Compatibility
$.fn.bgSwitcher = $.fn.bgswitcher;
/**
* BgSwitcher
*
* #param {HTMLElement} el
* #constructor
*/
function BgSwitcher(el) {
this.$el = $(el);
this.index = 0;
this.config = $.extend({}, BgSwitcher.defaultConfig);
this._setupBackgroundElement();
this._listenToResize();
}
$.extend(BgSwitcher.prototype, {
/**
* Dispatch
*
* #param {string|Array} one
*/
dispatch: function(one) {
switch (toString.call(one)) {
case '[object Object]':
this.setConfig(one);
break;
case '[object String]':
this[one].apply(this, slice.call(arguments, 1));
break;
default:
throw new Error('Please specify a Object or String');
}
},
/**
* Set config
*
* #param {Object} config
*/
setConfig: function(config) {
this.config = $.extend(this.config, config);
if (typeof this.config.random !== 'undefined') {
this.config.shuffle = this.config.random;
}
this.refresh();
},
/**
* Set images
*
* #param {Array} images
*/
setImages: function(images) {
this.imageList = new this.constructor.ImageList(images);
if (this.config.shuffle) {
this.imageList.shuffle();
}
},
/**
* Set switch handler
*
* #param {Function} fn
*/
setSwitchHandler: function(fn) {
this.switchHandler = $.proxy(fn, this);
},
/**
* Default switch handler
*
* #param {string} type
* #returns {Function}
*/
getBuiltInSwitchHandler: function(type) {
return this.constructor.switchHandlers[type || this.config.effect];
},
/**
* Refresh
*/
refresh: function() {
this.setImages(this.config.images);
this.setSwitchHandler(this.getBuiltInSwitchHandler());
this._prepareSwitching();
if (this.config.start) {
this.start();
}
},
/**
* Start switching
*/
start: function() {
if (!this._timerID) {
this._timerID = setTimeout($.proxy(this, 'next'), this.config.interval);
}
},
/**
* Stop switching
*/
stop: function() {
if (this._timerID) {
clearTimeout(this._timerID);
this._timerID = null;
}
},
/**
* Toggle between start/stop
*/
toggle: function() {
if (this._timerID) {
this.stop();
} else {
this.start();
}
},
/**
* Reset switching
*/
reset: function() {
this.index = 0;
this._prepareSwitching();
},
/**
* Go to next switching
*/
next: function() {
var max = this.imageList.count();
if (!this.config.loop && this.index + 1 === max) {
return;
}
if (++this.index === max) {
this.index = 0;
}
this.switching();
},
/**
* Go to previous switching
*/
prev: function() {
if (!this.config.loop && this.index === 0) {
return;
}
if (--this.index === -1) {
this.index = this.imageList.count() - 1;
}
this.switching();
},
/**
* Select the switching at index
*
* #param {number} index
*/
select: function(index) {
if (index === -1) {
index = this.imageList.count() - 1;
}
this.index = index;
this.switching();
},
/**
* Switching the background image
*/
switching: function() {
var started = !!this._timerID;
if (started) {
this.stop();
}
this._createSwitchableElement();
this._prepareSwitching();
this.switchHandler(this.$switchable);
if (started) {
this.start();
}
},
/**
* Destroy...
*/
destroy: function() {
this.stop();
this._stopListeningToResize();
if (this.$switchable) {
this.$switchable.stop();
this.$switchable.remove();
this.$switchable = null;
}
if (this.$bg) {
this.$bg.remove();
this.$bg = null;
}
this.$el.removeAttr('style');
this.$el.removeData(this.constructor.keys.instance);
this.$el = null;
},
/**
* Adjust rectangle
*/
_adjustRectangle: function() {
var corner,
i = 0,
length = corners.length,
offset = this.$el.position(),
copiedStyles = {
top: offset.top,
left: offset.left,
width: this.$el.innerWidth(),
height: this.$el.innerHeight()
};
for (; i < length; i++) {
corner = corners[i];
copiedStyles['margin' + corner] = this.$el.css('margin' + corner);
copiedStyles['border' + corner] = this.$el.css('border' + corner);
}
this.$bg.css(copiedStyles);
},
/**
* Setup background element
*/
_setupBackgroundElement: function() {
this.$bg = $(document.createElement('div'));
this.$bg.css({
position: 'absolute',
zIndex: (parseInt(this.$el.css('zIndex'), 10) || 0) - 1,
overflow: 'hidden'
});
this._copyBackgroundStyles();
this._adjustRectangle();
if (this.$el[0].tagName === 'BODY') {
this.$el.prepend(this.$bg);
} else {
this.$el.before(this.$bg);
this.$el.css('background', 'none');
}
},
/**
* Create switchable element
*/
_createSwitchableElement: function() {
if (this.$switchable) {
this.$switchable.remove();
}
this.$switchable = this.$bg.clone();
this.$switchable.css({top: 0, left: 0, margin: 0, border: 'none'});
this.$switchable.appendTo(this.$bg);
},
/**
* Copy background styles
*/
_copyBackgroundStyles: function () {
var prop,
copiedStyle = {},
i = 0,
length = backgroundProperties.length,
backgroundPosition = 'backgroundPosition';
for (; i < length; i++) {
prop = 'background' + backgroundProperties[i];
copiedStyle[prop] = this.$el.css(prop);
}
// For IE<=9
if (copiedStyle[backgroundPosition] === undefined) {
copiedStyle[backgroundPosition] = [
this.$el.css(backgroundPosition + 'X'),
this.$el.css(backgroundPosition + 'Y')
].join(' ');
}
this.$bg.css(copiedStyle);
},
/**
* Listen to the resize event
*/
_listenToResize: function() {
var that = this;
this._resizeHandler = function() {
that._adjustRectangle();
};
$(window).on('resize', this._resizeHandler);
},
/**
* Stop listening to the resize event
*/
_stopListeningToResize: function() {
$(window).off('resize', this._resizeHandler);
this._resizeHandler = null;
},
/**
* Prepare the Switching
*/
_prepareSwitching: function() {
this.$bg.css('backgroundImage', this.imageList.url(this.index));
}
});
/**
* Data Keys
* #type {Object}
*/
BgSwitcher.keys = {
instance: 'bgSwitcher'
};
/**
* Default Config
* #type {Object}
*/
BgSwitcher.defaultConfig = {
images: [],
interval: 5000,
start: true,
loop: true,
shuffle: false,
effect: 'fade',
duration: 1000,
easing: 'swing'
};
/**
* Built-In switch handlers (effects)
* #type {Object}
*/
BgSwitcher.switchHandlers = {
fade: function($el) {
$el.animate({opacity: 0}, this.config.duration, this.config.easing);
},
blind: function($el) {
$el.animate({height: 0}, this.config.duration, this.config.easing);
},
clip: function($el) {
$el.animate({
top: parseInt($el.css('top'), 10) + $el.height() / 2,
height: 0
}, this.config.duration, this.config.easing);
},
slide: function($el) {
$el.animate({top: -$el.height()}, this.config.duration, this.config.easing);
},
drop: function($el) {
$el.animate({
left: -$el.width(),
opacity: 0
}, this.config.duration, this.config.easing);
},
hide: function($el) {
$el.hide();
}
};
/**
* Define effect
*
* #param {String} name
* #param {Function} fn
*/
BgSwitcher.defineEffect = function(name, fn) {
this.switchHandlers[name] = fn;
};
/**
* BgSwitcher.ImageList
*
* #param {Array} images
* #constructor
*/
BgSwitcher.ImageList = function(images) {
this.images = images;
this.createImagesBySequence();
this.preload();
};
$.extend(BgSwitcher.ImageList.prototype, {
/**
* Images is sequenceable
*
* #returns {boolean}
*/
isSequenceable: function() {
return typeof this.images[0] === 'string' &&
typeof this.images[1] === 'number' &&
typeof this.images[2] === 'number';
},
/**
* Create an images by sequence
*/
createImagesBySequence: function() {
if (!this.isSequenceable()) {
return;
}
var images = [],
base = this.images[0],
min = this.images[1],
max = this.images[2];
do {
images.push(base.replace(/\.\w+$/, min + '$&'));
} while (++min <= max);
this.images = images;
},
/**
* Preload an images
*/
preload: function() {
var path,
length = this.images.length,
i = 0;
for (; i < length; i++) {
path = this.images[i];
if (!loadedImages[path]) {
loadedImages[path] = new Image();
loadedImages[path].src = path;
}
}
},
/**
* Shuffle an images
*/
shuffle: function() {
var j, t,
i = this.images.length,
original = this.images.join();
if (!i) {
return;
}
while (i) {
j = Math.floor(Math.random() * i);
t = this.images[--i];
this.images[i] = this.images[j];
this.images[j] = t;
}
if (this.images.join() === original) {
this.shuffle();
}
},
/**
* Get the image from index
*
* #param {number} index
* #returns {string}
*/
get: function(index) {
return this.images[index];
},
/**
* Get the URL with function of CSS
*
* #param {number} index
* #returns {string}
*/
url: function(index) {
return 'url(' + this.get(index) + ')';
},
/**
* Count of images
*
* #returns {number}
*/
count: function() {
return this.images.length;
}
});
$.BgSwitcher = BgSwitcher;
}(jQuery));
$(".amrum").bgswitcher({
images: ["https://inmeditas.satsang-hamburg.de/headerAmrum1.jpg", "https://inmeditas.satsang-hamburg.de/headerAmrum2.jpg", "https://inmeditas.satsang-hamburg.de/headerAmrum3.jpg", "https://inmeditas.satsang-hamburg.de/headerAmrum4.jpg"],
interval: 5000,
duration: 1000
});
.amrum {
background-position: center;
background-size: cover;
}
.unterseite {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="amrum"><img class="unterseite" src="https://inmeditas.satsang-hamburg.de/headerAmrum-hilf.png" /></div>
I would love a solution without that mistake and without problems with the Bootstrap 4 Navbar (which some other scripts unfortunately have that I tried).
Thanks for your help.
I now used http://responsiveslides.com/ and so far it works with Bootstrap 4 and I didn't get an error.
/*! ResponsiveSlides.js v1.55
* http://responsiveslides.com
* http://viljamis.com
*
* Copyright (c) 2011-2012 #viljamis
* Available under the MIT license
*/
/*jslint browser: true, sloppy: true, vars: true, plusplus: true, indent: 2 */
(function ($, window, i) {
$.fn.responsiveSlides = function (options) {
// Default settings
var settings = $.extend({
"auto": true, // Boolean: Animate automatically, true or false
"speed": 1000, // Integer: Speed of the transition, in milliseconds
"timeout": 5000, // Integer: Time between slide transitions, in milliseconds
"pager": false, // Boolean: Show pager, true or false
"nav": false, // Boolean: Show navigation, true or false
"random": false, // Boolean: Randomize the order of the slides, true or false
"pause": false, // Boolean: Pause on hover, true or false
"pauseControls": true, // Boolean: Pause when hovering controls, true or false
"prevText": "Previous", // String: Text for the "previous" button
"nextText": "Next", // String: Text for the "next" button
"maxwidth": "", // Integer: Max-width of the slideshow, in pixels
"navContainer": "", // Selector: Where auto generated controls should be appended to, default is after the <ul>
"manualControls": "", // Selector: Declare custom pager navigation
"namespace": "rslides", // String: change the default namespace used
"before": $.noop, // Function: Before callback
"after": $.noop // Function: After callback
}, options);
return this.each(function () {
// Index for namespacing
i++;
var $this = $(this),
// Local variables
vendor,
selectTab,
startCycle,
restartCycle,
rotate,
$tabs,
// Helpers
index = 0,
$slide = $this.children(),
length = $slide.length,
fadeTime = parseFloat(settings.speed),
waitTime = parseFloat(settings.timeout),
maxw = parseFloat(settings.maxwidth),
// Namespacing
namespace = settings.namespace,
namespaceIdx = namespace + i,
// Classes
navClass = namespace + "_nav " + namespaceIdx + "_nav",
activeClass = namespace + "_here",
visibleClass = namespaceIdx + "_on",
slideClassPrefix = namespaceIdx + "_s",
// Pager
$pager = $("<ul class='" + namespace + "_tabs " + namespaceIdx + "_tabs' />"),
// Styles for visible and hidden slides
visible = {"float": "left", "position": "relative", "opacity": 1, "zIndex": 2},
hidden = {"float": "none", "position": "absolute", "opacity": 0, "zIndex": 1},
// Detect transition support
supportsTransitions = (function () {
var docBody = document.body || document.documentElement;
var styles = docBody.style;
var prop = "transition";
if (typeof styles[prop] === "string") {
return true;
}
// Tests for vendor specific prop
vendor = ["Moz", "Webkit", "Khtml", "O", "ms"];
prop = prop.charAt(0).toUpperCase() + prop.substr(1);
var i;
for (i = 0; i < vendor.length; i++) {
if (typeof styles[vendor[i] + prop] === "string") {
return true;
}
}
return false;
})(),
// Fading animation
slideTo = function (idx) {
settings.before(idx);
// If CSS3 transitions are supported
if (supportsTransitions) {
$slide
.removeClass(visibleClass)
.css(hidden)
.eq(idx)
.addClass(visibleClass)
.css(visible);
index = idx;
setTimeout(function () {
settings.after(idx);
}, fadeTime);
// If not, use jQuery fallback
} else {
$slide
.stop()
.fadeOut(fadeTime, function () {
$(this)
.removeClass(visibleClass)
.css(hidden)
.css("opacity", 1);
})
.eq(idx)
.fadeIn(fadeTime, function () {
$(this)
.addClass(visibleClass)
.css(visible);
settings.after(idx);
index = idx;
});
}
};
// Random order
if (settings.random) {
$slide.sort(function () {
return (Math.round(Math.random()) - 0.5);
});
$this
.empty()
.append($slide);
}
// Add ID's to each slide
$slide.each(function (i) {
this.id = slideClassPrefix + i;
});
// Add max-width and classes
$this.addClass(namespace + " " + namespaceIdx);
if (options && options.maxwidth) {
$this.css("max-width", maxw);
}
// Hide all slides, then show first one
$slide
.hide()
.css(hidden)
.eq(0)
.addClass(visibleClass)
.css(visible)
.show();
// CSS transitions
if (supportsTransitions) {
$slide
.show()
.css({
// -ms prefix isn't needed as IE10 uses prefix free version
"-webkit-transition": "opacity " + fadeTime + "ms ease-in-out",
"-moz-transition": "opacity " + fadeTime + "ms ease-in-out",
"-o-transition": "opacity " + fadeTime + "ms ease-in-out",
"transition": "opacity " + fadeTime + "ms ease-in-out"
});
}
// Only run if there's more than one slide
if ($slide.length > 1) {
// Make sure the timeout is at least 100ms longer than the fade
if (waitTime < fadeTime + 100) {
return;
}
// Pager
if (settings.pager && !settings.manualControls) {
var tabMarkup = [];
$slide.each(function (i) {
var n = i + 1;
tabMarkup +=
"<li>" +
"<a href='#' class='" + slideClassPrefix + n + "'>" + n + "</a>" +
"</li>";
});
$pager.append(tabMarkup);
// Inject pager
if (options.navContainer) {
$(settings.navContainer).append($pager);
} else {
$this.after($pager);
}
}
// Manual pager controls
if (settings.manualControls) {
$pager = $(settings.manualControls);
$pager.addClass(namespace + "_tabs " + namespaceIdx + "_tabs");
}
// Add pager slide class prefixes
if (settings.pager || settings.manualControls) {
$pager.find('li').each(function (i) {
$(this).addClass(slideClassPrefix + (i + 1));
});
}
// If we have a pager, we need to set up the selectTab function
if (settings.pager || settings.manualControls) {
$tabs = $pager.find('a');
// Select pager item
selectTab = function (idx) {
$tabs
.closest("li")
.removeClass(activeClass)
.eq(idx)
.addClass(activeClass);
};
}
// Auto cycle
if (settings.auto) {
startCycle = function () {
rotate = setInterval(function () {
// Clear the event queue
$slide.stop(true, true);
var idx = index + 1 < length ? index + 1 : 0;
// Remove active state and set new if pager is set
if (settings.pager || settings.manualControls) {
selectTab(idx);
}
slideTo(idx);
}, waitTime);
};
// Init cycle
startCycle();
}
// Restarting cycle
restartCycle = function () {
if (settings.auto) {
// Stop
clearInterval(rotate);
// Restart
startCycle();
}
};
// Pause on hover
if (settings.pause) {
$this.hover(function () {
clearInterval(rotate);
}, function () {
restartCycle();
});
}
// Pager click event handler
if (settings.pager || settings.manualControls) {
$tabs.bind("click", function (e) {
e.preventDefault();
if (!settings.pauseControls) {
restartCycle();
}
// Get index of clicked tab
var idx = $tabs.index(this);
// Break if element is already active or currently animated
if (index === idx || $("." + visibleClass).queue('fx').length) {
return;
}
// Remove active state from old tab and set new one
selectTab(idx);
// Do the animation
slideTo(idx);
})
.eq(0)
.closest("li")
.addClass(activeClass);
// Pause when hovering pager
if (settings.pauseControls) {
$tabs.hover(function () {
clearInterval(rotate);
}, function () {
restartCycle();
});
}
}
// Navigation
if (settings.nav) {
var navMarkup =
"<a href='#' class='" + navClass + " prev'>" + settings.prevText + "</a>" +
"<a href='#' class='" + navClass + " next'>" + settings.nextText + "</a>";
// Inject navigation
if (options.navContainer) {
$(settings.navContainer).append(navMarkup);
} else {
$this.after(navMarkup);
}
var $trigger = $("." + namespaceIdx + "_nav"),
$prev = $trigger.filter(".prev");
// Click event handler
$trigger.bind("click", function (e) {
e.preventDefault();
var $visibleClass = $("." + visibleClass);
// Prevent clicking if currently animated
if ($visibleClass.queue('fx').length) {
return;
}
// Adds active class during slide animation
// $(this)
// .addClass(namespace + "_active")
// .delay(fadeTime)
// .queue(function (next) {
// $(this).removeClass(namespace + "_active");
// next();
// });
// Determine where to slide
var idx = $slide.index($visibleClass),
prevIdx = idx - 1,
nextIdx = idx + 1 < length ? index + 1 : 0;
// Go to slide
slideTo($(this)[0] === $prev[0] ? prevIdx : nextIdx);
if (settings.pager || settings.manualControls) {
selectTab($(this)[0] === $prev[0] ? prevIdx : nextIdx);
}
if (!settings.pauseControls) {
restartCycle();
}
});
// Pause when hovering navigation
if (settings.pauseControls) {
$trigger.hover(function () {
clearInterval(rotate);
}, function () {
restartCycle();
});
}
}
}
// Max-width fallback
if (typeof document.body.style.maxWidth === "undefined" && options.maxwidth) {
var widthSupport = function () {
$this.css("width", "100%");
if ($this.width() > maxw) {
$this.css("width", maxw);
}
};
// Init fallback
widthSupport();
$(window).bind("resize", function () {
widthSupport();
});
}
});
};
})(jQuery, this, 0);
$(function() {
$(".rslides").responsiveSlides();
});
.rslides {
position: relative;
list-style: none;
overflow: hidden;
width: 100%;
padding: 0;
margin: 0;
}
.rslides li {
-webkit-backface-visibility: hidden;
position: absolute;
display: none;
width: 100%;
left: 0;
top: 0;
}
.rslides li:first-child {
position: relative;
display: block;
float: left;
}
.rslides img {
display: block;
height: auto;
float: left;
width: 100%;
border: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="rslides">
<li><img src="https://inmeditas.satsang-hamburg.de/headerAmrum1.jpg" alt=""></li>
<li><img src="https://inmeditas.satsang-hamburg.de/headerAmrum2.jpg" alt=""></li>
<li><img src="https://inmeditas.satsang-hamburg.de/headerAmrum3.jpg" alt=""></li>
<li><img src="https://inmeditas.satsang-hamburg.de/headerAmrum4.jpg" alt=""></li>
</ul>
I have a website that uses smooth scroll which works great.. But once I added the following code:
var $ = jQuery.noConflict();
$(document).ready(function() {
$(function() {
var $ticker = $('#news-ticker'),
$first = $('.news-ticket-class li:first-child', $ticker);
// put an empty space between each letter so we can
// use break word
$('.news-ticket-class li', $ticker).each(function() {
var $this = $(this),
text = $this.text();
$this.html(text.split('').join(''));
});
// begin the animation
function tick($el) {
$el.addClass('tick')
.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
$el.removeClass('tick');
var $next = $el.next('li');
$next = $next.length > 0 ? $next : $first;
tick($next);
});
}
tick($first);
});
});
It breaks the smooth scroll. I have tried using the noconflict and that doesn't help as you can see.
The template I use is here that has the smooth scrolling option.
I am stuck with either the above code or my menus working. If you have any other suggestions that mimic someone typing, like this website, please send over my way.
EDIT: This is the smooth scroll script:
//
// SmoothScroll for websites v1.4.0 (Balazs Galambosi)
// http://www.smoothscroll.net/
//
// Licensed under the terms of the MIT license.
//
// You may use it in your theme if you credit me.
// It is also free to use on any individual website.
//
// Exception:
// The only restriction is to not publish any
// extension for browsers or native application
// without getting a written permission first.
//
(function () {
// Scroll Variables (tweakable)
var defaultOptions = {
// Scrolling Core
frameRate : 150, // [Hz]
animationTime : 500, // [ms]
stepSize : 100, // [px]
// Pulse (less tweakable)
// ratio of "tail" to "acceleration"
pulseAlgorithm : true,
pulseScale : 4,
pulseNormalize : 1,
// Acceleration
accelerationDelta : 50, // 50
accelerationMax : 3, // 3
// Keyboard Settings
keyboardSupport : true, // option
arrowScroll : 50, // [px]
// Other
touchpadSupport : false, // ignore touchpad by default
fixedBackground : true,
excluded : ''
};
var options = defaultOptions;
// Other Variables
var isExcluded = false;
var isFrame = false;
var direction = { x: 0, y: 0 };
var initDone = false;
var root = document.documentElement;
var activeElement;
var observer;
var refreshSize;
var deltaBuffer = [];
var isMac = /^Mac/.test(navigator.platform);
var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32,
pageup: 33, pagedown: 34, end: 35, home: 36 };
/***********************************************
* INITIALIZE
***********************************************/
/**
* Tests if smooth scrolling is allowed. Shuts down everything if not.
*/
function initTest() {
if (options.keyboardSupport) {
addEvent('keydown', keydown);
}
}
/**
* Sets up scrolls array, determines if frames are involved.
*/
function init() {
if (initDone || !document.body) return;
initDone = true;
var body = document.body;
var html = document.documentElement;
var windowHeight = window.innerHeight;
var scrollHeight = body.scrollHeight;
// check compat mode for root element
root = (document.compatMode.indexOf('CSS') >= 0) ? html : body;
activeElement = body;
initTest();
// Checks if this script is running in a frame
if (top != self) {
isFrame = true;
}
/**
* Please duplicate this radar for a Safari fix!
* rdar://22376037
* https://openradar.appspot.com/radar?id=4965070979203072
*
* Only applies to Safari now, Chrome fixed it in v45:
* This fixes a bug where the areas left and right to
* the content does not trigger the onmousewheel event
* on some pages. e.g.: html, body { height: 100% }
*/
else if (scrollHeight > windowHeight &&
(body.offsetHeight <= windowHeight ||
html.offsetHeight <= windowHeight)) {
var fullPageElem = document.createElement('div');
fullPageElem.style.cssText = 'position:absolute; z-index:-10000; ' +
'top:0; left:0; right:0; height:' +
root.scrollHeight + 'px';
document.body.appendChild(fullPageElem);
// DOM changed (throttled) to fix height
var pendingRefresh;
refreshSize = function () {
if (pendingRefresh) return; // could also be: clearTimeout(pendingRefresh);
pendingRefresh = setTimeout(function () {
if (isExcluded) return; // could be running after cleanup
fullPageElem.style.height = '0';
fullPageElem.style.height = root.scrollHeight + 'px';
pendingRefresh = null;
}, 500); // act rarely to stay fast
};
setTimeout(refreshSize, 10);
addEvent('resize', refreshSize);
// TODO: attributeFilter?
var config = {
attributes: true,
childList: true,
characterData: false
// subtree: true
};
observer = new MutationObserver(refreshSize);
observer.observe(body, config);
if (root.offsetHeight <= windowHeight) {
var clearfix = document.createElement('div');
clearfix.style.clear = 'both';
body.appendChild(clearfix);
}
}
// disable fixed background
if (!options.fixedBackground && !isExcluded) {
body.style.backgroundAttachment = 'scroll';
html.style.backgroundAttachment = 'scroll';
}
}
/**
* Removes event listeners and other traces left on the page.
*/
function cleanup() {
observer && observer.disconnect();
removeEvent(wheelEvent, wheel);
removeEvent('mousedown', mousedown);
removeEvent('keydown', keydown);
removeEvent('resize', refreshSize);
removeEvent('load', init);
}
/************************************************
* SCROLLING
************************************************/
var que = [];
var pending = false;
var lastScroll = Date.now();
/**
* Pushes scroll actions to the scrolling queue.
*/
function scrollArray(elem, left, top) {
directionCheck(left, top);
if (options.accelerationMax != 1) {
var now = Date.now();
var elapsed = now - lastScroll;
if (elapsed < options.accelerationDelta) {
var factor = (1 + (50 / elapsed)) / 2;
if (factor > 1) {
factor = Math.min(factor, options.accelerationMax);
left *= factor;
top *= factor;
}
}
lastScroll = Date.now();
}
// push a scroll command
que.push({
x: left,
y: top,
lastX: (left < 0) ? 0.99 : -0.99,
lastY: (top < 0) ? 0.99 : -0.99,
start: Date.now()
});
// don't act if there's a pending queue
if (pending) {
return;
}
var scrollWindow = (elem === document.body);
var step = function (time) {
var now = Date.now();
var scrollX = 0;
var scrollY = 0;
for (var i = 0; i < que.length; i++) {
var item = que[i];
var elapsed = now - item.start;
var finished = (elapsed >= options.animationTime);
// scroll position: [0, 1]
var position = (finished) ? 1 : elapsed / options.animationTime;
// easing [optional]
if (options.pulseAlgorithm) {
position = pulse(position);
}
// only need the difference
var x = (item.x * position - item.lastX) >> 0;
var y = (item.y * position - item.lastY) >> 0;
// add this to the total scrolling
scrollX += x;
scrollY += y;
// update last values
item.lastX += x;
item.lastY += y;
// delete and step back if it's over
if (finished) {
que.splice(i, 1); i--;
}
}
// scroll left and top
if (scrollWindow) {
window.scrollBy(scrollX, scrollY);
}
else {
if (scrollX) elem.scrollLeft += scrollX;
if (scrollY) elem.scrollTop += scrollY;
}
// clean up if there's nothing left to do
if (!left && !top) {
que = [];
}
if (que.length) {
requestFrame(step, elem, (1000 / options.frameRate + 1));
} else {
pending = false;
}
};
// start a new queue of actions
requestFrame(step, elem, 0);
pending = true;
}
/***********************************************
* EVENTS
***********************************************/
/**
* Mouse wheel handler.
* #param {Object} event
*/
function wheel(event) {
if (!initDone) {
init();
}
var target = event.target;
var overflowing = overflowingAncestor(target);
// use default if there's no overflowing
// element or default action is prevented
// or it's a zooming event with CTRL
if (!overflowing || event.defaultPrevented || event.ctrlKey) {
return true;
}
// leave embedded content alone (flash & pdf)
if (isNodeName(activeElement, 'embed') ||
(isNodeName(target, 'embed') && /\.pdf/i.test(target.src)) ||
isNodeName(activeElement, 'object')) {
return true;
}
var deltaX = -event.wheelDeltaX || event.deltaX || 0;
var deltaY = -event.wheelDeltaY || event.deltaY || 0;
if (isMac) {
if (event.wheelDeltaX && isDivisible(event.wheelDeltaX, 120)) {
deltaX = -120 * (event.wheelDeltaX / Math.abs(event.wheelDeltaX));
}
if (event.wheelDeltaY && isDivisible(event.wheelDeltaY, 120)) {
deltaY = -120 * (event.wheelDeltaY / Math.abs(event.wheelDeltaY));
}
}
// use wheelDelta if deltaX/Y is not available
if (!deltaX && !deltaY) {
deltaY = -event.wheelDelta || 0;
}
// line based scrolling (Firefox mostly)
if (event.deltaMode === 1) {
deltaX *= 40;
deltaY *= 40;
}
// check if it's a touchpad scroll that should be ignored
if (!options.touchpadSupport && isTouchpad(deltaY)) {
return true;
}
// scale by step size
// delta is 120 most of the time
// synaptics seems to send 1 sometimes
if (Math.abs(deltaX) > 1.2) {
deltaX *= options.stepSize / 120;
}
if (Math.abs(deltaY) > 1.2) {
deltaY *= options.stepSize / 120;
}
scrollArray(overflowing, deltaX, deltaY);
event.preventDefault();
scheduleClearCache();
}
/**
* Keydown event handler.
* #param {Object} event
*/
function keydown(event) {
var target = event.target;
var modifier = event.ctrlKey || event.altKey || event.metaKey ||
(event.shiftKey && event.keyCode !== key.spacebar);
// our own tracked active element could've been removed from the DOM
if (!document.body.contains(activeElement)) {
activeElement = document.activeElement;
}
// do nothing if user is editing text
// or using a modifier key (except shift)
// or in a dropdown
// or inside interactive elements
var inputNodeNames = /^(textarea|select|embed|object)$/i;
var buttonTypes = /^(button|submit|radio|checkbox|file|color|image)$/i;
if ( inputNodeNames.test(target.nodeName) ||
isNodeName(target, 'input') && !buttonTypes.test(target.type) ||
isNodeName(activeElement, 'video') ||
isInsideYoutubeVideo(event) ||
target.isContentEditable ||
event.defaultPrevented ||
modifier ) {
return true;
}
// spacebar should trigger button press
if ((isNodeName(target, 'button') ||
isNodeName(target, 'input') && buttonTypes.test(target.type)) &&
event.keyCode === key.spacebar) {
return true;
}
var shift, x = 0, y = 0;
var elem = overflowingAncestor(activeElement);
var clientHeight = elem.clientHeight;
if (elem == document.body) {
clientHeight = window.innerHeight;
}
switch (event.keyCode) {
case key.up:
y = -options.arrowScroll;
break;
case key.down:
y = options.arrowScroll;
break;
case key.spacebar: // (+ shift)
shift = event.shiftKey ? 1 : -1;
y = -shift * clientHeight * 0.9;
break;
case key.pageup:
y = -clientHeight * 0.9;
break;
case key.pagedown:
y = clientHeight * 0.9;
break;
case key.home:
y = -elem.scrollTop;
break;
case key.end:
var damt = elem.scrollHeight - elem.scrollTop - clientHeight;
y = (damt > 0) ? damt+10 : 0;
break;
case key.left:
x = -options.arrowScroll;
break;
case key.right:
x = options.arrowScroll;
break;
default:
return true; // a key we don't care about
}
scrollArray(elem, x, y);
event.preventDefault();
scheduleClearCache();
}
/**
* Mousedown event only for updating activeElement
*/
function mousedown(event) {
activeElement = event.target;
}
/***********************************************
* OVERFLOW
***********************************************/
var uniqueID = (function () {
var i = 0;
return function (el) {
return el.uniqueID || (el.uniqueID = i++);
};
})();
var cache = {}; // cleared out after a scrolling session
var clearCacheTimer;
//setInterval(function () { cache = {}; }, 10 * 1000);
function scheduleClearCache() {
clearTimeout(clearCacheTimer);
clearCacheTimer = setInterval(function () { cache = {}; }, 1*1000);
}
function setCache(elems, overflowing) {
for (var i = elems.length; i--;)
cache[uniqueID(elems[i])] = overflowing;
return overflowing;
}
// (body) (root)
// | hidden | visible | scroll | auto |
// hidden | no | no | YES | YES |
// visible | no | YES | YES | YES |
// scroll | no | YES | YES | YES |
// auto | no | YES | YES | YES |
function overflowingAncestor(el) {
var elems = [];
var body = document.body;
var rootScrollHeight = root.scrollHeight;
do {
var cached = cache[uniqueID(el)];
if (cached) {
return setCache(elems, cached);
}
elems.push(el);
if (rootScrollHeight === el.scrollHeight) {
var topOverflowsNotHidden = overflowNotHidden(root) && overflowNotHidden(body);
var isOverflowCSS = topOverflowsNotHidden || overflowAutoOrScroll(root);
if (isFrame && isContentOverflowing(root) ||
!isFrame && isOverflowCSS) {
return setCache(elems, getScrollRoot());
}
} else if (isContentOverflowing(el) && overflowAutoOrScroll(el)) {
return setCache(elems, el);
}
} while (el = el.parentElement);
}
function isContentOverflowing(el) {
return (el.clientHeight + 10 < el.scrollHeight);
}
// typically for <body> and <html>
function overflowNotHidden(el) {
var overflow = getComputedStyle(el, '').getPropertyValue('overflow-y');
return (overflow !== 'hidden');
}
// for all other elements
function overflowAutoOrScroll(el) {
var overflow = getComputedStyle(el, '').getPropertyValue('overflow-y');
return (overflow === 'scroll' || overflow === 'auto');
}
/***********************************************
* HELPERS
***********************************************/
function addEvent(type, fn) {
window.addEventListener(type, fn, false);
}
function removeEvent(type, fn) {
window.removeEventListener(type, fn, false);
}
function isNodeName(el, tag) {
return (el.nodeName||'').toLowerCase() === tag.toLowerCase();
}
function directionCheck(x, y) {
x = (x > 0) ? 1 : -1;
y = (y > 0) ? 1 : -1;
if (direction.x !== x || direction.y !== y) {
direction.x = x;
direction.y = y;
que = [];
lastScroll = 0;
}
}
var deltaBufferTimer;
if (window.localStorage && localStorage.SS_deltaBuffer) {
deltaBuffer = localStorage.SS_deltaBuffer.split(',');
}
function isTouchpad(deltaY) {
if (!deltaY) return;
if (!deltaBuffer.length) {
deltaBuffer = [deltaY, deltaY, deltaY];
}
deltaY = Math.abs(deltaY)
deltaBuffer.push(deltaY);
deltaBuffer.shift();
clearTimeout(deltaBufferTimer);
deltaBufferTimer = setTimeout(function () {
if (window.localStorage) {
localStorage.SS_deltaBuffer = deltaBuffer.join(',');
}
}, 1000);
return !allDeltasDivisableBy(120) && !allDeltasDivisableBy(100);
}
function isDivisible(n, divisor) {
return (Math.floor(n / divisor) == n / divisor);
}
function allDeltasDivisableBy(divisor) {
return (isDivisible(deltaBuffer[0], divisor) &&
isDivisible(deltaBuffer[1], divisor) &&
isDivisible(deltaBuffer[2], divisor));
}
function isInsideYoutubeVideo(event) {
var elem = event.target;
var isControl = false;
if (document.URL.indexOf ('www.youtube.com/watch') != -1) {
do {
isControl = (elem.classList &&
elem.classList.contains('html5-video-controls'));
if (isControl) break;
} while (elem = elem.parentNode);
}
return isControl;
}
var requestFrame = (function () {
return (window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback, element, delay) {
window.setTimeout(callback, delay || (1000/60));
});
})();
var MutationObserver = (window.MutationObserver ||
window.WebKitMutationObserver ||
window.MozMutationObserver);
var getScrollRoot = (function() {
var SCROLL_ROOT;
return function() {
if (!SCROLL_ROOT) {
var dummy = document.createElement('div');
dummy.style.cssText = 'height:10000px;width:1px;';
document.body.appendChild(dummy);
var bodyScrollTop = document.body.scrollTop;
var docElScrollTop = document.documentElement.scrollTop;
window.scrollBy(0, 3);
if (document.body.scrollTop != bodyScrollTop)
(SCROLL_ROOT = document.body);
else
(SCROLL_ROOT = document.documentElement);
window.scrollBy(0, -3);
document.body.removeChild(dummy);
}
return SCROLL_ROOT;
};
})();
/***********************************************
* PULSE (by Michael Herf)
***********************************************/
/**
* Viscous fluid with a pulse for part and decay for the rest.
* - Applies a fixed force over an interval (a damped acceleration), and
* - Lets the exponential bleed away the velocity over a longer interval
* - Michael Herf, http://stereopsis.com/stopping/
*/
function pulse_(x) {
var val, start, expx;
// test
x = x * options.pulseScale;
if (x < 1) { // acceleartion
val = x - (1 - Math.exp(-x));
} else { // tail
// the previous animation ended here:
start = Math.exp(-1);
// simple viscous drag
x -= 1;
expx = 1 - Math.exp(-x);
val = start + (expx * (1 - start));
}
return val * options.pulseNormalize;
}
function pulse(x) {
if (x >= 1) return 1;
if (x <= 0) return 0;
if (options.pulseNormalize == 1) {
options.pulseNormalize /= pulse_(1);
}
return pulse_(x);
}
/***********************************************
* FIRST RUN
***********************************************/
var userAgent = window.navigator.userAgent;
var isEdge = /Edge/.test(userAgent); // thank you MS
var isChrome = /chrome/i.test(userAgent) && !isEdge;
var isSafari = /safari/i.test(userAgent) && !isEdge;
var isMobile = /mobile/i.test(userAgent);
var isIEWin7 = /Windows NT 6.1/i.test(userAgent) && /rv:11/i.test(userAgent);
var isEnabledForBrowser = (isChrome || isSafari || isIEWin7) && !isMobile;
var wheelEvent;
if ('onwheel' in document.createElement('div'))
wheelEvent = 'wheel';
else if ('onmousewheel' in document.createElement('div'))
wheelEvent = 'mousewheel';
if (wheelEvent && isEnabledForBrowser) {
addEvent(wheelEvent, wheel);
addEvent('mousedown', mousedown);
addEvent('load', init);
}
/***********************************************
* PUBLIC INTERFACE
***********************************************/
function SmoothScroll(optionsToSet) {
for (var key in optionsToSet)
if (defaultOptions.hasOwnProperty(key))
options[key] = optionsToSet[key];
}
SmoothScroll.destroy = cleanup;
if (window.SmoothScrollOptions) // async API
SmoothScroll(window.SmoothScrollOptions)
if (typeof define === 'function' && define.amd)
define(function() {
return SmoothScroll;
});
else if ('object' == typeof exports)
module.exports = SmoothScroll;
else
window.SmoothScroll = SmoothScroll;
})();
I believe the purpose of noConflict is to relinquish control of the $ global variable for external libraries, so doing var $ = jQuery.noConflict(); just sets the global $ to what noConflict returns, which is the jQuery object. In other words, it doesn't buy you anything - it's simply setting $ to what $ would be, even without the noConflict() method.
Change the $ to $j like the following:
var $j = jQuery.noConflict();
$j(document).ready(function() {
$j(function() {
var $ticker = $j('#news-ticker'),
$first = $j('.news-ticket-class li:first-child', $ticker);
// put an empty space between each letter so we can
// use break word
$j('.news-ticket-class li', $ticker).each(function() {
var $this = $j(this),
text = $this.text();
$this.html(text.split('').join(''));
});
// begin the animation
function tick($el) {
$el.addClass('tick')
.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
$el.removeClass('tick');
var $next = $el.next('li');
$next = $next.length > 0 ? $next : $first;
tick($next);
});
}
tick($first);
});
});
I have a JavaScript variable below which I need to pass some non-breaking spaces to, before the word.
var str = " Test";
How do I achieve this?
You can do something like this,
Creating a temporary div using $("<div/>")
Adding html content as the string using html(str)
Now to get the decoded string we can use text()
var str = " Test"
console.log($("<div/>").html(str).text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
In pure javascript you can use a textarea,
You can create a textarea using document.createElement('textarea')
Now you can use innerHTML to set the html content
For retrieving the decoded data you can use ele.value
var str = " Test",
ele = document.createElement('textarea');
ele.innerHTML = str;
console.log(ele.value);
I have added slight variation in your plugin code
/**
* jquery.typist — animated text typing
* #author Alexander Burtsev, http://burtsev.me, 2014—2015
* #license MIT
*/
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function($) {
'use strict';
$.fn.typistInit = function() {
return this.each(function() {
if (!$(this).data('typist')) {
new Typist(this);
}
});
};
$.fn.typist = function(opts) {
return this.each(function() {
new Typist(this, opts);
});
};
$.fn.typistAdd = function(text, callback) {
return this
.typistInit()
.each(function() {
var self = $(this).data('typist');
self.queue.push({
text: text,
callback: callback
});
self.type();
});
};
$.fn.typistRemove = function(length, callback) {
length = parseInt(length) || 0;
return this
.typistInit()
.each(function() {
var self = $(this).data('typist');
self.queue.push({
remove: length,
callback: callback
});
self.type();
});
};
$.fn.typistPause = function(delay, callback) {
delay = parseInt(delay) || 0;
return this
.typistInit()
.each(function() {
var self = $(this).data('typist');
self.queue.push({
delay: delay,
callback: callback
});
self.type();
});
};
$.fn.typistStop = function() {
return this
.typistInit()
.each(function() {
var self = $(this).data('typist');
self.queue.push({
stop: true
});
self.type();
});
};
/**
* #class
* #param {HTMLElement} element
* #param {Object} [opts]
* #param {String} [opts.text=''] Text for typing
* #param {Number} [opts.speed=10] Typing speed (characters per second)
* #param {Boolean} [opts.cursor=true] Shows blinking cursor
* #param {Number} [opts.blinkSpeed=2] Blinking per second
* #param {String} [opts.typeFrom='end'] Typing from start/end of element
* #param {Object} [opts.cursorStyles] CSS properties for cursor element
*/
function Typist(element, opts) {
$.extend(this, {
speed: 10, // characters per second
text: '',
cursor: true,
blinkSpeed: 2, // blink per second
typeFrom: 'end', // 'start', 'end'
cursorStyles: {
display: 'inline-block',
fontStyle: 'normal',
margin: '-2px 2px 0 2px'
}
}, opts || {});
this._cursor = null;
this._element = $(element);
this._element.data('typist', this);
this._container = null;
this.queue = [];
this.timer = null;
this.delay = 1000 / this.speed;
this.blinkTimer = null;
this.blinkDelay = 1000 / this.blinkSpeed;
if (this.text) {
this.queue.push({
text: this.text
});
this.type();
}
}
Typist.prototype =
/** #lends Typist */
{
/**
* Adds blinking cursor into element
*/
addCursor: function() {
if (this._cursor) {
clearInterval(this.blinkTimer);
this._cursor
.stop()
.remove();
}
this._cursor = $('<span>|</span>')
.css(this.cursorStyles)
.insertAfter(this._container);
this.cursorVisible = true;
this.blinkTimer = setInterval($.proxy(function() {
this.cursorVisible = !this.cursorVisible;
this._cursor.animate({
opacity: this.cursorVisible ? 1 : 0
}, 100);
}, this), this.blinkDelay);
},
/**
* Triggers event
* #param {String} event
* #return {Typist}
*/
fire: function(event) {
this._element.trigger(event, this);
return this;
},
/**
* New line to <br> tag
* #param {String} text
* #return {String}
*/
nl2br: function(text) {
return text.replace(/\n/g, '<br>');
},
/**
* <br> tag to new line
* #param {String} html
* #return {String}
*/
br2nl: function(html) {
return html.replace(/<br.*?>/g, '\n');
},
/**
* Removes given number of characters
* #param {Number} length
* #param {Function} [callback]
*/
remove: function(length, callback) {
if (length <= 0) {
callback();
this.timer = null;
return this
.fire('end_remove.typist')
.type();
}
var text = this._container.html();
length--;
text = this.br2nl(text);
text = text.substr(0, text.length - 1);
text = this.nl2br(text);
this.timer = setTimeout($.proxy(function() {
this._container.html(text);
this.remove(length, callback);
}, this), this.delay);
},
/**
* Adds given text character by character
* #param {String|Array} text
*/
step: function(text, callback) {
if (typeof text === 'string') {
text = text.split('').map(function(v){return v.replace(' ',' ');});
}
if (!text.length) {
callback();
this.timer = null;
return this
.fire('end_type.typist')
.type();
}
var character = text.shift();
//character = $('<div>').text(character).html();
character = this.nl2br(character);
this.timer = setTimeout($.proxy(function() {
this._container.html(this._container.html() + character);
this.step(text, callback);
}, this), this.delay);
},
/**
* Stops all animations and removes cursor
* #return {[type]} [description]
*/
stop: function() {
clearInterval(this.blinkTimer);
this.blinkTimer = null;
if (this._cursor) {
this._cursor.remove();
this._cursor = null;
}
clearTimeout(this.timer);
this.timer = null;
},
/**
* Gets and invokes tasks from queue
*/
type: function() {
if (this.timer) {
return;
}
if (!this._container) {
this._container = $('<span>');
if (this.typeFrom === 'start') {
this._element.prepend(this._container);
} else {
this._element.append(this._container);
}
}
if (this.cursor) {
this.addCursor();
}
var item = this.queue.shift() || {},
callback = $.proxy(item.callback || $.noop, this);
if (item.delay) {
this
.fire('start_pause.typist')
.timer = setTimeout($.proxy(function() {
callback();
this.timer = null;
this
.fire('end_pause.typist')
.type();
}, this), item.delay);
return;
} else if (item.remove) {
this
.fire('start_remove.typist')
.remove(item.remove, callback);
return;
} else if (item.stop) {
this.stop();
return;
}
if (!item.text) {
return;
}
this
.fire('start_type.typist')
.step(item.text, callback);
}
};
}));
$('.typist')
.typist({
speed: 12,
text: 'Hello!\n'
})
.typistAdd('It working!');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="typist"></p>
I have two scripts running on the same page, one is the jQuery.hSlides.js script http://www.jesuscarrera.info/demos/hslides/ and the other is a custom script that is used for MailChimp list signup integration. The hSlides panel can be seen in effect here: http://theatricalbellydance.com. I've turned off the MailChimp script because it was conflicting with the hSlides script, causing it not to to fail completely (as seen here http://theatricalbellydance.com/home2/). Can someone tell me what could be done to the hSlides script to stop the conflict with the MailChimp script?
The MailChimp Script
var fnames = new Array();
var ftypes = new Array();
fnames[0] = 'EMAIL';
ftypes[0] = 'email';
fnames[3] = 'MMERGE3';
ftypes[3] = 'text';
fnames[1] = 'FNAME';
ftypes[1] = 'text';
fnames[2] = 'LNAME';
ftypes[2] = 'text';
fnames[4] = 'MMERGE4';
ftypes[4] = 'address';
fnames[6] = 'MMERGE6';
ftypes[6] = 'number';
fnames[9] = 'MMERGE9';
ftypes[9] = 'text';
fnames[5] = 'MMERGE5';
ftypes[5] = 'text';
fnames[7] = 'MMERGE7';
ftypes[7] = 'text';
fnames[8] = 'MMERGE8';
ftypes[8] = 'text';
fnames[10] = 'MMERGE10';
ftypes[10] = 'text';
fnames[11] = 'MMERGE11';
ftypes[11] = 'text';
fnames[12] = 'MMERGE12';
ftypes[12] = 'text';
var err_style = '';
try {
err_style = mc_custom_error_style;
} catch (e) {
err_style = 'margin: 1em 0 0 0; padding: 1em 0.5em 0.5em 0.5em; background: rgb(255, 238, 238) none repeat scroll 0% 0%; font-weight: bold; float: left; z-index: 1; width: 80%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; color: rgb(255, 0, 0);';
}
var mce_jQuery = jQuery.noConflict();
mce_jQuery(document).ready(function ($) {
var options = {
errorClass: 'mce_inline_error',
errorElement: 'div',
errorStyle: err_style,
onkeyup: function () {},
onfocusout: function () {},
onblur: function () {}
};
var mce_validator = mce_jQuery("#mc-embedded-subscribe-form").validate(options);
options = {
url: 'http://theatricalbellydance.us1.list-manage.com/subscribe/post-json?u=1d127e7630ced825cb1a8b5a9&id=9f12d2a6bb&c=?',
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
beforeSubmit: function () {
mce_jQuery('#mce_tmp_error_msg').remove();
mce_jQuery('.datefield', '#mc_embed_signup').each(function () {
var txt = 'filled';
var fields = new Array();
var i = 0;
mce_jQuery(':text', this).each(function () {
fields[i] = this;
i++;
});
mce_jQuery(':hidden', this).each(function () {
if (fields[0].value == 'MM' && fields[1].value == 'DD' && fields[2].value == 'YYYY') {
this.value = '';
} else if (fields[0].value == '' && fields[1].value == '' && fields[2].value == '') {
this.value = '';
} else {
this.value = fields[0].value + '/' + fields[1].value + '/' + fields[2].value;
}
});
});
return mce_validator.form();
},
success: mce_success_cb
};
mce_jQuery('#mc-embedded-subscribe-form').ajaxForm(options);
});
function mce_success_cb(resp) {
mce_jQuery('#mce-success-response').hide();
mce_jQuery('#mce-error-response').hide();
if (resp.result == "success") {
mce_jQuery('#mce-' + resp.result + '-response').show();
mce_jQuery('#mce-' + resp.result + '-response').html(resp.msg);
mce_jQuery('#mc-embedded-subscribe-form').each(function () {
this.reset();
});
} else {
var index = -1;
var msg;
try {
var parts = resp.msg.split(' - ', 2);
if (parts[1] == undefined) {
msg = resp.msg;
} else {
i = parseInt(parts[0]);
if (i.toString() == parts[0]) {
index = parts[0];
msg = parts[1];
} else {
index = -1;
msg = resp.msg;
}
}
} catch (e) {
index = -1;
msg = resp.msg;
}
try {
if (index == -1) {
mce_jQuery('#mce-' + resp.result + '-response').show();
mce_jQuery('#mce-' + resp.result + '-response').html(msg);
} else {
err_id = 'mce_tmp_error_msg';
html = '<div id="' + err_id + '" style="' + err_style + '"> ' + msg + '</div>';
var input_id = '#mc_embed_signup';
var f = mce_jQuery(input_id);
if (ftypes[index] == 'address') {
input_id = '#mce-' + fnames[index] + '-addr1';
f = mce_jQuery(input_id).parent().parent().get(0);
} else if (ftypes[index] == 'date') {
input_id = '#mce-' + fnames[index] + '-month';
f = mce_jQuery(input_id).parent().parent().get(0);
} else {
input_id = '#mce-' + fnames[index];
f = mce_jQuery().parent(input_id).get(0);
}
if (f) {
mce_jQuery(f).append(html);
mce_jQuery(input_id).focus();
} else {
mce_jQuery('#mce-' + resp.result + '-response').show();
mce_jQuery('#mce-' + resp.result + '-response').html(msg);
}
}
} catch (e) {
mce_jQuery('#mce-' + resp.result + '-response').show();
mce_jQuery('#mce-' + resp.result + '-response').html(msg);
}
}
}
The hslides script:
/*
* hSlides (1.0) // 2008.02.25 // <http://plugins.jquery.com/project/hslides>
*
* REQUIRES jQuery 1.2.3+ <http://jquery.com/>
*
* Copyright (c) 2008 TrafficBroker <http://www.trafficbroker.co.uk>
* Licensed under GPL and MIT licenses
*
* hSlides is an horizontal accordion navigation, sliding the panels around to reveal one of interest.
*
* Sample Configuration:
* // this is the minimum configuration needed
* $('#accordion').hSlides({
* totalWidth: 730,
* totalHeight: 140,
* minPanelWidth: 87,
* maxPanelWidth: 425
* });
*
* Config Options:
* // Required configuration
* totalWidth: Total width of the accordion // default: 0
* totalHeight: Total height of the accordion // default: 0
* minPanelWidth: Minimum width of the panel (closed) // default: 0
* maxPanelWidth: Maximum width of the panel (opened) // default: 0
* // Optional configuration
* midPanelWidth: Middle width of the panel (centered) // default: 0
* speed: Speed for the animation // default: 500
* easing: Easing effect for the animation. Other than 'swing' or 'linear' must be provided by plugin // default: 'swing'
* sensitivity: Sensitivity threshold (must be 1 or higher) // default: 3
* interval: Milliseconds for onMouseOver polling interval // default: 100
* timeout: Milliseconds delay before onMouseOut // default: 300
* eventHandler: Event to open panels: click or hover. For the hover option requires hoverIntent plugin <http://cherne.net/brian/resources/jquery.hoverIntent.html> // default: 'click'
* panelSelector: HTML element storing the panels // default: 'li'
* activeClass: CSS class for the active panel // default: none
* panelPositioning: Accordion panelPositioning: top -> first panel on the bottom and next on the top, other value -> first panel on the top and next to the bottom // default: 'top'
* // Callback functions. Inside them, we can refer the panel with $(this).
* onEnter: Function raised when the panel is activated. // default: none
* onLeave: Function raised when the panel is deactivated. // default: none
*
* We can override the defaults with:
* $.fn.hSlides.defaults.easing = 'easeOutCubic';
*
* #param settings An object with configuration options
* #author Jesus Carrera <jesus.carrera#trafficbroker.co.uk>
*/
(function($) {
$.fn.hSlides = function(settings) {
// override default configuration
settings = $.extend({}, $.fn.hSlides.defaults, settings);
// for each accordion
return this.each(function(){
var wrapper = this;
var panelLeft = 0;
var panels = $(settings.panelSelector, wrapper);
var panelPositioning = 1;
if (settings.panelPositioning != 'top'){
panelLeft = ($(settings.panelSelector, wrapper).length - 1) * settings.minPanelWidth;
panels = $(settings.panelSelector, wrapper).reverse();
panelPositioning = -1;
}
// necessary styles for the wrapper
$(this).css('position', 'relative').css('overflow', 'hidden').css('width', settings.totalWidth).css('height', settings.totalHeight);
// set the initial position of the panels
var zIndex = 0;
panels.each(function(){
// necessary styles for the panels
$(this).css('position', 'absolute').css('left', panelLeft).css('zIndex', zIndex).css('height', settings.totalHeight).css('width', settings.maxPanelWidth);
zIndex ++;
// if this panel is the activated by default, set it as active and move the next (to show this one)
if ($(this).hasClass(settings.activeClass)){
$.data($(this)[0], 'active', true);
if (settings.panelPositioning != 'top'){
panelLeft = ($(settings.panelSelector, wrapper).index(this) + 1) * settings.minPanelWidth - settings.maxPanelWidth;
}else{
panelLeft = panelLeft + settings.maxPanelWidth;
}
}else{
// check if we are centering and some panel is active
// this is why we can't add/remove the active class in the callbacks: positioning the panels if we have one active
if (settings.midPanelWidth && $(settings.panelSelector, wrapper).hasClass(settings.activeClass) == false){
panelLeft = panelLeft + settings.midPanelWidth * panelPositioning;
}else{
panelLeft = panelLeft + settings.minPanelWidth * panelPositioning;
}
}
});
// iterates through the panels setting the active and changing the position
var movePanels = function(){
// index of the new active panel
var activeIndex = $(settings.panelSelector, wrapper).index(this);
// iterate all panels
panels.each(function(){
// deactivate if is the active
if ( $.data($(this)[0], 'active') == true ){
$.data($(this)[0], 'active', false);
$(this).removeClass(settings.activeClass).each(settings.onLeave);
}
// set position of current panel
var currentIndex = $(settings.panelSelector, wrapper).index(this);
panelLeft = settings.minPanelWidth * currentIndex;
// if the panel is next to the active, we need to add the opened width
if ( (currentIndex * panelPositioning) > (activeIndex * panelPositioning)){
panelLeft = panelLeft + (settings.maxPanelWidth - settings.minPanelWidth) * panelPositioning;
}
// animate
$(this).animate({left: panelLeft}, settings.speed, settings.easing);
});
// activate the new active panel
$.data($(this)[0], 'active', true);
$(this).addClass(settings.activeClass).each(settings.onEnter);
};
// center the panels if configured
var centerPanels = function(){
var panelLeft = 0;
if (settings.panelPositioning != 'top'){
panelLeft = ($(settings.panelSelector, wrapper).length - 1) * settings.minPanelWidth;
}
panels.each(function(){
$(this).removeClass(settings.activeClass).animate({left: panelLeft}, settings.speed, settings.easing);
if ($.data($(this)[0], 'active') == true){
$.data($(this)[0], 'active', false);
$(this).each(settings.onLeave);
}
panelLeft = panelLeft + settings.midPanelWidth * panelPositioning ;
});
};
// event handling
if(settings.eventHandler == 'click'){
$(settings.panelSelector, wrapper).click(movePanels);
}else{
var configHoverPanel = {
sensitivity: settings.sensitivity,
interval: settings.interval,
over: movePanels,
timeout: settings.timeout,
out: function() {}
}
var configHoverWrapper = {
sensitivity: settings.sensitivity,
interval: settings.interval,
over: function() {},
timeout: settings.timeout,
out: centerPanels
}
$(settings.panelSelector, wrapper).hoverIntent(configHoverPanel);
if (settings.midPanelWidth != 0){
$(wrapper).hoverIntent(configHoverWrapper);
}
}
});
};
// invert the order of the jQuery elements
$.fn.reverse = function(){
return this.pushStack(this.get().reverse(), arguments);
};
// default settings
$.fn.hSlides.defaults = {
totalWidth: 0,
totalHeight: 0,
minPanelWidth: 0,
maxPanelWidth: 0,
midPanelWidth: 0,
speed: 500,
easing: 'swing',
sensitivity: 3,
interval: 100,
timeout: 300,
eventHandler: 'click',
panelSelector: 'li',
activeClass: false,
panelPositioning: 'top',
onEnter: function() {},
onLeave: function() {}
};
})(jQuery);
The $ is no longer assigned to jQuery. I don't see what other library is using the $ however? What happens when you change
var mce_jQuery = jQuery.noConflict();
to
var mce_jQuery = jQuery;
Maybe it is just that I am not finding the library that is using the $ that required the call to noConflict.
**Edit:**Try reassigning the $ back to jQuery before your script runs.
I had a very similar problem with the custom MailChimp code. It turns out that another plugin was taking over jQuery and the $ symbol was not working. Michael's suggestion worked for me. What I did was just use the jQuery keyword on the $(document) line at the top of the MC code.
I also copied the MC js script off of the MailChimp server, and I am hosting it myself.