Conflict between two Javascripts (MailChimp validation etc. scripts & jQuery hSlides.js) - javascript

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.

Related

When value is x, display text next to value

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.

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.

Occasional error with div-background-switcher in Firefox

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>

Joomla Hot Themes Carousel Blank Space

I have installed the HotThemes Carousel module in joomla and this is working fine so far. (unfortunately on localhost so can't share link)
The problem I am trying to fix is that for some reason when I click the next button it brings the next 4 images (like its set to move by 4 images or something) and as I only have 6 images in total, it shows up with blank spaces after the last 2 images.
What I would like is if the next button is pressed then this should bring the next image (so 1 at a time) and then just stop on the last image and then the prev button could be used to go the other way.
How can I do this?
/* jQuery Carousel 0.9.1
Copyright 2008-2009 Thomas Lanciaux and Pierre Bertet.
This software is licensed under the CC-GNU LGPL
<http://creativecommons.org/licenses/LGPL/2.1/>
*/
;(function(jQuery){
jQuery.fn.carousel = function(params){
var params = jQuery.extend({
direction: "horizontal",
loop: false,
dispItems: 5,
pagination: false,
paginationPosition: "inside",
nextBtn: '<span>Next</span>',
prevBtn: '<span>Previous</span>',
btnsPosition: "inside",
nextBtnInsert: "appendTo",
prevBtnInsert: "prependTo",
nextBtnInsertFn: false,
prevBtnInsertFn: false,
autoSlide: false,
autoSlideInterval: 3000,
delayAutoSlide: false,
combinedClasses: false,
effect: "slide",
slideEasing: "swing",
animSpeed: "normal",
equalWidths: "true",
callback: function(){},
useAddress: false,
adressIdentifier: "carousel"
}, params);
// Buttons position
if (params.btnsPosition == "inside"){
params.prevBtnInsert = "insertBefore";
params.nextBtnInsert = "insertAfter";
}
// Slide delay
params.delayAutoSlide = params.delayAutoSlide || params.autoSlideInterval;
return this.each(function(){
// Env object
var env = {
$elts: {},
params: params,
launchOnLoad: []
};
// Carousel main container
env.$elts.carousel = jQuery(this).addClass("js");
// Carousel content
env.$elts.content = jQuery(this).children().css({position: "absolute", "top": 0});
// Content wrapper
env.$elts.wrap = env.$elts.content.wrap('<div class="carousel-wrap"></div>').parent().css({overflow: "hidden", position: "relative"});
// env.steps object
env.steps = {
first: 0, // First step
count: env.$elts.content.children().length // Items count
};
// Last visible step
env.steps.last = env.steps.count - 1;
// Prev Button
if (jQuery.isFunction(env.params.prevBtnInsertFn)) {
env.$elts.prevBtn = env.params.prevBtnInsertFn(env.$elts);
} else {
env.$elts.prevBtn = jQuery(params.prevBtn)[params.prevBtnInsert](env.$elts.carousel);
}
// Next Button
if (jQuery.isFunction(env.params.nextBtnInsertFn)) {
env.$elts.nextBtn = env.params.nextBtnInsertFn(env.$elts);
} else {
env.$elts.nextBtn = jQuery(params.nextBtn)[params.nextBtnInsert](env.$elts.carousel);
}
// Add buttons classes / data
env.$elts.nextBtn.addClass("carousel-control next carousel-next");
env.$elts.prevBtn.addClass("carousel-control previous carousel-previous");
// Bind events on next / prev buttons
initButtonsEvents(env);
// Pagination
if (env.params.pagination) {
initPagination(env);
}
// Address plugin
initAddress(env);
// On document load...
jQuery(function(){
// First item
var $firstItem = env.$elts.content.children(":first");
// Width 1/3 : Get default item width
env.itemWidth = $firstItem.outerWidth();
// Width 2/3 : Define content width
if (params.direction == "vertical"){
env.contentWidth = env.itemWidth;
} else {
if (params.equalWidths) {
env.contentWidth = env.itemWidth * env.steps.count;
} else {
env.contentWidth = (function(){
var totalWidth = 0;
env.$elts.content.children().each(function(){
totalWidth += jQuery(this).outerWidth();
});
return totalWidth;
})();
}
}
// Width 3/3 : Set content width to container
env.$elts.content.width( env.contentWidth );
// Height 1/2 : Get default item height
env.itemHeight = $firstItem.outerHeight();
// Height 2/2 : Set content height to container
if (params.direction == "vertical"){
env.$elts.content.css({height:env.itemHeight * env.steps.count + "px"});
env.$elts.content.parent().css({height:env.itemHeight * env.params.dispItems + "px"});
} else {
env.$elts.content.parent().css({height:env.itemHeight + "px"});
}
// Update Next / Prev buttons state
updateButtonsState(env);
// Launch function added to "document ready" event
jQuery.each(env.launchOnLoad, function(i,fn){
fn();
});
// Launch autoslide
if (env.params.autoSlide){
window.setTimeout(function(){
env.autoSlideInterval = window.setInterval(function(){
goToStep( env, getRelativeStep(env, "next") );
}, env.params.autoSlideInterval);
}, env.params.delayAutoSlide);
}
});
});
};
// Next / Prev buttons events only
function initButtonsEvents(env){
env.$elts.nextBtn.add(env.$elts.prevBtn)
.bind("enable", function(){
var $this = jQuery(this)
.unbind("click")
.bind("click", function(){
goToStep( env, getRelativeStep(env, ($this.is(".next")? "next" : "prev" )) );
stopAutoSlide(env);
})
.removeClass("disabled");
// Combined classes (IE6 compatibility)
if (env.params.combinedClasses) {
$this.removeClass("next-disabled previous-disabled");
}
})
.bind("disable", function(){
var $this = jQuery(this).unbind("click").addClass("disabled");
// Combined classes (IE6 compatibility)
if (env.params.combinedClasses) {
if ($this.is(".next")) {
$this.addClass("next-disabled");
} else if ($this.is(".previous")) {
$this.addClass("previous-disabled");
}
}
})
.hover(function(){
jQuery(this).toggleClass("hover");
});
};
// Pagination
function initPagination(env){
env.$elts.pagination = jQuery('<div class="center-wrap"><div class="carousel-pagination"><p></p></div></div>')[((env.params.paginationPosition == "outside")? "insertAfter" : "appendTo")](env.$elts.carousel).find("p");
env.$elts.paginationBtns = jQuery([]);
env.$elts.content.find("li").each(function(i){
if (i % env.params.dispItems == 0) {
env.$elts.paginationBtns = env.$elts.paginationBtns.add( jQuery('<a role="button"><span>'+( env.$elts.paginationBtns.length + 1 )+'</span></a>').data("firstStep", i) );
}
});
env.$elts.paginationBtns.appendTo(env.$elts.pagination);
env.$elts.paginationBtns.slice(0,1).addClass("active");
// Events
env.launchOnLoad.push(function(){
env.$elts.paginationBtns.click(function(e){
goToStep( env, jQuery(this).data("firstStep") );
stopAutoSlide(env);
});
});
};
// Address plugin
function initAddress(env) {
if (env.params.useAddress && jQuery.isFunction(jQuery.fn.address)) {
jQuery.address
.init(function(e) {
var pathNames = jQuery.address.pathNames();
if (pathNames[0] === env.params.adressIdentifier && !!pathNames[1]) {
goToStep(env, pathNames[1]-1);
} else {
jQuery.address.value('/'+ env.params.adressIdentifier +'/1');
}
})
.change(function(e) {
var pathNames = jQuery.address.pathNames();
if (pathNames[0] === env.params.adressIdentifier && !!pathNames[1]) {
goToStep(env, pathNames[1]-1);
}
});
} else {
env.params.useAddress = false;
}
};
function goToStep(env, step) {
// Callback
env.params.callback(step);
// Launch animation
transition(env, step);
// Update first step
env.steps.first = step;
// Update buttons status
updateButtonsState(env);
// Update address (jQuery Address plugin)
if ( env.params.useAddress ) {
jQuery.address.value('/'+ env.params.adressIdentifier +'/' + (step + 1));
}
};
// Get next/prev step, useful for autoSlide
function getRelativeStep(env, position) {
if (position == "prev") {
if ( (env.steps.first - env.params.dispItems) >= 0 ) {
return env.steps.first - env.params.dispItems;
} else {
return ( (env.params.loop)? (env.steps.count - env.params.dispItems) : false );
}
} else if (position == "next") {
if ( (env.steps.first + env.params.dispItems) < env.steps.count ) {
return env.steps.first + env.params.dispItems;
} else {
return ( (env.params.loop)? 0 : false );
}
}
};
// Animation
function transition(env, step) {
// Effect
switch (env.params.effect){
// No effect
case "no":
if (env.params.direction == "vertical"){
env.$elts.content.css("top", -(env.itemHeight * step) + "px");
} else {
env.$elts.content.css("left", -(env.itemWidth * step) + "px");
}
break;
// Fade effect
case "fade":
if (env.params.direction == "vertical"){
env.$elts.content.hide().css("top", -(env.itemHeight * step) + "px").fadeIn(env.params.animSpeed);
} else {
env.$elts.content.hide().css("left", -(env.itemWidth * step) + "px").fadeIn(1000);
}
break;
// Slide effect
default:
if (env.params.direction == "vertical"){
env.$elts.content.stop().animate({
top : -(env.itemHeight * step) + "px"
}, env.params.animSpeed, env.params.slideEasing);
} else {
env.$elts.content.stop().animate({
left : -(env.itemWidth * step) + "px"
}, env.params.animSpeed, env.params.slideEasing);
}
break;
}
};
// Update all buttons state : disabled or not
function updateButtonsState(env){
if (getRelativeStep(env, "prev") !== false) {
env.$elts.prevBtn.trigger("enable");
} else {
env.$elts.prevBtn.trigger("disable");
}
if (getRelativeStep(env, "next") !== false) {
env.$elts.nextBtn.trigger("enable");
} else {
env.$elts.nextBtn.trigger("disable");
}
if (env.params.pagination){
env.$elts.paginationBtns.removeClass("active")
.filter(function(){ return (jQuery(this).data("firstStep") == env.steps.first) }).addClass("active");
}
};
// Stop autoslide
function stopAutoSlide(env) {
if (!!env.autoSlideInterval){
window.clearInterval(env.autoSlideInterval);
}
};
})(jQuery);

responsive top-bar navigation with mootools

i am working with mootools , and with foundation as my css "framework".
i am using the navigation top-bar from foundation and its great. yet the responsive design was ruined.
since i am not working with jquery ....
http://jsfiddle.net/idanhen/3LXQb/ <-- this is the foundation code.
http://foundation.zurb.com/docs/navigation.php <- navigation documentation
i cant understand the jquery script they did to convert it.
anyone know of a mootools responsive navigation bar ?
Made it myself , thought i would share if someone will ever need it .
original file is : "jquery.foundation.topbar.js"
new file is : "mootools.foundation.topbar.js"
just add foundation.css
mootools-core-1.4.5 , mootools-more-1.4.0.1 ( i have both cause its a huge project , but i guess u can only use the core ... )
mootools.foundation.topbar.js
and ofcourse run the following command :
<script type="text/javascript">
window.addEvent('domready', function() {
window.foundationTopBar();
});
</script>
"mootools.foundation.topbar.js" :
`
/**
* mootools.foundation.topbar
*
* taken from foundation.topbar.js
* http://foundation.zurb.com
*
* Written by Idan Hen : idandush#gmail.com
*/
;(function ($, window, undefined) {
'use strict';
/* just create settings object */
var settings = {
index : 0,
breakPoint : 940, // Set to to 9999 to force it into responsive always
initialized : false
};
var methods = {
init : function (options) {
return function () {
settings = Object.merge(settings, options); //settings = $.extend(settings, options);
settings.window = window;
settings.topbar = $$('nav.top-bar');
settings.titlebar = settings.topbar.getChildren('ul')[0]; // getElement() just return #
if (!settings.initialized) {
methods.assemble();
settings.initialized = true;
}
if (!settings.height) {
methods.largestUL();
}
$$('.top-bar .toggle-topbar').getParent().addEvent('click.fndtn:relay(.top-bar .toggle-topbar)', function (e) { //live switched to addEvent
e.preventDefault();
if (methods.breakpoint()) {
settings.topbar.toggleClass('expanded');
settings.topbar.setStyle('min-height', ''); //css
}
});
// Show the Dropdown Levels on Click
$$('.top-bar .has-dropdown>a').getParent().addEvent('click.fndtn:relay(.top-bar .has-dropdown>a)', function (e) {
e.preventDefault();
if (methods.breakpoint()) {
var anchor = $(this),
selectedLi = anchor.getParent('li'), // closest -> getParent
section = anchor.getParents('section')[0],// closest -> getParents
largestUl;
settings.index += 1;
selectedLi.addClass('moved');
section.setStyle('left', -(100 * settings.index) + '%');
section.getElements('>.name').setStyle('left', 100 * settings.index + '%');
//outerHeight
anchor.getSiblings('ul').setStyle('height', (settings.height + settings.titlebar.getSize().y));
settings.topbar.setStyle('min-height', settings.height + settings.titlebar.getSize().y * 2) //outerHeight
}
});
// Go up a level on Click
$$('.top-bar .has-dropdown .back').getParent().addEvent('click.fndtn:relay(.top-bar .has-dropdown .back)', function (e) {
e.preventDefault();
var anchor = $(this),
movedLi = anchor.getParent('li.moved'),
section = anchor.getParents('section')[0],
previousLevelUl = movedLi.getParent();
settings.index -= 1;
section.setStyle('left', -(100 * settings.index) + '%'); //css
section.getElements('>.name').setStyle('left', 100 * settings.index + '%'); // find
if (settings.index === 0) {
settings.topbar.setStyle('min-height', 0); // changed topbar from $topbar
}
setTimeout(function () {
movedLi.removeClass('moved');
}, 300);
});
}.call(window.document.HTMLDocument);
},
breakpoint : function () {
return settings.window.getSize().x < settings.breakPoint; //width()
},
assemble : function assemble() {
var section = settings.topbar.getElements('section')[0];
// Pull element out of the DOM for manipulation
section = section.dispose(); //detach
//console.log('section.getElements.n>a : ', section.getElements('.has-dropdown>a'));
section.getElements('.has-dropdown>a').each(function(e){
e.each(function (e) {
//console.log('section' , section);
var link = $(e),
dropdown = link.getSiblings('.dropdown'), //siblings
//<li class="title back js-generated"><h5></h5></li>
a = new Element('a', {
href: '#'
}),
h5 = new Element('h5', {}),
titleLi = new Element('li', {
'class': 'title back js-generated'
});//section.getChildren('ul li');// back js-generated');
// console.log('dropdown: ', dropdown);
h5.grab(a);
titleLi.grab(h5);
// Copy link to subnav
titleLi.getElements('h5>a').set('html', (link.get('html') ) ); // find -> getElements
dropdown.grab(titleLi, 'top');
});
});
// Put element back in the DOM
settings.topbar[0].grab(section[0]); // section.appendTo(settings.topbar);
},
largestUL : function () {
var uls = settings.topbar[0].getElements('section ul ul'), // find -> getElements
largest = uls.getFirst(),
total = 0;
uls.each(function(ul){
if (ul.getChildren('li').length > largest.getChildren('li').length) { //length -> getSize().x
largest = ul;
}
});
largest.getChildren('li').each(function (li) { total += li.getComputedSize().height; }); //outerHeight(true); -> getSize().y
settings.height = total;
}
};
/**
* this function is added to the window -> need to add it myself
* apply is call ...
*/
window.foundationTopBar = 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 on jQuery.foundationTopBar');
}
};
}($, this));
`

Categories

Resources