IE6-7 Javascript - javascript

I am using the "mimic igoogle tutorial with cookies" by James Padolsey
http://james.padolsey.com/tag/cookies/
I have encountered a problem with the way that IE6 & 7 interprets the javascript. I have found the problem but I have no way of working around it.
The following code is long but the problem is only in one small section
/*
* Script from NETTUTS.com [by James Padolsey] V.2 (ENHANCED, WITH COOKIES!!!)
* #requires jQuery($), jQuery UI & sortable/draggable UI modules & jQuery COOKIE plugin
*/
var iNettuts = {
jQuery : $,
settings : {
columns : '.column',
widgetSelector: '.widget',
handleSelector: '.widget-head',
contentSelector: '.widget-content',
/* If you don't want preferences to be saved change this value to false, otherwise change it to the name of the cookie: */
saveToCookie: false,
widgetDefault : {
movable: true,
removable: true,
collapsible: true,
editable: false,
colorClasses : ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green']
},
widgetIndividual : {
static: {
movable: false,
removable: true,
collapsible: true,
editable: false,
}
},
},
init : function () {
this.attachStylesheet('css/sortable.js.css');
this.sortWidgets();
this.addWidgetControls();
this.makeSortable();
},
getWidgetSettings : function (id) {
var $ = this.jQuery,
settings = this.settings;
return (id&&settings.widgetIndividual[id]) ? $.extend({},settings.widgetDefault,settings.widgetIndividual[id]) : settings.widgetDefault;
},
addWidgetControls : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings;
$(settings.widgetSelector, $(settings.columns)).each(function () {
var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);
if (thisWidgetSettings.removable) {
$(' ').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).click(function () {
if(confirm('This widget will be removed, ok?')) {
$(this).parents(settings.widgetSelector).animate({
opacity: 0
},function () {
$(this).slideUp(function () {
$(this).toggleClass('closed');
/* Save prefs to cookie: */
iNettuts.savePreferences();
});
});
}
return false;
}).appendTo($(settings.handleSelector, this));
}
if (thisWidgetSettings.editable) {
$('Edit').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).toggle(function () {
$(this).css({backgroundPosition: '-66px 0', width: '55px'})
.parents(settings.widgetSelector)
.find('.edit-box').show().find('input').focus();
return false;
},function () {
$(this).css({backgroundPosition: '', width: '20px'})
.parents(settings.widgetSelector)
.find('.edit-box').hide();
return false;
}).appendTo($(settings.handleSelector,this));
$('<div class="edit-box" style="display:none;"/>')
.append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')
.append((function(){
var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';
$(thisWidgetSettings.colorClasses).each(function () {
colorList += '<li class="' + this + '"/>';
});
return colorList + '</ul>';
})())
.append('</ul>')
.insertAfter($(settings.handleSelector,this));
}
if (thisWidgetSettings.collapsible) {
$(' ').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).click(function(){
$(this).parents(settings.widgetSelector).toggleClass('collapsed');
/* Save prefs to cookie: */
iNettuts.savePreferences();
return false;
}).prependTo($(settings.handleSelector,this));
}
});
$('.edit-box').each(function () {
$('input',this).keyup(function () {
$(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>20 ? $(this).val().substr(0,20)+'...' : $(this).val() );
iNettuts.savePreferences();
});
$('ul.colors li',this).click(function () {
var colorStylePattern = /\bcolor-[\w]{1,}\b/,
thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern)
if (thisWidgetColorClass) {
$(this).parents(settings.widgetSelector)
.removeClass(thisWidgetColorClass[0])
.addClass($(this).attr('class').match(colorStylePattern)[0]);
/* Save prefs to cookie: */
iNettuts.savePreferences();
}
return false;
});
});
},
attachStylesheet : function (href) {
var $ = this.jQuery;
return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
},
makeSortable : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings,
$sortableItems = (function () {
var notSortable = null;
$(settings.widgetSelector,$(settings.columns)).each(function (i) {
if (!iNettuts.getWidgetSettings(this.id).movable) {
if(!this.id) {
this.id = 'widget-no-id-' + i;
}
notSortable += '#' + this.id + ',';
}
});
return $('> li:not(' + notSortable + ')', settings.columns);
})();
$sortableItems.find(settings.handleSelector).css({
cursor: 'move'
}).mousedown(function (e) {
$sortableItems.css({width:''});
$(this).parent().css({
width: $(this).parent().width() + 'px'
});
}).mouseup(function () {
if(!$(this).parent().hasClass('dragging')) {
$(this).parent().css({width:''});
} else {
$(settings.columns).sortable('disable');
}
});
$(settings.columns).sortable({
items: $sortableItems,
connectWith: $(settings.columns),
handle: settings.handleSelector,
placeholder: 'widget-placeholder',
forcePlaceholderSize: true,
revert: 300,
delay: 100,
opacity: 0.8,
containment: 'document',
start: function (e,ui) {
$(ui.helper).addClass('dragging');
},
stop: function (e,ui) {
$(ui.item).css({width:''}).removeClass('dragging');
$(settings.columns).sortable('enable');
/* Save prefs to cookie: */
iNettuts.savePreferences();
}
});
},
savePreferences : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings,
cookieString = '';
if(!settings.saveToCookie) {return;}
/* Assemble the cookie string */
$(settings.columns).each(function(i){
cookieString += (i===0) ? '' : '|';
$(settings.widgetSelector,this).each(function(i){
cookieString += (i===0) ? '' : ';';
/* ID of widget: */
cookieString += $(this).attr('id') + ',';
/* Color of widget (color classes) */
cookieString += $(this).attr('class').match(/\bcolor-[\w]{1,}\b/) + ',';
/* Title of widget (replaced used characters) */
cookieString += $('h3:eq(0)',this).text().replace(/\|/g,'[-PIPE-]').replace(/,/g,'[-COMMA-]') + ',';
/* Collapsed/not collapsed widget? : */
cookieString += $(settings.contentSelector,this).css('display') === 'none' ? 'collapsed,' : 'not-collapsed,';
/* Closed/not closed widget? : */
cookieString += $(settings.handleSelector,this).css('display') === 'none' ? 'closed' : 'not-closed';
});
});
$.cookie(settings.saveToCookie,cookieString,{
expires: 10
//path: '/'
});
},
sortWidgets : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings;
/* Read cookie: */
var cookie = $.cookie(settings.saveToCookie);
if(!settings.saveToCookie||!cookie) {
/* Get rid of loading gif and show columns: */
$('body').css({background:'#fff'});
$(settings.columns).css({visibility:'visible'});
return;
}
/* For each column */
$(settings.columns).each(function(i){
var thisColumn = $(this),
widgetData = cookie.split('|')[i].split(';');
$(widgetData).each(function(){
if(!this.length) {return;}
var thisWidgetData = this.split(','),
clonedWidget = $('#' + thisWidgetData[0]),
colorStylePattern = /\bcolor-[\w]{1,}\b/,
thisWidgetColorClass = $(clonedWidget).attr('class').match(colorStylePattern);
/* Add/Replace new colour class: */
if (thisWidgetColorClass) {
$(clonedWidget).removeClass(thisWidgetColorClass[0]).addClass(thisWidgetData[1]);
}
/* Add/replace new title (Bring back reserved characters): */
$(clonedWidget).find('h3:eq(0)').html(thisWidgetData[2].replace(/\[-PIPE-\]/g,'|').replace(/\[-COMMA-\]/g,','));
/* Modify collapsed state if needed: */
if(thisWidgetData[3]==='collapsed') {
/* Set CSS styles so widget is in COLLAPSED state */
$(clonedWidget).addClass('collapsed');
}
/* Modify closed state if needed: */
if(thisWidgetData[4]==='closed') {
/* Set CSS styles so widget is in CLOSED state */
$(clonedWidget).addClass('closed');
}
$('#' + thisWidgetData[0]).remove();
$(thisColumn).append(clonedWidget);
});
});
/* All done, remove loading gif and show columns: */
$('body').css({background:'#fff'});
$(settings.columns).css({visibility:'visible'});
}
};
iNettuts.init();
If I leave this section blank
widgetIndividual : {
static: {
movable: false,
removable: true,
collapsible: true,
editable: false,
}
}
For example, like this
widgetIndividual : {
}
Then it works fine on all browsers, unfortunately I need to use the Individual Widget settings for my project.
IE6-7 throws out an error because of these guys "}", I have no idea why.

Remove the last comma in this object it will work.
widgetIndividual : {
static: {
movable: false,
removable: true,
collapsible: true,
editable: false
}
}

Related

How can I make my JQuery run again when using goBack() in React

I have react app using Switch of react-router-dom. When people click they can see the profile of a person in full, but I want a goBack button, so I did this.
const onClick = () => {
return history.goBack();
}
The problem is, when I go back to the last page, the jQuery libraries I'm using don't work, and even some code I'm using in useEffect. I'm using forceRefresh in my Router so every time I go to another page in the Switch I can see the animations an load the actions, is not the best solution but has been working so far.
EDIT:
I'm adding the jQuery file, maybe this helps. This file is called in index.html of the public folder
<script src="%PUBLIC_URL%/assets/js/custom.js" async defer></script>
Code:
(function ($) {
'use strict';
$(document).ready(function () {
$(function () {
function mmenuInit() {
var wi = $(window).width();
if (wi <= '1099') {
$('.mmenu-init').remove();
$('#navigation')
.clone()
.addClass('mmenu-init')
.insertBefore('#navigation')
.removeAttr('id')
.removeClass('style-1 style-2')
.find('ul, div')
.removeClass(
'style-1 style-2 mega-menu mega-menu-content mega-menu-section'
)
.removeAttr('id');
$('.mmenu-init').find('ul').addClass('mm-listview');
$('.mmenu-init').find('.mobile-styles .mm-listview').unwrap();
$('.mmenu-init').mmenu(
{
counters: true,
},
{
// configuration
offCanvas: {
pageNodetype: '#wrapper',
},
}
);
var mmenuAPI = $('.mmenu-init').data('mmenu');
var $icon = $('.mmenu-trigger .hamburger');
$(document).on('click', '.mmenu-trigger', function () {
mmenuAPI.open();
});
}
$('.mm-next').addClass('mm-fullsubopen');
}
mmenuInit();
$(window).resize(function () {
mmenuInit();
});
});
$(window).on('load resize', function () {
var transparentHeaderHeight = $('.transparent-header').outerHeight();
$('.transparent-header-spacer').css({
height: transparentHeaderHeight,
});
});
$('.ripple-effect, .ripple-effect-dark').on('click', function (e) {
var rippleDiv = $('<span class="ripple-overlay">'),
rippleOffset = $(this).offset(),
rippleY = e.pageY - rippleOffset.top,
rippleX = e.pageX - rippleOffset.left;
rippleDiv
.css({
top: rippleY - rippleDiv.height() / 2,
left: rippleX - rippleDiv.width() / 2,
// background: $(this).data("ripple-color");
})
.appendTo($(this));
window.setTimeout(function () {
rippleDiv.remove();
}, 800);
});
$('.switch, .radio').each(function () {
var intElem = $(this);
intElem.on('click', function () {
intElem.addClass('interactive-effect');
setTimeout(function () {
intElem.removeClass('interactive-effect');
}, 400);
});
});
$(window).on('load', function () {
$('.button.button-sliding-icon')
.not('.task-listing .button.button-sliding-icon')
.each(function () {
var buttonWidth = $(this).outerWidth() + 30;
$(this).css('width', buttonWidth);
});
});
$('.bookmark-icon').on('click', function (e) {
e.preventDefault();
$(this).toggleClass('bookmarked');
});
$('.bookmark-button').on('click', function (e) {
e.preventDefault();
$(this).toggleClass('bookmarked');
});
$('a.close')
.removeAttr('href')
.on('click', function () {
function slideFade(elem) {
var fadeOut = { opacity: 0, transition: 'opacity 0.5s' };
elem.css(fadeOut).slideUp();
}
slideFade($(this).parent());
});
// Closing function
function close_user_dropdown() {
$('.header-notifications').removeClass('active');
}
// Closes notification dropdown on click outside the conatainer
var mouse_is_inside = false;
$('.header-notifications').on('mouseenter', function () {
mouse_is_inside = true;
});
$('.header-notifications').on('mouseleave', function () {
mouse_is_inside = false;
});
$('body').mouseup(function () {
if (!mouse_is_inside) close_user_dropdown();
});
// Close with ESC
$(document).keyup(function (e) {
if (e.keyCode == 27) {
close_user_dropdown();
}
});
if ($('.status-switch label.user-invisible').hasClass('current-status')) {
$('.status-indicator').addClass('right');
}
$('.status-switch label.user-invisible').on('click', function () {
$('.status-indicator').addClass('right');
$('.status-switch label').removeClass('current-status');
$('.user-invisible').addClass('current-status');
});
$('.status-switch label.user-online').on('click', function () {
$('.status-indicator').removeClass('right');
$('.status-switch label').removeClass('current-status');
$('.user-online').addClass('current-status');
});
// Wrapper Height (window height - header height)
function wrapperHeight() {
var headerHeight = $('#header-container').outerHeight();
var windowHeight = $(window).outerHeight() - headerHeight;
$(
'.full-page-content-container, .dashboard-content-container, .dashboard-sidebar-inner, .dashboard-container, .full-page-container'
).css({ height: windowHeight });
$('.dashboard-content-inner').css({ 'min-height': windowHeight });
}
// Enabling Scrollbar
function fullPageScrollbar() {
$('.full-page-sidebar-inner, .dashboard-sidebar-inner').each(function () {
var headerHeight = $('#header-container').outerHeight();
var windowHeight = $(window).outerHeight() - headerHeight;
var sidebarContainerHeight = $(this)
.find('.sidebar-container, .dashboard-nav-container')
.outerHeight();
// Enables scrollbar if sidebar is higher than wrapper
if (sidebarContainerHeight > windowHeight) {
$(this).css({ height: windowHeight });
} else {
$(this).find('.simplebar-track').hide();
}
});
}
// Init
$(window).on('load resize', function () {
wrapperHeight();
fullPageScrollbar();
});
wrapperHeight();
fullPageScrollbar();
// Sliding Sidebar
$('.enable-filters-button').on('click', function () {
$('.full-page-sidebar').toggleClass('enabled-sidebar');
$(this).toggleClass('active');
$('.filter-button-tooltip').removeClass('tooltip-visible');
});
/* Enable Filters Button Tooltip */
$(window).on('load', function () {
$('.filter-button-tooltip')
.css({
left: $('.enable-filters-button').outerWidth() + 48,
})
.addClass('tooltip-visible');
});
// Avatar Switcher
function avatarSwitcher() {
var readURL = function (input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.profile-pic').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
};
$('.file-upload').on('change', function () {
readURL(this);
});
$('.upload-button').on('click', function () {
$('.file-upload').click();
});
}
avatarSwitcher();
// Dashboard Nav Submenus
$('.dashboard-nav ul li a').on('click', function (e) {
if ($(this).closest('li').children('ul').length) {
if ($(this).closest('li').is('.active-submenu')) {
$('.dashboard-nav ul li').removeClass('active-submenu');
} else {
$('.dashboard-nav ul li').removeClass('active-submenu');
$(this).parent('li').addClass('active-submenu');
}
e.preventDefault();
}
});
// Responsive Dashbaord Nav Trigger
$('.dashboard-responsive-nav-trigger').on('click', function (e) {
e.preventDefault();
$(this).toggleClass('active');
var dashboardNavContainer = $('body').find('.dashboard-nav');
if ($(this).hasClass('active')) {
$(dashboardNavContainer).addClass('active');
} else {
$(dashboardNavContainer).removeClass('active');
}
$('.dashboard-responsive-nav-trigger .hamburger').toggleClass(
'is-active'
);
});
// Fun Facts
function funFacts() {
/*jslint bitwise: true */
function hexToRgbA(hex) {
var c;
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
c = hex.substring(1).split('');
if (c.length == 3) {
c = [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c = '0x' + c.join('');
return (
'rgba(' +
[(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') +
',0.07)'
);
}
}
$('.fun-fact').each(function () {
var factColor = $(this).attr('data-fun-fact-color');
if (factColor !== undefined) {
$(this)
.find('.fun-fact-icon')
.css('background-color', hexToRgbA(factColor));
$(this).find('i').css('color', factColor);
}
});
}
funFacts();
// Notes & Messages Scrollbar
$(window).on('load resize', function () {
var winwidth = $(window).width();
if (winwidth > 1199) {
// Notes
$('.row').each(function () {
var mbh = $(this).find('.main-box-in-row').outerHeight();
var cbh = $(this).find('.child-box-in-row').outerHeight();
if (mbh < cbh) {
var headerBoxHeight = $(this)
.find('.child-box-in-row .headline')
.outerHeight();
var mainBoxHeight =
$(this).find('.main-box-in-row').outerHeight() -
headerBoxHeight +
39;
$(this)
.find('.child-box-in-row .content')
.wrap(
'<div class="dashboard-box-scrollbar" style="max-height: ' +
mainBoxHeight +
'px" data-simplebar></div>'
);
}
});
// Messages Sidebar
// var messagesList = $(".messages-inbox").outerHeight();
// var messageWrap = $(".message-content").outerHeight();
// if ( messagesList > messagesWrap) {
// $(messagesList).css({
// 'max-height': messageWrap,
// });
// }
}
});
// Mobile Adjustment for Single Button Icon in Dashboard Box
$('.buttons-to-right').each(function () {
var btr = $(this).width();
if (btr < 36) {
$(this).addClass('single-right-button');
}
});
// Small Footer Adjustment
$(window).on('load resize', function () {
var smallFooterHeight = $('.small-footer').outerHeight();
$('.dashboard-footer-spacer').css({
'padding-top': smallFooterHeight + 45,
});
});
// Auto Resizing Message Input Field
/* global jQuery */
jQuery.each(jQuery('textarea[data-autoresize]'), function () {
var offset = this.offsetHeight - this.clientHeight;
var resizeTextarea = function (el) {
jQuery(el)
.css('height', 'auto')
.css('height', el.scrollHeight + offset);
};
jQuery(this)
.on('keyup input', function () {
resizeTextarea(this);
})
.removeAttr('data-autoresize');
});
function userMenuScrollbar() {
$('.header-notifications-scroll').each(function () {
var scrollContainerList = $(this).find('ul');
var itemsCount = scrollContainerList.children('li').length;
var notificationItems;
// Determines how many items are displayed based on items height
/* jshint shadow:true */
if (scrollContainerList.children('li').outerHeight() > 140) {
var notificationItems = 2;
} else {
var notificationItems = 3;
}
// Enables scrollbar if more than 2 items
if (itemsCount > notificationItems) {
var listHeight = 0;
$(scrollContainerList)
.find('li:lt(' + notificationItems + ')')
.each(function () {
listHeight += $(this).height();
});
$(this).css({ height: listHeight });
} else {
$(this).css({ height: 'auto' });
$(this).find('.simplebar-track').hide();
}
});
}
// Init
userMenuScrollbar();
/* global tippy */
tippy('[data-tippy-placement]', {
delay: 100,
arrow: true,
arrowType: 'sharp',
size: 'regular',
duration: 200,
// 'shift-toward', 'fade', 'scale', 'perspective'
animation: 'shift-away',
animateFill: true,
theme: 'dark',
// How far the tooltip is from its reference element in pixels
distance: 10,
});
var accordion = (function () {
var $accordion = $('.js-accordion');
var $accordion_header = $accordion.find('.js-accordion-header');
// default settings
var settings = {
// animation speed
speed: 400,
// close all other accordion items if true
oneOpen: false,
};
return {
// pass configurable object literal
init: function ($settings) {
$accordion_header.on('click', function () {
accordion.toggle($(this));
});
$.extend(settings, $settings);
// ensure only one accordion is active if oneOpen is true
if (settings.oneOpen && $('.js-accordion-item.active').length > 1) {
$('.js-accordion-item.active:not(:first)').removeClass('active');
}
// reveal the active accordion bodies
$('.js-accordion-item.active').find('> .js-accordion-body').show();
},
toggle: function ($this) {
if (
settings.oneOpen &&
$this[0] !=
$this
.closest('.js-accordion')
.find('> .js-accordion-item.active > .js-accordion-header')[0]
) {
$this
.closest('.js-accordion')
.find('> .js-accordion-item')
.removeClass('active')
.find('.js-accordion-body')
.slideUp();
}
// show/hide the clicked accordion item
$this.closest('.js-accordion-item').toggleClass('active');
$this.next().stop().slideToggle(settings.speed);
},
};
})();
$(document).ready(function () {
accordion.init({ speed: 300, oneOpen: true });
});
$(window).on('load resize', function () {
if ($('.tabs')[0]) {
$('.tabs').each(function () {
var thisTab = $(this);
// Intial Border Position
var activePos = thisTab.find('.tabs-header .active').position();
function changePos() {
// Update Position
activePos = thisTab.find('.tabs-header .active').position();
// Change Position & Width
thisTab
.find('.tab-hover')
.stop()
.css({
left: activePos.left,
width: thisTab.find('.tabs-header .active').width(),
});
}
changePos();
// Intial Tab Height
var tabHeight = thisTab.find('.tab.active').outerHeight();
// Animate Tab Height
function animateTabHeight() {
// Update Tab Height
tabHeight = thisTab.find('.tab.active').outerHeight();
// Animate Height
thisTab
.find('.tabs-content')
.stop()
.css({
height: tabHeight + 'px',
});
}
animateTabHeight();
// Change Tab
function changeTab() {
var getTabId = thisTab
.find('.tabs-header .active a')
.attr('data-tab-id');
// Remove Active State
thisTab
.find('.tab')
.stop()
.fadeOut(300, function () {
// Remove Class
$(this).removeClass('active');
})
.hide();
thisTab
.find('.tab[data-tab-id=' + getTabId + ']')
.stop()
.fadeIn(300, function () {
// Add Class
$(this).addClass('active');
// Animate Height
animateTabHeight();
});
}
// Tabs
thisTab.find('.tabs-header a').on('click', function (e) {
e.preventDefault();
// Tab Id
var tabId = $(this).attr('data-tab-id');
// Remove Active State
thisTab
.find('.tabs-header a')
.stop()
.parent()
.removeClass('active');
// Add Active State
$(this).stop().parent().addClass('active');
changePos();
// Update Current Itm
tabCurrentItem = tabItems.filter('.active');
// Remove Active State
thisTab
.find('.tab')
.stop()
.fadeOut(300, function () {
// Remove Class
$(this).removeClass('active');
})
.hide();
// Add Active State
thisTab
.find('.tab[data-tab-id="' + tabId + '"]')
.stop()
.fadeIn(300, function () {
// Add Class
$(this).addClass('active');
// Animate Height
animateTabHeight();
});
});
// Tab Items
var tabItems = thisTab.find('.tabs-header ul li');
// Tab Current Item
var tabCurrentItem = tabItems.filter('.active');
// Next Button
thisTab.find('.tab-next').on('click', function (e) {
e.preventDefault();
var nextItem = tabCurrentItem.next();
tabCurrentItem.removeClass('active');
if (nextItem.length) {
tabCurrentItem = nextItem.addClass('active');
} else {
tabCurrentItem = tabItems.first().addClass('active');
}
changePos();
changeTab();
});
// Prev Button
thisTab.find('.tab-prev').on('click', function (e) {
e.preventDefault();
var prevItem = tabCurrentItem.prev();
tabCurrentItem.removeClass('active');
if (prevItem.length) {
tabCurrentItem = prevItem.addClass('active');
} else {
tabCurrentItem = tabItems.last().addClass('active');
}
changePos();
changeTab();
});
});
}
});
// Thousand Separator
function ThousandSeparator(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
// Bidding Slider Average Value
var avgValue =
(parseInt($('.bidding-slider').attr('data-slider-min')) +
parseInt($('.bidding-slider').attr('data-slider-max'))) /
2;
if ($('.bidding-slider').data('slider-value') === 'auto') {
$('.bidding-slider').attr({ 'data-slider-value': avgValue });
}
// Bidding Slider Init
$('.bidding-slider').slider();
$('.bidding-slider').on('slide', function (slideEvt) {
$('#biddingVal').text(ThousandSeparator(parseInt(slideEvt.value)));
});
$('#biddingVal').text(
ThousandSeparator(parseInt($('.bidding-slider').val()))
);
// Default Bootstrap Range Slider
var currencyAttr = $('.range-slider').attr('data-slider-currency');
$('.range-slider').slider({
formatter: function (value) {
return (
currencyAttr +
ThousandSeparator(parseInt(value[0])) +
' - ' +
currencyAttr +
ThousandSeparator(parseInt(value[1]))
);
},
});
$('.range-slider-single').slider();
var radios = document.querySelectorAll('.payment-tab-trigger > input');
for (var i = 0; i < radios.length; i++) {
radios[i].addEventListener('change', expandAccordion);
}
function expandAccordion(event) {
/* jshint validthis: true */
var tabber = this.closest('.payment');
var allTabs = tabber.querySelectorAll('.payment-tab');
for (var i = 0; i < allTabs.length; i++) {
allTabs[i].classList.remove('payment-tab-active');
}
event.target.parentNode.parentNode.classList.add('payment-tab-active');
}
$('.billing-cycle-radios').on('click', function () {
if ($('.billed-yearly-radio input').is(':checked')) {
$('.pricing-plans-container').addClass('billed-yearly');
}
if ($('.billed-monthly-radio input').is(':checked')) {
$('.pricing-plans-container').removeClass('billed-yearly');
}
});
function qtySum() {
var arr = document.getElementsByName('qtyInput');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) tot += parseInt(arr[i].value);
}
}
qtySum();
$('.qtyDec, .qtyInc').on('click', function () {
var $button = $(this);
var oldValue = $button.parent().find('input').val();
if ($button.hasClass('qtyInc')) {
$button
.parent()
.find('input')
.val(parseFloat(oldValue) + 1);
} else {
if (oldValue > 1) {
$button
.parent()
.find('input')
.val(parseFloat(oldValue) - 1);
} else {
$button.parent().find('input').val(1);
}
}
qtySum();
$('.qtyTotal').addClass('rotate-x');
});
/* global ClipboardJS */
$('.copy-url input').val(window.location.href);
new ClipboardJS('.copy-url-button');
$('.share-buttons-icons a').each(function () {
var buttonBG = $(this).attr('data-button-color');
if (buttonBG !== undefined) {
$(this).css('background-color', buttonBG);
}
});
var $tabsNav = $('.popup-tabs-nav'),
$tabsNavLis = $tabsNav.children('li');
$tabsNav.each(function () {
var $this = $(this);
$this
.next()
.children('.popup-tab-content')
.stop(true, true)
.hide()
.first()
.show();
$this.children('li').first().addClass('active').stop(true, true).show();
});
$tabsNavLis.on('click', function (e) {
var $this = $(this);
$this.siblings().removeClass('active').end().addClass('active');
$this
.parent()
.next()
.children('.popup-tab-content')
.stop(true, true)
.hide()
.siblings($this.find('a').attr('href'))
.fadeIn();
e.preventDefault();
});
var hash = window.location.hash;
var anchor = $('.tabs-nav a[href="' + hash + '"]');
if (anchor.length === 0) {
$('.popup-tabs-nav li:first').addClass('active').show(); //Activate first tab
$('.popup-tab-content:first').show(); //Show first tab content
} else {
anchor.parent('li').click();
}
// Link to Register Tab
$('.register-tab').on('click', function (event) {
event.preventDefault();
$('.popup-tab-content').hide();
$('#register.popup-tab-content').show();
$('body')
.find('.popup-tabs-nav a[href="#register"]')
.parent('li')
.click();
});
// Disable tabs if there's only one tab
$('.popup-tabs-nav').each(function () {
var listCount = $(this).find('li').length;
if (listCount < 2) {
$(this).css({
'pointer-events': 'none',
});
}
});
$('.indicator-bar').each(function () {
var indicatorLenght = $(this).attr('data-indicator-percentage');
$(this)
.find('span')
.css({
width: indicatorLenght + '%',
});
});
var uploadButton = {
$button: $('.uploadButton-input'),
$nameField: $('.uploadButton-file-name'),
};
uploadButton.$button.on('change', function () {
_populateFileField($(this));
});
function _populateFileField($button) {
var selectedFile = [];
for (var i = 0; i < $button.get(0).files.length; ++i) {
selectedFile.push($button.get(0).files[i].name + '<br>');
}
uploadButton.$nameField.html(selectedFile);
}
$('.default-slick-carousel').slick({
infinite: false,
slidesToShow: 3,
slidesToScroll: 1,
dots: false,
arrows: true,
adaptiveHeight: true,
responsive: [
{
breakpoint: 1292,
settings: {
dots: true,
arrows: false,
},
},
{
breakpoint: 993,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
dots: true,
arrows: false,
},
},
{
breakpoint: 769,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
dots: true,
arrows: false,
},
},
],
});
$('.testimonial-carousel').slick({
centerMode: true,
centerPadding: '30%',
slidesToShow: 1,
dots: false,
arrows: true,
adaptiveHeight: true,
responsive: [
{
breakpoint: 1600,
settings: {
centerPadding: '21%',
slidesToShow: 1,
},
},
{
breakpoint: 993,
settings: {
centerPadding: '15%',
slidesToShow: 1,
},
},
{
breakpoint: 769,
settings: {
centerPadding: '5%',
dots: true,
arrows: false,
},
},
],
});
$('.logo-carousel').slick({
infinite: true,
slidesToShow: 5,
slidesToScroll: 1,
dots: false,
arrows: true,
responsive: [
{
breakpoint: 1365,
settings: {
slidesToShow: 5,
dots: true,
arrows: false,
},
},
{
breakpoint: 992,
settings: {
slidesToShow: 3,
dots: true,
arrows: false,
},
},
{
breakpoint: 768,
settings: {
slidesToShow: 1,
dots: true,
arrows: false,
},
},
],
});
$('.mfp-gallery-container').each(function () {
// the containers for all your galleries
$(this).magnificPopup({
type: 'image',
delegate: 'a.mfp-gallery',
fixedContentPos: true,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: false,
preloader: true,
removalDelay: 0,
mainClass: 'mfp-fade',
gallery: { enabled: true, tCounter: '' },
});
});
$('.popup-with-zoom-anim').magnificPopup({
type: 'inline',
fixedContentPos: false,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: true,
preloader: false,
midClick: true,
removalDelay: 300,
mainClass: 'my-mfp-zoom-in',
});
$('.mfp-image').magnificPopup({
type: 'image',
closeOnContentClick: true,
mainClass: 'mfp-fade',
image: {
verticalFit: true,
},
});
$('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: false,
fixedContentPos: false,
});
});
})(this.jQuery);
Thanks for any help.

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>

Collapse Wordpress mobile menu on anchor link click

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

Shortcode dropdown box in Tinymce is not working in WordPress 3.9?

Hi since the new version is about to be released I thought I would download it and see if my theme works still.
Everything works great apart from the dropdown box which is now longer showing.
Here is the codes we used to show it in previous versions.
PHP CODE:
function register_ppp_shortcodes( $buttons ) {
array_unshift( $buttons, "Shortcodes" );
return $buttons;
}
function add_ppp_shortcodes( $plugin_array ) {
$plugin_array['Shortcodes'] = get_template_directory_uri() . '/js/Shortcodes_js.js';
return $plugin_array;
}
function ppp_shortcodes() {
if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') ) {
return;
}
if ( get_user_option('rich_editing') == 'true' ) {
add_filter( 'mce_external_plugins', 'add_ppp_shortcodes' );
add_filter( 'mce_buttons', 'register_ppp_shortcodes' );
}
}
add_action('init', 'ppp_shortcodes');
JS CODE:
/*global tinyMCE, tinymce*/
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, devel:true, maxerr:50 */
(function() {
"use strict";
tinymce.create('tinymce.plugins.Shortcodes', {
init : function(ed, url) {
ed = ed;
url = url;
},
createControl : function(n, cm) {
if(n==='Shortcodes'){
var mtb = cm.createListBox('Shortcodes', {
title : 'Shortcodes',
onselect : function(p) {
var selected = false;
var content = '';
switch (p){
case 'H1 Title':{
var h1titleclass = prompt("Would you like a custom class?", "");
selected = tinyMCE.activeEditor.selection.getContent();
if(h1titleclass != ''){
h1titleclass = 'class= "'+h1titleclass+'"';
}
if (selected) {
content = '[h1'+h1titleclass+']' + selected + '[/h1]';
} else {
content = '[h1'+h1titleclass+'][/h1]';
}
tinymce.execCommand('mceInsertContent', false, content);
} // finished shortcode
break;
case 'H2 Title':{
var h2titleclass = prompt("Would you like a custom class?", "");
selected = tinyMCE.activeEditor.selection.getContent();
if(h2titleclass != ''){
h2titleclass = 'class= "'+h2titleclass+'"';
}
if (selected) {
content = '[h2'+h2titleclass+']' + selected + '[/h2]';
} else {
content = '[h2'+h2titleclass+'][/h2]';
}
tinymce.execCommand('mceInsertContent', false, content);
} // finished shortcode
break;
}
}
});
// Add some menu items
var my_shortcodes = ['H1 Title','H2 Title'];
for(var i in my_shortcodes){
if (true) {mtb.add(my_shortcodes[i],my_shortcodes[i]);}
}
return mtb;
}
return null;
}
});
tinymce.PluginManager.add('Shortcodes', tinymce.plugins.Shortcodes);
})();
Can anyone point me in the right direction on where to start.
I know very little about tinymce as you can tell :(
Thanks
In tinymce4 createControl doen't exist anymore.
You will have to create a button and assign text-value pairs as values to that button.
Use the onSelect function to do stuff when you choose an elemtn from the dropdow list.
Here is a piece of example code:
var my_options = [];
my_options.push({text: "title1", value: "value1"});
my_options.push({text: "title2", value: "value2"});
my_options.push({text: "title3", value: "value3"});
ed.addButton('shortcodes', {
type: 'listbox',
text: 'my_own_decription',
icon: false,
tooltip: 'my_own_decription',
fixedWidth: true,
onselect: function(e)
{
var options = {paragraphs: 1, calldirect: 1};
var text = this.text();
var value = this.value();
console.log("Text choosen:", text);
console.log("Value choosen:", value);
// get selection and range
var selection = ed.selection;
var rng = selection.getRng();
...
ed.focus();
},
values: my_options,
onPostRender: function()
{
ed.my_control = this; // ui control element
}
});
I had the same issue and was searching around the web. The best possible solution I've found was this article.
It worked for me like a charm.
(function() {
"use strict";
tinymce.create('tinymce.plugins.shortcodes', {
init : function(ed, url) {
ed.addButton( 'shortcodes', {
type: 'listbox',
text: 'My Shortcodes',
icon: false,
onselect: function(e) {
},
values: [
{text: 'H1 Title', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[h1][/h1]');
}},
{text: 'H2 Title', onclick : function() {
var selected2 = false;
var content2 = selected2 = tinyMCE.activeEditor.selection.getContent();
var h2titleclass = prompt("Would you like a custom class?", "");
if(h2titleclass != ''){
h2titleclass = ' class= "'+h2titleclass+'"';
}
if (selected2 !== '') {
content2 = '[h2'+h2titleclass+']' + selected2 + '[/h2]';
} else {
content2 = '[h2'+h2titleclass+'][/h2]';
}
tinymce.execCommand('mceInsertContent', false, content2);
}},
]
});
},
});
tinymce.PluginManager.add('shortcodes', tinymce.plugins.shortcodes);
})()

how to set edit form position and size in jqgrid combining with other properties

How to create jqgrid edit form at specified position and size which can changed in runtime?
Edit window postition should combined with other edit parameters in navGrid.
I tried code below but alert box does not appear and edit form is shown in default position.
var oldJqDnRstop,
editWindowParams = {
left: 10,
width: window.innerWidth-18,
top: 5,
height: 100
};
if ($.jqDnR) {
oldJqDnRstop = $.jqDnR.stop; // save original function
$.jqDnR.stop = function (e) {
var $dialog = $(e.target).parent(), dialogId = $dialog.attr("id"), position;
oldJqDnRstop.call(this, e); // call original function
if (typeof dialogId !== "string") {
return;
}
if (dialogId.substr(0, 11) === "editmodgrid") {
editWindowParams.width = $dialog.width();
position = $dialog.position();
editWindowParams.left = position.left;
editWindowParams.top = position.top;
}
};
}
$.extend($.jgrid.edit, {
closeAfterAdd: true,
recreateForm: true,
reloadAfterSubmit: false,
left: 10,
dataheight: '100%',
width: window.innerWidth-18
});
$grid.jqGrid("navGrid", "#grid_toppager", { edit: true },
{
top: function() { alert(editWindowParams.top); return editWindowParams.top; },
left: function() { return editWindowParams.left; },
width: function() { return editWindowParams.width; },
height: function() { return editWindowParams.height; },
afterSubmit: function (response, postdata) {
if (response.responseText.charAt(0) === '{') {
var json = $.parseJSON(response.responseText);
return [true, '', json.Id];
}
alert( decodeErrorMessage(response.responseText, '', ''));
return [false, decodeErrorMessage(response.responseText, '', ''), null];
},
beforeShowForm: function ($form) {
$("#tr_Info>td:eq(1)").attr("colspan", "2");
$("#tr_Info>td:eq(1)>textarea").css("width", "95%");
$("#tr_Info>td:eq(0)").hide();
$("#tr_Markused>td:eq(1)").attr("colspan", "2");
$("#tr_Markused>td:eq(1)>textarea").css("width", "95%");
$("#tr_Markused>td:eq(0)").hide();
beforeShowForm_base($form);
},
url: '/Edit',
closeAfterEdit: true,
onClose: function(){
$( ".ui-autocomplete-input").trigger("blur");
}
} );
The demo demonstrate the fixed code. It's modification of the demo from my previous answer. It uses the following code:
if ($.jqDnR) {
oldJqDnRstop = $.jqDnR.stop; // save original function
$.jqDnR.stop = function (e) {
var $dialog = $(e.target).parent(), dialogId = $dialog.attr("id"),
position, $form;
oldJqDnRstop.call(this, e); // call original function
if (typeof dialogId === "string") {
if (dialogId.substr(0,14) === "searchmodfbox_") {
// save the dialog position here
searchParams.width = $dialog.width();
position = $dialog.position();
searchParams.left = Math.max(0, position.left);
searchParams.top = Math.max(0, position.top);
} else if (dialogId.substr(0,7) === "editmod") {
// Add or Edit form
editParams.width = $dialog.width();
position = $dialog.position();
editParams.left = Math.max(0, position.left);
editParams.top = Math.max(0, position.top);
$form = $dialog.find("form.FormGrid");
if ($form.length > 0) {
editParams.dataheight = $form.height();
}
editParams.height = $dialog.height();
} else if (dialogId.substr(0,6) === "delmod") {
// Delete form
}
}
};
}

Categories

Resources