Collapse Wordpress mobile menu on anchor link click - javascript

I'm trying to get my hamburger menu to close after clicking a nav link on my one page website at alecbwd.com/testing/jay. The website uses the Infinity Pro Genesis theme. Here's the JavaScript file for the responsive menu:
(function(document, $, undefined) {
// Add js body class when javascript is enabled
$('body').addClass('js');
// Add accessibility menu
'use strict';
var infinity = {},
mainMenuButtonClass = 'menu-toggle',
subMenuButtonClass = 'sub-menu-toggle';
infinity.init = function() {
var toggleButtons = {
menu: $('<button />', {
'class': mainMenuButtonClass,
'aria-expanded': false,
'aria-pressed': false,
'role': 'button'
})
.append(infinity.params.mainMenu),
submenu: $('<button />', {
'class': subMenuButtonClass,
'aria-expanded': false,
'aria-pressed': false,
'role': 'button'
})
.append($('<span />', {
'class': 'screen-reader-text',
text: infinity.params.subMenu
}))
};
$('.nav-primary').before(toggleButtons.menu); // add the main nav buttons
$('nav .sub-menu').before(toggleButtons.submenu); // add the submenu nav buttons
$('.' + mainMenuButtonClass).each(_addClassID);
$('.' + mainMenuButtonClass).addClass('ionicons-before ion-drag');
$('.' + subMenuButtonClass).addClass('ionicons-before ion-chevron-down');
$(window).on('resize.infinity', _doResize).triggerHandler('resize.infinity');
$('.' + mainMenuButtonClass).on('click.infinity-mainbutton', _mainmenuToggle);
$('.' + subMenuButtonClass).on('click.infinity-subbutton', _submenuToggle);
};
// add nav class and ID to related button
function _addClassID() {
var $this = $(this),
nav = $this.next('nav'),
id = 'class';
$this.addClass($(nav).attr('class'));
if ($(nav).attr('id')) {
id = 'id';
}
$this.attr('id', 'mobile-' + $(nav).attr(id));
}
// Change Skiplinks and Superfish
function _doResize() {
var buttons = $('button[id^=mobile-]').attr('id');
if (typeof buttons === 'undefined') {
return;
}
_superfishToggle(buttons);
_changeSkipLink(buttons);
_maybeClose(buttons);
}
/**
* action to happen when the main menu button is clicked
*/
function _mainmenuToggle() {
var $this = $(this);
_toggleAria($this, 'aria-pressed');
_toggleAria($this, 'aria-expanded');
$this.toggleClass('activated');
$('nav.nav-primary').slideToggle('fast'); //changed to .nav-primary since we're not toggling .nav-secondary
}
/**
* action for submenu toggles
*/
function _submenuToggle() {
var $this = $(this),
others = $this.closest('.menu-item').siblings();
_toggleAria($this, 'aria-pressed');
_toggleAria($this, 'aria-expanded');
$this.toggleClass('activated');
$this.next('.sub-menu').slideToggle('fast');
others.find('.' + subMenuButtonClass).removeClass('activated').attr('aria-pressed', 'false');
others.find('.sub-menu').slideUp('fast');
}
/**
* activate/deactivate superfish
*/
function _superfishToggle(buttons) {
if (typeof $('.js-superfish').superfish !== 'function') {
return;
}
if ('none' === _getDisplayValue(buttons)) {
$('.js-superfish').superfish({
'delay': 100,
'animation': {
'opacity': 'show',
'height': 'show'
},
'dropShadows': false
});
} else {
$('.js-superfish').superfish('destroy');
}
}
/**
* modify skip links to match mobile buttons
*/
function _changeSkipLink(buttons) {
var startLink = 'genesis-nav',
endLink = 'mobile-genesis-nav';
if ('none' === _getDisplayValue(buttons)) {
startLink = 'mobile-genesis-nav';
endLink = 'genesis-nav';
}
$('.genesis-skip-link a[href^="#' + startLink + '"]').each(function() {
var link = $(this).attr('href');
link = link.replace(startLink, endLink);
$(this).attr('href', link);
});
}
function _maybeClose(buttons) {
if ('none' !== _getDisplayValue(buttons)) {
return;
}
$('.menu-toggle, .sub-menu-toggle')
.removeClass('activated')
.attr('aria-expanded', false)
.attr('aria-pressed', false);
$('nav, .sub-menu')
.attr('style', '');
}
/**
* generic function to get the display value of an element
* #param {id} $id ID to check
* #return {string} CSS value of display property
*/
function _getDisplayValue($id) {
var element = document.getElementById($id),
style = window.getComputedStyle(element);
return style.getPropertyValue('display');
}
/**
* Toggle aria attributes
* #param {button} $this passed through
* #param {aria-xx} attribute aria attribute to toggle
* #return {bool} from _ariaReturn
*/
function _toggleAria($this, attribute) {
$this.attr(attribute, function(index, value) {
return 'false' === value;
});
}
$(document).ready(function() {
infinity.params = typeof InfinityL10n === 'undefined' ? '' : InfinityL10n;
if (typeof infinity.params !== 'undefined') {
infinity.init();
}
});
})(document, jQuery);
Thank you!
Update: I still don't have an solution to this -- this is one of my first questions here, am I doing it right?

I didn't test it but this javascript should do the trick
$(function(){
$('#genesis-nav-primary li').click(function()
{
$('nav.nav-primary').slideToggle('fast');
});
});
So your javascript file will looks like this :
(function(document, $, undefined) {
// Add js body class when javascript is enabled
$('body').addClass('js');
// Add accessibility menu
'use strict';
var infinity = {},
mainMenuButtonClass = 'menu-toggle',
subMenuButtonClass = 'sub-menu-toggle';
infinity.init = function() {
var toggleButtons = {
menu: $('<button />', {
'class': mainMenuButtonClass,
'aria-expanded': false,
'aria-pressed': false,
'role': 'button'
})
.append(infinity.params.mainMenu),
submenu: $('<button />', {
'class': subMenuButtonClass,
'aria-expanded': false,
'aria-pressed': false,
'role': 'button'
})
.append($('<span />', {
'class': 'screen-reader-text',
text: infinity.params.subMenu
}))
};
$('.nav-primary').before(toggleButtons.menu); // add the main nav buttons
$('nav .sub-menu').before(toggleButtons.submenu); // add the submenu nav buttons
$('.' + mainMenuButtonClass).each(_addClassID);
$('.' + mainMenuButtonClass).addClass('ionicons-before ion-drag');
$('.' + subMenuButtonClass).addClass('ionicons-before ion-chevron-down');
$(window).on('resize.infinity',
_doResize).triggerHandler('resize.infinity');
$('.' + mainMenuButtonClass).on('click.infinity-mainbutton', _mainmenuToggle);
$('.' + subMenuButtonClass).on('click.infinity-subbutton', _submenuToggle);
};
// add nav class and ID to related button
function _addClassID() {
var $this = $(this),
nav = $this.next('nav'),
id = 'class';
$this.addClass($(nav).attr('class'));
if ($(nav).attr('id')) {
id = 'id';
}
$this.attr('id', 'mobile-' + $(nav).attr(id));
}
// Change Skiplinks and Superfish
function _doResize() {
var buttons = $('button[id^=mobile-]').attr('id');
if (typeof buttons === 'undefined') {
return;
}
_superfishToggle(buttons);
_changeSkipLink(buttons);
_maybeClose(buttons);
}
/**
* action to happen when the main menu button is clicked
*/
function _mainmenuToggle() {
var $this = $(this);
_toggleAria($this, 'aria-pressed');
_toggleAria($this, 'aria-expanded');
$this.toggleClass('activated');
$('nav.nav-primary').slideToggle('fast'); //changed to .nav-primary since we're not toggling .nav-secondary
}
/**
* action for submenu toggles
*/
function _submenuToggle() {
var $this = $(this),
others = $this.closest('.menu-item').siblings();
_toggleAria($this, 'aria-pressed');
_toggleAria($this, 'aria-expanded');
$this.toggleClass('activated');
$this.next('.sub-menu').slideToggle('fast');
others.find('.' + subMenuButtonClass).removeClass('activated').attr('aria-pressed', 'false');
others.find('.sub-menu').slideUp('fast');
}
/**
* activate/deactivate superfish
*/
function _superfishToggle(buttons) {
if (typeof $('.js-superfish').superfish !== 'function') {
return;
}
if ('none' === _getDisplayValue(buttons)) {
$('.js-superfish').superfish({
'delay': 100,
'animation': {
'opacity': 'show',
'height': 'show'
},
'dropShadows': false
});
} else {
$('.js-superfish').superfish('destroy');
}
}
/**
* modify skip links to match mobile buttons
*/
function _changeSkipLink(buttons) {
var startLink = 'genesis-nav',
endLink = 'mobile-genesis-nav';
if ('none' === _getDisplayValue(buttons)) {
startLink = 'mobile-genesis-nav';
endLink = 'genesis-nav';
}
$('.genesis-skip-link a[href^="#' + startLink + '"]').each(function() {
var link = $(this).attr('href');
link = link.replace(startLink, endLink);
$(this).attr('href', link);
});
}
function _maybeClose(buttons) {
if ('none' !== _getDisplayValue(buttons)) {
return;
}
$('.menu-toggle, .sub-menu-toggle')
.removeClass('activated')
.attr('aria-expanded', false)
.attr('aria-pressed', false);
$('nav, .sub-menu')
.attr('style', '');
}
/**
* generic function to get the display value of an element
* #param {id} $id ID to check
* #return {string} CSS value of display property
*/
function _getDisplayValue($id) {
var element = document.getElementById($id),
style = window.getComputedStyle(element);
return style.getPropertyValue('display');
}
/**
* Toggle aria attributes
* #param {button} $this passed through
* #param {aria-xx} attribute aria attribute to toggle
* #return {bool} from _ariaReturn
*/
function _toggleAria($this, attribute) {
$this.attr(attribute, function(index, value) {
return 'false' === value;
});
}
$(function(){
$('#genesis-nav-primary li').click(function()
{
$('nav.nav-primary').slideToggle('fast');
});
});
$(document).ready(function() {
infinity.params = typeof InfinityL10n === 'undefined' ? '' : InfinityL10n;
if (typeof infinity.params !== 'undefined') {
infinity.init();
}
});
})(document, jQuery);

Related

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>

How to avoid getting same functionality by jquery in same multiple elements?

I've very little knowledge at jQuery. I'm working at a webpage. There are different kinds of select option element at that page. Among one of them, I've to use a jQuery Dropdown checkbox. This one, I've used.
I can implement this at my webpage successfully. But, problem is it affects all my Select option element!! I've different class name for different select element. like
<select name="company" class="company">
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
</select>
<select name="institute" class="institute">
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
</select>
<select name="group" class="dropdownCheckbox">
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
</select>
I've used the jquery at last one(class="dropdownCheckbox"). But, it affected all the select element. I can't understand how I edit the jquery defining only for class="dropdownCheckbox".
This is the javascript code for HTML file:
<script type="text/javascript">
$(function(){
$("select").multiselect();
});
</script>
And the main javasript file for the effect(jquery.multiselect.js):
(function($, undefined) {
var multiselectID = 0;
var $doc = $(document);
$.widget("ech.multiselect.dropdownCheckbox", {
// default options
options: {
header: true,
height: 175,
minWidth: 310,
classes: 'dropdownCheckbox',
checkAllText: 'Check all',
uncheckAllText: 'Uncheck all',
noneSelectedText: 'Select Group',
selectedText: 'Select Group',
selectedList: 0,
show: null,
hide: null,
autoOpen: false,
multiple: true,
position: {},
appendTo: "body"
},
_create: function() {
var el = this.element.hide();
var o = this.options;
this.speed = $.fx.speeds._default; // default speed for effects
this._isOpen = false; // assume no
// create a unique namespace for events that the widget
// factory cannot unbind automatically. Use eventNamespace if on
// jQuery UI 1.9+, and otherwise fallback to a custom string.
this._namespaceID = this.eventNamespace || ('multiselect' + multiselectID);
var button = (this.button = $('<button type="button"><span class="ui-icon ui-icon-triangle-1-s"></span></button>'))
.addClass('ui-multiselect ui-widget ui-state-default ui-corner-all')
.addClass(o.classes)
.attr({ 'title':el.attr('title'), 'aria-haspopup':true, 'tabIndex':el.attr('tabIndex') })
.insertAfter(el),
buttonlabel = (this.buttonlabel = $('<span />'))
.html(o.noneSelectedText)
.appendTo(button),
menu = (this.menu = $('<div />'))
.addClass('ui-multiselect-menu ui-widget ui-widget-content ui-corner-all')
.addClass(o.classes)
.appendTo($(o.appendTo)),
header = (this.header = $('<div />'))
.addClass('ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix')
.appendTo(menu),
headerLinkContainer = (this.headerLinkContainer = $('<ul />'))
.addClass('ui-helper-reset')
.html(function() {
if(o.header === true) {
return '<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>' + o.checkAllText + '</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>' + o.uncheckAllText + '</span></a></li>';
} else if(typeof o.header === "string") {
return '<li>' + o.header + '</li>';
} else {
return '';
}
})
.append('<li class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></li>')
.appendTo(header),
checkboxContainer = (this.checkboxContainer = $('<ul />'))
.addClass('ui-multiselect-checkboxes ui-helper-reset')
.appendTo(menu);
// perform event bindings
this._bindEvents();
// build menu
this.refresh(true);
// some addl. logic for single selects
if(!o.multiple) {
menu.addClass('ui-multiselect-single');
}
// bump unique ID
multiselectID++;
},
_init: function() {
if(this.options.header === false) {
this.header.hide();
}
if(!this.options.multiple) {
this.headerLinkContainer.find('.ui-multiselect-all, .ui-multiselect-none').hide();
}
if(this.options.autoOpen) {
this.open();
}
if(this.element.is(':disabled')) {
this.disable();
}
},
refresh: function(init) {
var el = this.element;
var o = this.options;
var menu = this.menu;
var checkboxContainer = this.checkboxContainer;
var optgroups = [];
var html = "";
var id = el.attr('id') || multiselectID++; // unique ID for the label & option tags
// build items
el.find('option').each(function(i) {
var $this = $(this);
var parent = this.parentNode;
var description = this.innerHTML;
var title = this.title;
var value = this.value;
var inputID = 'ui-multiselect-' + (this.id || id + '-option-' + i);
var isDisabled = this.disabled;
var isSelected = this.selected;
var labelClasses = [ 'ui-corner-all' ];
var liClasses = (isDisabled ? 'ui-multiselect-disabled ' : ' ') + this.className;
var optLabel;
// is this an optgroup?
if(parent.tagName === 'OPTGROUP') {
optLabel = parent.getAttribute('label');
// has this optgroup been added already?
if($.inArray(optLabel, optgroups) === -1) {
html += '<li class="ui-multiselect-optgroup-label ' + parent.className + '">' + optLabel + '</li>';
optgroups.push(optLabel);
}
}
if(isDisabled) {
labelClasses.push('ui-state-disabled');
}
// browsers automatically select the first option
// by default with single selects
if(isSelected && !o.multiple) {
labelClasses.push('ui-state-active');
}
html += '<li class="' + liClasses + '">';
// create the label
html += '<label for="' + inputID + '" title="' + title + '" class="' + labelClasses.join(' ') + '">';
html += '<input id="' + inputID + '" name="multiselect_' + id + '" type="' + (o.multiple ? "checkbox" : "radio") + '" value="' + value + '" title="' + title + '"';
// pre-selected?
if(isSelected) {
html += ' checked="checked"';
html += ' aria-selected="true"';
}
// disabled?
if(isDisabled) {
html += ' disabled="disabled"';
html += ' aria-disabled="true"';
}
// add the title and close everything off
html += ' /><span>' + description + '</span></label></li>';
});
// insert into the DOM
checkboxContainer.html(html);
// cache some moar useful elements
this.labels = menu.find('label');
this.inputs = this.labels.children('input');
// set widths
this._setButtonWidth();
this._setMenuWidth();
// remember default value
this.button[0].defaultValue = this.update();
// broadcast refresh event; useful for widgets
if(!init) {
this._trigger('refresh');
}
},
// updates the button text. call refresh() to rebuild
update: function() {
var o = this.options;
var $inputs = this.inputs;
var $checked = $inputs.filter(':checked');
var numChecked = $checked.length;
var value;
if(numChecked === 0) {
value = o.noneSelectedText;
} else {
if($.isFunction(o.selectedText)) {
value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get());
} else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) {
value = $checked.map(function() { return $(this).next().html(); }).get().join(', ');
} else {
value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length);
}
}
this._setButtonValue(value);
return value;
},
// this exists as a separate method so that the developer
// can easily override it.
_setButtonValue: function(value) {
this.buttonlabel.text(value);
},
// binds events
_bindEvents: function() {
var self = this;
var button = this.button;
function clickHandler() {
self[ self._isOpen ? 'close' : 'open' ]();
return false;
}
// webkit doesn't like it when you click on the span :(
button
.find('span')
.bind('click.multiselect', clickHandler);
// button events
button.bind({
click: clickHandler,
keypress: function(e) {
switch(e.which) {
case 27: // esc
case 38: // up
case 37: // left
self.close();
break;
case 39: // right
case 40: // down
self.open();
break;
}
},
mouseenter: function() {
if(!button.hasClass('ui-state-disabled')) {
$(this).addClass('ui-state-hover');
}
},
mouseleave: function() {
$(this).removeClass('ui-state-hover');
},
focus: function() {
if(!button.hasClass('ui-state-disabled')) {
$(this).addClass('ui-state-focus');
}
},
blur: function() {
$(this).removeClass('ui-state-focus');
}
});
// header links
this.header.delegate('a', 'click.multiselect', function(e) {
// close link
if($(this).hasClass('ui-multiselect-close')) {
self.close();
// check all / uncheck all
} else {
self[$(this).hasClass('ui-multiselect-all') ? 'checkAll' : 'uncheckAll']();
}
e.preventDefault();
});
// optgroup label toggle support
this.menu.delegate('li.ui-multiselect-optgroup-label a', 'click.multiselect', function(e) {
e.preventDefault();
var $this = $(this);
var $inputs = $this.parent().nextUntil('li.ui-multiselect-optgroup-label').find('input:visible:not(:disabled)');
var nodes = $inputs.get();
var label = $this.parent().text();
// trigger event and bail if the return is false
if(self._trigger('beforeoptgrouptoggle', e, { inputs:nodes, label:label }) === false) {
return;
}
// toggle inputs
self._toggleChecked(
$inputs.filter(':checked').length !== $inputs.length,
$inputs
);
self._trigger('optgrouptoggle', e, {
inputs: nodes,
label: label,
checked: nodes[0].checked
});
})
.delegate('label', 'mouseenter.multiselect', function() {
if(!$(this).hasClass('ui-state-disabled')) {
self.labels.removeClass('ui-state-hover');
$(this).addClass('ui-state-hover').find('input').focus();
}
})
.delegate('label', 'keydown.multiselect', function(e) {
e.preventDefault();
switch(e.which) {
case 9: // tab
case 27: // esc
self.close();
break;
case 38: // up
case 40: // down
case 37: // left
case 39: // right
self._traverse(e.which, this);
break;
case 13: // enter
$(this).find('input')[0].click();
break;
}
})
.delegate('input[type="checkbox"], input[type="radio"]', 'click.multiselect', function(e) {
var $this = $(this);
var val = this.value;
var checked = this.checked;
var tags = self.element.find('option');
// bail if this input is disabled or the event is cancelled
if(this.disabled || self._trigger('click', e, { value: val, text: this.title, checked: checked }) === false) {
e.preventDefault();
return;
}
// make sure the input has focus. otherwise, the esc key
// won't close the menu after clicking an item.
$this.focus();
// toggle aria state
$this.attr('aria-selected', checked);
// change state on the original option tags
tags.each(function() {
if(this.value === val) {
this.selected = checked;
} else if(!self.options.multiple) {
this.selected = false;
}
});
// some additional single select-specific logic
if(!self.options.multiple) {
self.labels.removeClass('ui-state-active');
$this.closest('label').toggleClass('ui-state-active', checked);
// close menu
self.close();
}
// fire change on the select box
self.element.trigger("change");
// setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827
// http://bugs.jquery.com/ticket/3827
setTimeout($.proxy(self.update, self), 10);
});
// close each widget when clicking on any other element/anywhere else on the page
$doc.bind('mousedown.' + this._namespaceID, function(event) {
var target = event.target;
if(self._isOpen
&& target !== self.button[0]
&& target !== self.menu[0]
&& !$.contains(self.menu[0], target)
&& !$.contains(self.button[0], target)
) {
self.close();
}
});
// deal with form resets. the problem here is that buttons aren't
// restored to their defaultValue prop on form reset, and the reset
// handler fires before the form is actually reset. delaying it a bit
// gives the form inputs time to clear.
$(this.element[0].form).bind('reset.multiselect', function() {
setTimeout($.proxy(self.refresh, self), 10);
});
},
// set button width
_setButtonWidth: function() {
var width = this.element.outerWidth();
var o = this.options;
if(/\d/.test(o.minWidth) && width < o.minWidth) {
width = o.minWidth;
}
// set widths
this.button.outerWidth(width);
},
// set menu width
_setMenuWidth: function() {
var m = this.menu;
m.outerWidth(this.button.outerWidth());
},
// move up or down within the menu
_traverse: function(which, start) {
var $start = $(start);
var moveToLast = which === 38 || which === 37;
// select the first li that isn't an optgroup label / disabled
var $next = $start.parent()[moveToLast ? 'prevAll' : 'nextAll']('li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)').first();
// if at the first/last element
if(!$next.length) {
var $container = this.menu.find('ul').last();
// move to the first/last
this.menu.find('label')[ moveToLast ? 'last' : 'first' ]().trigger('mouseover');
// set scroll position
$container.scrollTop(moveToLast ? $container.height() : 0);
} else {
$next.find('label').trigger('mouseover');
}
},
// This is an internal function to toggle the checked property and
// other related attributes of a checkbox.
//
// The context of this function should be a checkbox; do not proxy it.
_toggleState: function(prop, flag) {
return function() {
if(!this.disabled) {
this[ prop ] = flag;
}
if(flag) {
this.setAttribute('aria-selected', true);
} else {
this.removeAttribute('aria-selected');
}
};
},
_toggleChecked: function(flag, group) {
var $inputs = (group && group.length) ? group : this.inputs;
var self = this;
// toggle state on inputs
$inputs.each(this._toggleState('checked', flag));
// give the first input focus
$inputs.eq(0).focus();
// update button text
this.update();
// gather an array of the values that actually changed
var values = $inputs.map(function() {
return this.value;
}).get();
// toggle state on original option tags
this.element
.find('option')
.each(function() {
if(!this.disabled && $.inArray(this.value, values) > -1) {
self._toggleState('selected', flag).call(this);
}
});
// trigger the change event on the select
if($inputs.length) {
this.element.trigger("change");
}
},
_toggleDisabled: function(flag) {
this.button.attr({ 'disabled':flag, 'aria-disabled':flag })[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
var inputs = this.menu.find('input');
var key = "ech-multiselect-disabled";
if(flag) {
// remember which elements this widget disabled (not pre-disabled)
// elements, so that they can be restored if the widget is re-enabled.
inputs = inputs.filter(':enabled').data(key, true)
} else {
inputs = inputs.filter(function() {
return $.data(this, key) === true;
}).removeData(key);
}
inputs
.attr({ 'disabled':flag, 'arial-disabled':flag })
.parent()[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
this.element.attr({
'disabled':flag,
'aria-disabled':flag
});
},
// open the menu
open: function(e) {
var self = this;
var button = this.button;
var menu = this.menu;
var speed = this.speed;
var o = this.options;
var args = [];
// bail if the multiselectopen event returns false, this widget is disabled, or is already open
if(this._trigger('beforeopen') === false || button.hasClass('ui-state-disabled') || this._isOpen) {
return;
}
var $container = menu.find('ul').last();
var effect = o.show;
// figure out opening effects/speeds
if($.isArray(o.show)) {
effect = o.show[0];
speed = o.show[1] || self.speed;
}
// if there's an effect, assume jQuery UI is in use
// build the arguments to pass to show()
if(effect) {
args = [ effect, speed ];
}
// set the scroll of the checkbox container
$container.scrollTop(0).height(o.height);
// positon
this.position();
// show the menu, maybe with a speed/effect combo
$.fn.show.apply(menu, args);
// select the first not disabled option
// triggering both mouseover and mouseover because 1.4.2+ has a bug where triggering mouseover
// will actually trigger mouseenter. the mouseenter trigger is there for when it's eventually fixed
this.labels.filter(':not(.ui-state-disabled)').eq(0).trigger('mouseover').trigger('mouseenter').find('input').trigger('focus');
button.addClass('ui-state-active');
this._isOpen = true;
this._trigger('open');
},
// close the menu
close: function() {
if(this._trigger('beforeclose') === false) {
return;
}
var o = this.options;
var effect = o.hide;
var speed = this.speed;
var args = [];
// figure out opening effects/speeds
if($.isArray(o.hide)) {
effect = o.hide[0];
speed = o.hide[1] || this.speed;
}
if(effect) {
args = [ effect, speed ];
}
$.fn.hide.apply(this.menu, args);
this.button.removeClass('ui-state-active').trigger('blur').trigger('mouseleave');
this._isOpen = false;
this._trigger('close');
},
enable: function() {
this._toggleDisabled(false);
},
disable: function() {
this._toggleDisabled(true);
},
checkAll: function(e) {
this._toggleChecked(true);
this._trigger('checkAll');
},
uncheckAll: function() {
this._toggleChecked(false);
this._trigger('uncheckAll');
},
getChecked: function() {
return this.menu.find('input').filter(':checked');
},
destroy: function() {
// remove classes + data
$.Widget.prototype.destroy.call(this);
// unbind events
$doc.unbind(this._namespaceID);
this.button.remove();
this.menu.remove();
this.element.show();
return this;
},
isOpen: function() {
return this._isOpen;
},
widget: function() {
return this.menu;
},
getButton: function() {
return this.button;
},
position: function() {
var o = this.options;
// use the position utility if it exists and options are specifified
if($.ui.position && !$.isEmptyObject(o.position)) {
o.position.of = o.position.of || this.button;
this.menu
.show()
.position(o.position)
.hide();
// otherwise fallback to custom positioning
} else {
var pos = this.button.offset();
this.menu.css({
top: pos.top + this.button.outerHeight(),
left: pos.left
});
}
},
// react to option changes after initialization
_setOption: function(key, value) {
var menu = this.menu;
switch(key) {
case 'header':
menu.find('div.ui-multiselect-header')[value ? 'show' : 'hide']();
break;
case 'checkAllText':
menu.find('a.ui-multiselect-all span').eq(-1).text(value);
break;
case 'uncheckAllText':
menu.find('a.ui-multiselect-none span').eq(-1).text(value);
break;
case 'height':
menu.find('ul').last().height(parseInt(value, 10));
break;
case 'minWidth':
this.options[key] = parseInt(value, 10);
this._setButtonWidth();
this._setMenuWidth();
break;
case 'selectedText':
case 'selectedList':
case 'noneSelectedText':
this.options[key] = value; // these all needs to update immediately for the update() call
this.update();
break;
case 'classes':
menu.add(this.button).removeClass(this.options.classes).addClass(value);
break;
case 'multiple':
menu.toggleClass('ui-multiselect-single', !value);
this.options.multiple = value;
this.element[0].multiple = value;
this.refresh();
break;
case 'position':
this.position();
}
$.Widget.prototype._setOption.apply(this, arguments);
}
});
})(jQuery);
How can I make this jquery active only for class="dropdownCheckbox"?
you can use
$(".dropdownCheckbox").multiselect();
You can use the class selector
<script type="text/javascript">
$(function(){
$("select.company").multiselect();
// Targets the select with class="company"
});
</script>
jQuery uses the same selctors as CSS does :)

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

jeditable to update database?

I need the jeditable plugin to update the ProductName in the database when it gets edited. As of right now the ProductName only updates on the page. I didn't install this plugin so I'm not familiar with how it works or the code behind it all. I am just looking for some help, I understand that the code might look funky, but I didn't write any of this. Thanks
ProductPage.js
$(document).ready(function () {
// EDIT PRODUCT NAME
$('.productName.edit').editable(function (value, settings) {
var ProductID = $('input#body_ProductID').val();
var result = SubmitProductName(ProductID, value);
return (value);
}, {
width: '350',
submit: 'Save Changes',
cancel: 'Cancel',
onBlur: 'ignore'
});
// this makes the call to the webservice to update the product name
The problem is right here in the SubmitProductName function. After putting alerts in the javascript, I found out that the UpdateProductName url was never getting hit
function SubmitProductName(ProductID, NewName) {
var result;
**$.ajax({
type: "POST",
data: '{ "ProductID" : "' + ProductID + '", "UpdateText" : "' + NewName + '"}',
url: '../WebService.asmx/UpdateProductName',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (json) {
result = json.d;
},**
error: function (e) {
result = "error";
}
});
}
});
WebService.vb
'Updates a product and returns the new product name
<WebMethod()> _
Public Function UpdateProductName(ProductID As String, UpdateText As String) As String
Dim sqlUpdate As String = "UPDATE Product SET ProductName = '" & UpdateText & "' WHERE ProductID = " & ProductID
Dim sqlResults As String = "SELECT ProductName FROM Product WHERE ProductID = " & ProductID
'Create sql connection object
Dim sqlConn As New SqlConnection("Server=off-db1;uid=productsDB_admin;pwd=*******;database=Products")
'Open SQL connection
sqlConn.Open()
'SQL Statement to get CategoryIDs and Names of all subcategories
Dim myCommand As New SqlCommand(sqlUpdate, sqlConn)
myCommand.ExecuteNonQuery()
Dim cmdResults As New SqlCommand(sqlResults, sqlConn)
Dim myReader As SqlDataReader = cmdResults.ExecuteReader()
Dim results As String = Nothing
While myReader.Read
results = myReader(0)
End While
myReader.Close()
sqlConn.Close()
Return results
End Function
jeditable.js
(function($) {
$.fn.editable = function(target, options) {
if ('disable' == target) {
$(this).data('disabled.editable', true);
return;
}
if ('enable' == target) {
$(this).data('disabled.editable', false);
return;
}
if ('destroy' == target) {
$(this)
.unbind($(this).data('event.editable'))
.removeData('disabled.editable')
.removeData('event.editable');
return;
}
var settings = $.extend({}, $.fn.editable.defaults, {target:target}, options);
/* setup some functions */
var plugin = $.editable.types[settings.type].plugin || function() { };
var submit = $.editable.types[settings.type].submit || function() { };
var buttons = $.editable.types[settings.type].buttons
|| $.editable.types['defaults'].buttons;
var content = $.editable.types[settings.type].content
|| $.editable.types['defaults'].content;
var element = $.editable.types[settings.type].element
|| $.editable.types['defaults'].element;
var reset = $.editable.types[settings.type].reset
|| $.editable.types['defaults'].reset;
var callback = settings.callback || function() { };
var onedit = settings.onedit || function() { };
var onsubmit = settings.onsubmit || function() { };
var onreset = settings.onreset || function() { };
var onerror = settings.onerror || reset;
/* show tooltip */
if (settings.tooltip) {
$(this).attr('title', settings.tooltip);
}
settings.autowidth = 'auto' == settings.width;
settings.autoheight = 'auto' == settings.height;
return this.each(function() {
/* save this to self because this changes when scope changes */
var self = this;
/* inlined block elements lose their width and height after first edit */
/* save them for later use as workaround */
var savedwidth = $(self).width();
var savedheight = $(self).height();
/* save so it can be later used by $.editable('destroy') */
$(this).data('event.editable', settings.event);
/* if element is empty add something clickable (if requested) */
if (!$.trim($(this).html())) {
$(this).html(settings.placeholder);
}
$(this).bind(settings.event, function(e) {
/* abort if disabled for this element */
if (true === $(this).data('disabled.editable')) {
return;
}
/* prevent throwing an exeption if edit field is clicked again */
if (self.editing) {
return;
}
/* abort if onedit hook returns false */
if (false === onedit.apply(this, [settings, self])) {
return;
}
/* prevent default action and bubbling */
e.preventDefault();
e.stopPropagation();
/* remove tooltip */
if (settings.tooltip) {
$(self).removeAttr('title');
}
/* figure out how wide and tall we are, saved width and height */
/* are workaround for http://dev.jquery.com/ticket/2190 */
if (0 == $(self).width()) {
//$(self).css('visibility', 'hidden');
settings.width = savedwidth;
settings.height = savedheight;
} else {
if (settings.width != 'none') {
settings.width =
settings.autowidth ? $(self).width() : settings.width;
}
if (settings.height != 'none') {
settings.height =
settings.autoheight ? $(self).height() : settings.height;
}
}
//$(this).css('visibility', '');
/* remove placeholder text, replace is here because of IE */
if ($(this).html().toLowerCase().replace(/(;|")/g, '') ==
settings.placeholder.toLowerCase().replace(/(;|")/g, '')) {
$(this).html('');
}
self.editing = true;
self.revert = $(self).html();
$(self).html('');
/* create the form object */
var form = $('<form />');
/* apply css or style or both */
if (settings.cssclass) {
if ('inherit' == settings.cssclass) {
form.attr('class', $(self).attr('class'));
} else {
form.attr('class', settings.cssclass);
}
}
if (settings.style) {
if ('inherit' == settings.style) {
form.attr('style', $(self).attr('style'));
/* IE needs the second line or display wont be inherited */
form.css('display', $(self).css('display'));
} else {
form.attr('style', settings.style);
}
}
/* add main input element to form and store it in input */
var input = element.apply(form, [settings, self]);
/* set input content via POST, GET, given data or existing value */
var input_content;
if (settings.loadurl) {
var t = setTimeout(function() {
input.disabled = true;
content.apply(form, [settings.loadtext, settings, self]);
}, 100);
var loaddata = {};
loaddata[settings.id] = self.id;
if ($.isFunction(settings.loaddata)) {
$.extend(loaddata, settings.loaddata.apply(self, [self.revert,
settings]));
} else {
$.extend(loaddata, settings.loaddata);
}
$.ajax({
type : settings.loadtype,
url : settings.loadurl,
data : loaddata,
async : false,
success: function(result) {
window.clearTimeout(t);
input_content = result;
input.disabled = false;
}
});
} else if (settings.data) {
input_content = settings.data;
if ($.isFunction(settings.data)) {
input_content = settings.data.apply(self, [self.revert, settings]);
}
} else {
input_content = self.revert;
}
content.apply(form, [input_content, settings, self]);
input.attr('name', settings.name);
/* add buttons to the form */
buttons.apply(form, [settings, self]);
/* add created form to self */
$(self).append(form);
/* attach 3rd party plugin if requested */
plugin.apply(form, [settings, self]);
/* focus to first visible form element */
$(':input:visible:enabled:first', form).focus();
/* highlight input contents when requested */
if (settings.select) {
input.select();
}
/* discard changes if pressing esc */
input.keydown(function(e) {
if (e.keyCode == 27) {
e.preventDefault();
//self.reset();
reset.apply(form, [settings, self]);
}
});
/* discard, submit or nothing with changes when clicking outside */
/* do nothing is usable when navigating with tab */
var t;
if ('cancel' == settings.onblur) {
input.blur(function(e) {
/* prevent canceling if submit was clicked */
t = setTimeout(function() {
reset.apply(form, [settings, self]);
}, 500);
});
} else if ('submit' == settings.onblur) {
input.blur(function(e) {
/* prevent double submit if submit was clicked */
t = setTimeout(function() {
form.submit();
}, 200);
});
} else if ($.isFunction(settings.onblur)) {
input.blur(function(e) {
settings.onblur.apply(self, [input.val(), settings]);
});
} else {
input.blur(function(e) {
/* TODO: maybe something here */
});
}
form.submit(function(e) {
if (t) {
clearTimeout(t);
}
/* do no submit */
e.preventDefault();
/* call before submit hook. */
/* if it returns false abort submitting */
if (false !== onsubmit.apply(form, [settings, self])) {
/* custom inputs call before submit hook. */
/* if it returns false abort submitting */
if (false !== submit.apply(form, [settings, self])) {
/* check if given target is function */
if ($.isFunction(settings.target)) {
var str = settings.target.apply(self, [input.val(),
settings]);
$(self).html(str);
self.editing = false;
callback.apply(self, [self.innerHTML, settings]);
/* TODO: this is not dry */
if (!$.trim($(self).html())) {
$(self).html(settings.placeholder);
}
} else {
/* add edited content and id of edited element to POST */
var submitdata = {};
submitdata[settings.name] = input.val();
submitdata[settings.id] = self.id;
/* add extra data to be POST:ed */
if ($.isFunction(settings.submitdata)) {
$.extend(submitdata, settings.submitdata.apply(self,
[self.revert, settings]));
} else {
$.extend(submitdata, settings.submitdata);
}
/* quick and dirty PUT support */
if ('PUT' == settings.method) {
submitdata['_method'] = 'put';
}
/* show the saving indicator */
$(self).html(settings.indicator);
/* defaults for ajaxoptions */
var ajaxoptions = {
type : 'POST',
data : submitdata,
dataType: 'html',
url : settings.target,
success : function(result, status) {
if (ajaxoptions.dataType == 'html') {
$(self).html(result);
}
self.editing = false;
callback.apply(self, [result, settings]);
if (!$.trim($(self).html())) {
$(self).html(settings.placeholder);
}
},
error : function(xhr, status, error) {
onerror.apply(form, [settings, self, xhr]);
}
};
/* override with what is given in settings.ajaxoptions */
$.extend(ajaxoptions, settings.ajaxoptions);
$.ajax(ajaxoptions);
}
}
}
/* show tooltip again */
$(self).attr('title', settings.tooltip);
return false;
});
});
/* privileged methods */
this.reset = function(form) {
/* prevent calling reset twice when blurring */
if (this.editing) {
/* before reset hook, if it returns false abort reseting */
if (false !== onreset.apply(form, [settings, self])) {
$(self).html(self.revert);
self.editing = false;
if (!$.trim($(self).html())) {
$(self).html(settings.placeholder);
}
/* show tooltip again */
if (settings.tooltip) {
$(self).attr('title', settings.tooltip);
}
}
}
};
});
};
$.editable = {
types: {
defaults: {
element : function(settings, original) {
var input = $('<input type="hidden"></input>');
$(this).append(input);
return(input);
},
content : function(string, settings, original) {
$(':input:first', this).val(string);
},
reset : function(settings, original) {
original.reset(this);
},
buttons : function(settings, original) {
var form = this;
if (settings.submit) {
/* if given html string use that */
if (settings.submit.match(/>$/)) {
var submit = $(settings.submit).click(function() {
if (submit.attr("type") != "submit") {
form.submit();
}
});
/* otherwise use button with given string as text */
} else {
var submit = $('<button type="submit" />');
submit.html(settings.submit);
}
$(this).append(submit);
}
if (settings.cancel) {
/* if given html string use that */
if (settings.cancel.match(/>$/)) {
var cancel = $(settings.cancel);
/* otherwise use button with given string as text */
} else {
var cancel = $('<button type="cancel" />');
cancel.html(settings.cancel);
}
$(this).append(cancel);
$(cancel).click(function(event) {
//original.reset();
if ($.isFunction($.editable.types[settings.type].reset)) {
var reset = $.editable.types[settings.type].reset;
} else {
var reset = $.editable.types['defaults'].reset;
}
reset.apply(form, [settings, original]);
return false;
});
}
}
},
text: {
element : function(settings, original) {
var input = $('<input />');
if (settings.width != 'none') { input.width(settings.width); }
if (settings.height != 'none') { input.height(settings.height); }
/* https://bugzilla.mozilla.org/show_bug.cgi?id=236791 */
//input[0].setAttribute('autocomplete','off');
input.attr('autocomplete','off');
$(this).append(input);
return(input);
}
},
textarea: {
element : function(settings, original) {
var textarea = $('<textarea />');
if (settings.rows) {
textarea.attr('rows', settings.rows);
} else if (settings.height != "none") {
textarea.height(settings.height);
}
if (settings.cols) {
textarea.attr('cols', settings.cols);
} else if (settings.width != "none") {
textarea.width(settings.width);
}
$(this).append(textarea);
return(textarea);
}
},
select: {
element : function(settings, original) {
var select = $('<select />');
$(this).append(select);
return(select);
},
content : function(data, settings, original) {
/* If it is string assume it is json. */
if (String == data.constructor) {
eval ('var json = ' + data);
} else {
/* Otherwise assume it is a hash already. */
var json = data;
}
for (var key in json) {
if (!json.hasOwnProperty(key)) {
continue;
}
if ('selected' == key) {
continue;
}
var option = $('<option />').val(key).append(json[key]);
$('select', this).append(option);
}
/* Loop option again to set selected. IE needed this... */
$('select', this).children().each(function() {
if ($(this).val() == json['selected'] ||
$(this).text() == $.trim(original.revert)) {
$(this).attr('selected', 'selected');
}
});
}
}
},
/* Add new input type */
addInputType: function(name, input) {
$.editable.types[name] = input;
}
};
// publicly accessible defaults
$.fn.editable.defaults = {
name : 'value',
id : 'id',
type : 'text',
width : 'auto',
height : 'auto',
event : 'click.editable',
onblur : 'cancel',
loadtype : 'GET',
loadtext : 'Loading...',
placeholder: 'No description.',
loaddata : {},
submitdata : {},
ajaxoptions: {}
};
})(jQuery);
You need to write the backend to do the DB update. Javascript is run on the client and can't possibly do it itself. In ASP.NET, you'd usually write a Web Service (.svc or .asmx) that receives the POST jEditable can send to do the database update.
When you call .editable() on an element, the first argument is the URL it should post the result to -- that should point to your web service.
From jEditable's web page:
$(document).ready(function() {
$('.edit').editable('http://www.example.com/save.php');
});
In that case, save.php is the PHP web service... substitute your own.
Try running some diagnostics on your ajax request using something like Firebug. This should give you an idea of what type of issues the request is running into.
My first guess would be url:
'../WebService.asmx/UpdateProductName'
is either one looking in the wrong directory, or two is getting denied by some authentication you have setup in your application.
You could do something like this to display error information about your ajax request on your screen

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

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.

Categories

Resources