Solution of my Mozilla browser? - javascript

It works in chrome.But when i use with Mozilla Firefox then it shows this
" A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue.
Script: http://localhost/tsdev_v2/resources/js/libs/jquery-1.8.3.js:6841"
My code is...
<script>
/*$("table").stickyTableHeaders();*/
/* $(function(){
$("table").stickyTableHeaders();
});*/
$(document).ready(function() {
$("table").stickyTableHeaders({fixedOffset:40});
});
</script>
<script>
;(function ($, window, undefined) {
'use strict';
var name = 'stickyTableHeaders',
id = 0,
defaults = {
fixedOffset: 0,
leftOffset: 0,
marginTop: 0,
objDocument: document,
objHead: 'head',
objWindow: window,
scrollableArea: window
};
function Plugin (el, options) {
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
base.id = id++;
// Listen for destroyed, call teardown
base.$el.bind('destroyed',
$.proxy(base.teardown, base));
// Cache DOM refs for performance reasons
base.$clonedHeader = null;
base.$originalHeader = null;
// Keep track of state
base.isSticky = false;
base.hasBeenSticky = false;
base.leftOffset = null;
base.topOffset = null;
base.init = function () {
base.setOptions(options);
base.$el.each(function () {
var $this = $(this);
// remove padding on <table> to fix issue #7
$this.css('padding', 0);
base.$originalHeader = $('thead:first', this);
base.$clonedHeader = base.$originalHeader.clone();
$this.trigger('clonedHeader.' + name, [base.$clonedHeader]);
base.$clonedHeader.addClass('tableFloatingHeader');
base.$clonedHeader.css('display', 'none');
base.$originalHeader.addClass('tableFloatingHeaderOriginal');
base.$originalHeader.after(base.$clonedHeader);
base.$printStyle = $('<style type="text/css" media="print">' +
'.tableFloatingHeader{display:none !important;}' +
'.tableFloatingHeaderOriginal{position:static !important;}' +
'</style>');
base.$head.append(base.$printStyle);
});
base.updateWidth();
base.toggleHeaders();
base.bind();
};
base.destroy = function (){
base.$el.unbind('destroyed', base.teardown);
base.teardown();
};
base.teardown = function(){
if (base.isSticky) {
base.$originalHeader.css('position', 'static');
}
$.removeData(base.el, 'plugin_' + name);
base.unbind();
base.$clonedHeader.remove();
base.$originalHeader.removeClass('tableFloatingHeaderOriginal');
base.$originalHeader.css('visibility', 'visible');
base.$printStyle.remove();
base.el = null;
base.$el = null;
};
base.bind = function(){
base.$scrollableArea.on('scroll.' + name, base.toggleHeaders);
if (!base.isWindowScrolling) {
base.$window.on('scroll.' + name + base.id, base.setPositionValues);
base.$window.on('resize.' + name + base.id, base.toggleHeaders);
}
base.$scrollableArea.on('resize.' + name, base.toggleHeaders);
base.$scrollableArea.on('resize.' + name, base.updateWidth);
};
base.unbind = function(){
// unbind window events by specifying handle so we don't remove too much
base.$scrollableArea.off('.' + name, base.toggleHeaders);
if (!base.isWindowScrolling) {
base.$window.off('.' + name + base.id, base.setPositionValues);
base.$window.off('.' + name + base.id, base.toggleHeaders);
}
base.$scrollableArea.off('.' + name, base.updateWidth);
};
base.toggleHeaders = function () {
if (base.$el) {
base.$el.each(function () {
var $this = $(this),
newLeft,
newTopOffset = base.isWindowScrolling ? (
isNaN(base.options.fixedOffset) ?
base.options.fixedOffset.outerHeight() :
base.options.fixedOffset
) :
base.$scrollableArea.offset().top + (!isNaN(base.options.fixedOffset) ? base.options.fixedOffset : 0),
offset = $this.offset(),
scrollTop = base.$scrollableArea.scrollTop() + newTopOffset,
scrollLeft = base.$scrollableArea.scrollLeft(),
scrolledPastTop = base.isWindowScrolling ?
scrollTop > offset.top :
newTopOffset > offset.top,
notScrolledPastBottom = (base.isWindowScrolling ? scrollTop : 0) <
(offset.top + $this.height() - base.$clonedHeader.height() - (base.isWindowScrolling ? 0 : newTopOffset));
if (scrolledPastTop && notScrolledPastBottom) {
newLeft = offset.left - scrollLeft + base.options.leftOffset;
base.$originalHeader.css({
'position': 'fixed',
'margin-top': base.options.marginTop,
'left': newLeft,
'z-index': 3 // #18: opacity bug
});
base.leftOffset = newLeft;
base.topOffset = newTopOffset;
base.$clonedHeader.css('display', '');
if (!base.isSticky) {
base.isSticky = true;
// make sure the width is correct: the user might have resized the browser while in static mode
base.updateWidth();
$this.trigger('enabledStickiness.' + name);
}
base.setPositionValues();
} else if (base.isSticky) {
base.$originalHeader.css('position', 'static');
base.$clonedHeader.css('display', 'none');
base.isSticky = false;
base.resetWidth($('td,th', base.$clonedHeader), $('td,th', base.$originalHeader));
$this.trigger('disabledStickiness.' + name);
}
});
}
};
base.setPositionValues = function () {
var winScrollTop = base.$window.scrollTop(),
winScrollLeft = base.$window.scrollLeft();
if (!base.isSticky ||
winScrollTop < 0 || winScrollTop + base.$window.height() > base.$document.height() ||
winScrollLeft < 0 || winScrollLeft + base.$window.width() > base.$document.width()) {
return;
}
base.$originalHeader.css({
'top': base.topOffset - (base.isWindowScrolling ? 0 : winScrollTop),
'left': base.leftOffset - (base.isWindowScrolling ? 0 : winScrollLeft)
});
};
base.updateWidth = function () {
if (!base.isSticky) {
return;
}
// Copy cell widths from clone
if (!base.$originalHeaderCells) {
base.$originalHeaderCells = $('th,td', base.$originalHeader);
}
if (!base.$clonedHeaderCells) {
base.$clonedHeaderCells = $('th,td', base.$clonedHeader);
}
var cellWidths = base.getWidth(base.$clonedHeaderCells);
base.setWidth(cellWidths, base.$clonedHeaderCells, base.$originalHeaderCells);
// Copy row width from whole table
base.$originalHeader.css('width', base.$clonedHeader.width());
};
base.getWidth = function ($clonedHeaders) {
var widths = [];
$clonedHeaders.each(function (index) {
var width, $this = $(this);
if ($this.css('box-sizing') === 'border-box') {
var boundingClientRect = $this[0].getBoundingClientRect();
if(boundingClientRect.width) {
width = boundingClientRect.width; // #39: border-box bug
} else {
width = boundingClientRect.right - boundingClientRect.left; // ie8 bug: getBoundingClientRect() does not have a width property
}
} else {
var $origTh = $('th', base.$originalHeader);
if ($origTh.css('border-collapse') === 'collapse') {
if (window.getComputedStyle) {
width = parseFloat(window.getComputedStyle(this, null).width);
} else {
// ie8 only
var leftPadding = parseFloat($this.css('padding-left'));
var rightPadding = parseFloat($this.css('padding-right'));
// Needs more investigation - this is assuming constant border around this cell and it's neighbours.
var border = parseFloat($this.css('border-width'));
width = $this.outerWidth() - leftPadding - rightPadding - border;
}
} else {
width = $this.width();
}
}
widths[index] = width;
});
return widths;
};
base.setWidth = function (widths, $clonedHeaders, $origHeaders) {
$clonedHeaders.each(function (index) {
var width = widths[index];
$origHeaders.eq(index).css({
'min-width': width,
'max-width': width
});
});
};
base.resetWidth = function ($clonedHeaders, $origHeaders) {
$clonedHeaders.each(function (index) {
var $this = $(this);
$origHeaders.eq(index).css({
'min-width': $this.css('min-width'),
'max-width': $this.css('max-width')
});
});
};
base.setOptions = function (options) {
base.options = $.extend({}, defaults, options);
base.$window = $(base.options.objWindow);
base.$head = $(base.options.objHead);
base.$document = $(base.options.objDocument);
base.$scrollableArea = $(base.options.scrollableArea);
base.isWindowScrolling = base.$scrollableArea[0] === base.$window[0];
};
base.updateOptions = function (options) {
base.setOptions(options);
// scrollableArea might have changed
base.unbind();
base.bind();
base.updateWidth();
base.toggleHeaders();
};
// Run initializer
base.init();
}
// A plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[name] = function ( options ) {
return this.each(function () {
var instance = $.data(this, 'plugin_' + name);
if (instance) {
if (typeof options === 'string') {
instance[options].apply(instance);
} else {
instance.updateOptions(options);
}
} else if(options !== 'destroy') {
$.data(this, 'plugin_' + name, new Plugin( this, options ));
}
});
};
})(jQuery, window);
</script>
In my jquery-1.8.3.js:6841
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
How to recover this ? Please help.

Related

Uncaught TypeError: window.getWidth is not a function . what is this error? how to fix? [duplicate]

This question already has answers here:
Get the size of the screen, current web page and browser window
(20 answers)
Closed 6 days ago.
I see following error for my website (via google Inspect). I need your help to understand the problem and how to fix it?
script.js:137 Uncaught TypeError: window.getWidth is not a function
at Object.check (script.js:137:23)
at Object.initialize (script.js:58:14)
at HTMLDocument.<anonymous> (script.js:442:14)
at n (jquery-1.7.1.min.js:2:14784)
at Object.fireWith (jquery-1.7.1.min.js:2:15553)
at Function.ready (jquery-1.7.1.min.js:2:9773)
at HTMLDocument.B (jquery-1.7.1.min.js:2:14348)
and following is script.js file content:
var TouchMask = {
handlers: [],
isbind: 0,
ontouch: function(){
var result = 1;
TouchMask.handlers.each(function(fn){
result = fn() && result;
});
if(result){
document.removeEvent('touchstart', TouchMask.ontouch);
TouchMask.isbind = 0;
}
},
show: function(){
if(this.isbind){
return false;
}
document.addEvent('touchstart', TouchMask.ontouch);
this.isbind = 1;
},
register: function(handler){
if(typeOf (handler) == 'function' && this.handlers.indexOf(handler) == -1){
this.handlers.push(handler);
}
},
unregister: function(handler){
this.handlers.erase(handler);
}
};
var JawallMenu = {
initialize: function(){
JawallMenu.isAndroidTable = navigator.userAgent.toLowerCase().indexOf('android') > -1 && navigator.userAgent.toLowerCase().indexOf('mobile') == -1;
JawallMenu.isTouch = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion);
JawallMenu.isTablet = JawallMenu.isTouch && (window.innerWidth >= 720);
JawallMenu.enableTouch();
JawallMenu.check();
window.addEvent('resize', JawallMenu.check);
},
enableTouch: function(){
if (JawallMenu.isTouch){
var jmainnav = $('mainnav');
if(!jmainnav){
return false;
}
var jmenu = jmainnav.getElement('.menu');
if(!jmenu){
return false;
}
var jitems = jmenu.getElements('li.deeper'),
onTouch = function(e){
var i, len, noclick = !this.retrieve('noclick');
e.stopPropagation();
// reset all
for (i = 0, len = jitems.length; i < len; ++i) {
jitems[i].store('noclick', 0);
}
if(noclick){
var jshow = this.addClass('hover').getParents('li.parent').addClass('hover');
jshow = jshow.append([this]);
jitems.each(function (jitem) {
if(!jshow.contains(jitem)){
jitem.removeClass('hover');
}
});
}
this.store('noclick', noclick);
this.focus();
},
onClick = function(e){
e.stopPropagation();
if(this.retrieve('noclick')){
e.preventDefault();
jitems.removeClass('hover');
this.addClass('hover').getParents('li.parent').addClass('hover');
TouchMask.hidetoggle();
TouchMask.show();
} else {
var href = this.getElement('a').get('href');
if(href){
window.location.href = href;
}
}
};
jitems.each(function(jitem){
jitem.addEvent('touchstart', onTouch)
.addEvent('click', onClick)
.store('noclick', 0);
});
JawallMenu.resetmenu = function(){
jitems.store('noclick', 0).removeClass('hover');
return true;
};
TouchMask.register(JawallMenu.resetmenu);
}
},
oldWidth: 0,
check: function(){
var wwidth = window.getWidth();
if(wwidth == JawallMenu.oldWidth){
return;
}
JawallMenu.oldWidth = wwidth;
var jmainnav = $('mainnav');
if(!jmainnav){
return;
}
var jmenuinner = jmainnav.getElement('.menu-inner'),
jmenu = jmainnav.getElement('.menu');
if(!jmenuinner || !jmenu){
return;
}
//check if we have to implement scroll
if (jmenu.offsetWidth > jmenuinner.offsetWidth) {
jmenu.setStyle('float', 'left');
if(!window.menuIScroll){
var jprev = jmainnav.getChildren('.navprev')[0] || new Element('a', {
'href': 'javascript:;',
'class': 'navprev'
}).inject(jmainnav).addEvent('click', function(){
if(window.menuIScroll){
window.menuIScroll.scrollToPage('prev');
}
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
}),
jnext = jmainnav.getChildren('.navnext')[0] || new Element('a', {
'href': 'javascript:;',
'class': 'navnext'
}).inject(jmainnav).addEvent('click', function(){
if(window.menuIScroll){
window.menuIScroll.scrollToPage('next');
}
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
}),
checkNav = function (){
if(window.menuIScroll){
jprev.setStyle('display', window.menuIScroll.x >= 0 ? 'none' : 'block');
jnext.setStyle('display', (window.menuIScroll.x <= window.menuIScroll.maxScrollX) ? 'none' : 'block');
}
};
window.menuIScroll = new iScroll(jmenuinner, {
snap: '.menu > li',
hScrollbar: false,
vScrollbar: false,
onRefresh: checkNav,
onScrollEnd: checkNav,
useTransform: false,
onScrollStart: function(){
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
},
overflow: ''
});
checkNav();
var jactive = jmenu.getChildren('.active')[0];
if(jactive){
window.menuIScroll.scrollToElement(jactive);
}
}
if (window.menuIScroll) {
window.menuIScroll.refresh();
}
} else {
if (window.menuIScroll) {
window.menuIScroll.scrollTo(0, 0, 0);
}
jmenu.setStyle('float', '');
}
//check if the mobile layout, we change html structure
if(wwidth < 720){
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
jmenuinner.setStyle('overflow', 'hidden');
jmenu.getChildren('.deeper > ul').each(function(jsub){
var jitem = jsub.getParent(),
sid = null;
jsub.store('parent', jitem).addClass('jsub').inject(jmainnav).setStyle('position', 'absolute');
if(!JawallMenu.isTouch){
//add mouse event to show/hide sub on desktop
jitem.addEvent('mouseenter', function(e){
clearTimeout(sid);
if(jsub.getStyle('display') != 'none'){
return false;
} else {
if(JawallMenu.jcitem && JawallMenu.jcitem != jitem){
JawallMenu.jcitem.fireEvent('shide');
}
jsub.setStyles({
display: 'block',
top: jmenuinner.getHeight()
});
jitem.addClass('over');
JawallMenu.jcitem = jitem;
}
}).addEvent('mouseleave', function(){
clearTimeout(sid);
sid = setTimeout(function(){
jitem.fireEvent('shide');
}, 100);
});
jsub.addEvent('mouseenter', function(){
clearTimeout(sid);
}).addEvent('mouseleave', function(){
clearTimeout(sid);
sid = setTimeout(function(){
jitem.fireEvent('shide');
}, 100);
});
} else {
//add touch event for touch device
jitem.addEvent('touchstart', function(e){
if(jsub.getStyle('display') == 'none'){
e.stop();
if(JawallMenu.jcitem && JawallMenu.jcitem != jitem){
JawallMenu.jcitem.fireEvent('shide');
}
jsub.setStyles({
display: 'block',
top: jmenuinner.getHeight()
});
jitem.addClass('over');
JawallMenu.jcitem = jitem;
TouchMask.hidetoggle();
TouchMask.show();
}
});
}
jitem.addEvent('shide', function(){
clearTimeout(sid);
jsub.setStyle('display', 'none');
jitem.removeClass('over');
JawallMenu.jcitem = null;
}).fireEvent('shide');
});
//only init once
if(!JawallMenu.initTouch && JawallMenu.isTouch){
jmainnav.addEvent('touchstart', function(){
if(JawallMenu.jcitem){
this.store('touchInside', 1);
}
});
TouchMask.hidesub = function(){
if(jmainnav.retrieve('touchInside')){
jmainnav.store('touchInside', 0);
return false;
} else {
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
return false;
}
}
return true;
};
TouchMask.register(TouchMask.hidesub);
TouchMask.hidesub();
JawallMenu.initTouch = 1;
}
} else {
JawallMenu.jcitem = null;
jmainnav.getChildren('.jsub').each(function(jsub){
var jitem = jsub.retrieve('parent');
jitem.removeEvents('mouseenter').removeEvents('mouseleave').removeEvents('touchstart').removeEvents('shide');
jsub.removeProperty('style').removeEvents('mouseenter').removeEvents('mouseleave').removeClass('jsub').inject(jitem);
});
jmenuinner.setStyle('overflow', '');
}
}
};
window.addEventListener('load', function(event) {
if(window.menuIScroll){
window.menuIScroll.refresh();
}
if(window.sidebarIScroll){
window.sidebarIScroll.refresh();
}
});
(function($){
var groups = {
},
handler = function (group, value) {
// ignore user setting for page with fixed option
if ($(document.body).hasClass ('fixed-' + group)){
return;
}
if (value) {
if (groups[group]['type'] == 'toggle') {
var cvalue = $.cookie ('ja-'+group);
if (new RegExp ('(^|\\s)' + value+'(?:\\s|$)').test(cvalue)) {
$(document.body).removeClass (group + '-' + value);
cvalue = cvalue.replace (new RegExp ('(^|\\s)' + value+'(?:\\s|$)', 'g'), '$1');
} else {
$(document.body).addClass (group + '-' + value);
cvalue += ' ' + value;
}
groups[group]['val'] = cvalue;
// update cookie
$.cookie ('ja-'+group, cvalue, {duration: 365, path: '/'});
} else {
// update value & cookie
groups[group]['val'] = value;
$.cookie ('ja-'+group, value, {duration: 365, path: '/'});
// remove current
document.body.className = document.body.className.replace (new RegExp ('(^|\\s)' + group+'-[^\\s]*', 'g'), '$1');
$(document.body).addClass (group + '-' + value);
}
}
// Make the UI reload by trigger resize event for window
$(window).trigger('resize');
};
$.fn.toolbar = function(options){
var defaults = {
group: 'basegrid',
type: 'single',
val: 'm'
},
opt = $.extend(defaults, options);
groups[opt.group] = groups[opt.group] || {};
$.extend(groups[opt.group], {type: opt.type, val: opt.val});
if (!$(document.body).hasClass ('fixed-' + opt.group)){
var value = $.cookie('ja-'+opt.group);
if (value) {
groups[opt.group]['val'] = value; // setting exists, replace the default
// add active class
$(document.body).addClass (groups[opt.group]['val'].replace (/(^|\s)([^\s]+)/g, '$1' + opt.group + '-$2'));
} else if(opt.val) {
handler (opt.group, opt.val);
}
}
// bind event for toolbar
return this.bind('click', function () { handler (opt.group, this.id.replace ('toolbar-' + opt.group + '-', '')); return false; });
};
})(window.$wall || window.jQuery);
(window.$wall || window.jQuery)(document).ready(function ($) {
// enable menu responsive check
if(!($.browser.msie && parseFloat($.browser.version) < 9)){
JawallMenu.initialize();
}
var bindevent = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion) ? 'touchstart' : 'click',
jtoggles = $('.btn-toggle'),
jsidebar = $('#sidebar'),
jtoggleactive = null;
// toggle handle
jtoggles.bind(bindevent, function (event) {
var jactive = $(this),
jparent = jactive.parent();
if (jparent.hasClass('active')) {
jparent.removeClass ('active');
// remove btn-toggle-active
jtoggleactive = null
} else {
// remove other active
jtoggles.parent().removeClass ('active');
// add active for this toggle
jparent.addClass ('active');
// store
jtoggleactive = jactive;
}
if(typeOf (TouchMask.hidesub) == 'function'){
TouchMask.hidesub();
}
TouchMask.show();
return false;
});
jtoggles.parent().bind(bindevent, function(){
if(jtoggleactive){
$('body').data('touchInside', 1);
}
});
TouchMask.hidetoggle = function(){
if (jtoggleactive) {
if($('body').data('touchInside')){
$('body').data('touchInside', 0);
return false;
} else {
// remove active
jtoggleactive.parent().removeClass ('active');
jtoggleactive = null;
return false;
}
}
return true;
};
TouchMask.register(TouchMask.hidetoggle);
var rfpage = $('#josForm').hasClass('wform') && $('#k2Container').hasClass('k2AccountPage'),
wmobile = false, //normal by default
wmeditor = function(){
if(!wmobile){
var jmce = $('.mceLayout:first');
if(jmce.width() > jmce.closest('.wcontrols').width()){
wmobile = true;
$('table.mceToolbar').each(function(){
$(this).find('> tbody > tr').css('white-space', 'normal').find('td').css({
position: '',
float: 'left',
display: 'inline-block'
});
});
$('.toggle-editor a').trigger('click').delay(300).trigger('click');
}
}
},
sidrfp = setTimeout(wmeditor, 350);
// tracking status of btn-toggle
$(window).resize (function() {
JawallMenu.isTablet = JawallMenu.isTouch && (window.innerWidth >= 720);
if (jtoggleactive) {
if (jtoggleactive.css('display') == 'none') {
// remove active
jtoggleactive.parent().removeClass ('active');
jtoggleactive = null;
}
}
if (jsidebar.length) {
if(JawallMenu.isTablet){
jsidebar.css({
position: 'fixed',
top: ''
});
}
jsidebar
.add(jsidebar.find('.sidebar-inner'))
.css('height', Math.max(80,
(window.innerHeight || $(window).height())
- parseInt(jsidebar.css('top'))
- parseInt(jsidebar.css('margin-bottom'))
- parseInt(jsidebar.css('padding-bottom'))));
if(window.sidebarIScroll){
window.sidebarIScroll.refresh();
}
}
if(rfpage){
clearTimeout(sidrfp);
sidrfp = setTimeout(wmeditor, 350);
}
});
// scrollbar for sidebar if exist
if (jsidebar.length) {
jsidebar
.add(jsidebar.find('.sidebar-inner'))
.css('height', Math.max(80,
(window.innerHeight || $(window).height())
- parseInt(jsidebar.css('top'))
- parseInt(jsidebar.css('margin-bottom'))
- parseInt(jsidebar.css('padding-bottom'))));
window.sidebarIScroll = new iScroll(jsidebar.find('.sidebar-inner')[0], {vScrollbar: true, scrollbarClass: 'sidebarTracker', useTransform: false});
if(JawallMenu.isTouch){
var jsbtoggle = jsidebar.find('.btn-toggle:first');
$('<div id="dummy-toggle"></div>').css({
position: 'absolute',
top: 0,
left: 0,
width: jsbtoggle.width(),
height: jsbtoggle.height(),
}).appendTo(document.body).bind(bindevent, function(e){
e.preventDefault();
e.stopPropagation();
jsbtoggle.trigger(bindevent);
});
var lastScroll = 0,
scrollid = null;
$(window).scroll(function(){
lastScroll = $(window).scrollTop();
$('#dummy-toggle').css('top', lastScroll);
if(JawallMenu.isTablet){
clearTimeout(scrollid);
scrollid = setTimeout(function(){
lastScroll = $(window).scrollTop();
scrollid = setTimeout(function(){
if(lastScroll == $(window).scrollTop()){
jsidebar
.css('top', lastScroll + parseFloat(jsidebar.css('top', '').css('top')))
.css('position', 'absolute');
$(document).one('touchmove', function(){
jsidebar.css({position: 'fixed', top: ''});
});
}
}, 100);
}, 100);
}
});
}
if(JawallMenu.isTablet && !JawallMenu.isBindTablet){
$(document).on('touchmove', function(){
jsidebar.css({position: 'fixed', top: ''});
});
JawallMenu.isBindTablet = 1;
}
}
// check and load typography assert files if nessesary
window.jtypo = jQuery('.item-pagetypography .item-content');
if(!window.jtypo.length){
window.jtypo = jQuery('.typography .itemBody');
}
if(window.jtypo.length){
var css = document.createElement('link');
css.type = 'text/css';
css.rel= 'stylesheet';
css.href= JADef.tplurl + 'css/jtypo.css';
document.getElementsByTagName('head')[0].appendChild(css);
$.getScript(JADef.tplurl + 'js/jtypo.js');
}
});
to understand it better please see the error directly via google inspect at following page:
http://test6.harfrooz.com/117-more/18376-top-20-ufo-sightings
This error made my menus disabled and more issues. I would appreciate for any help to solve this error.
I am fairly certain this has been answered before here.
For normal javascript you can use:
window.innerHeight - the inner height of the browser window (in
pixels)
window.innerWidth - the inner width of the browser window (in
pixels)

Multi-level Accordion Menu: Its possible to open each level with an anchor?

I have a Multi-Level Accordion Menu - from a FAQ - with 2 levels.
Each level have a 13 Questions / Answers.
My problem:
One of the Questions/Answers have a lot of information. (almost 10 pages).
The other Questions/Answers have 3, 4 lines of information each.
The Question with many information is number 7.
Then When I click on question 7 - the answer 7 is open. with many information, and the user must scroll down the page to read all.
Until here, OK. no problem.
but at end - If I click on Question 8 - to read the answer, the menu closes question 7 (ok) - open question 8 (ok) - but the page still in the footer - the page dont scrolls up with the faq..
With all other questions - because they are small - I can see in same screen almost all 13 questions + the answer opened.
With question 7 - no. the page scrolls down and don't scrolls up - when we close the question 7.
There is a way to solve this? I think I need to create an anchor for each question..
Tks a lot!
https://jsfiddle.net/27sdLvmh/
Please, click on Question 7, scrool down to read the answer and then click on question 8. the menu scrolls up - but the screen no.. and the user was lost in the footer of the page.. :D
JS:
;(function ( $, window, document, undefined ) {
var pluginName = 'accordion',
defaults = {
transitionSpeed: 300,
transitionEasing: 'ease',
controlElement: '[data-control]',
contentElement: '[data-content]',
groupElement: '[data-accordion-group]',
singleOpen: true
};
function Accordion(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Accordion.prototype.init = function () {
var self = this,
opts = self.options;
var $accordion = $(self.element),
$controls = $accordion.find('> ' + opts.controlElement),
$content = $accordion.find('> ' + opts.contentElement);
var accordionParentsQty = $accordion.parents('[data-accordion]').length,
accordionHasParent = accordionParentsQty > 0;
var closedCSS = { 'max-height': 0, 'overflow': 'hidden' };
var CSStransitions = supportsTransitions();
function debounce(func, threshold, execAsap) {
var timeout;
return function debounced() {
var obj = this,
args = arguments;
function delayed() {
if (!execAsap) func.apply(obj, args);
timeout = null;
};
if (timeout) clearTimeout(timeout);
else if (execAsap) func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
function supportsTransitions() {
var b = document.body || document.documentElement,
s = b.style,
p = 'transition';
if (typeof s[p] == 'string') {
return true;
}
var v = ['Moz', 'webkit', 'Webkit', 'Khtml', 'O', 'ms'];
p = 'Transition';
for (var i=0; i<v.length; i++) {
if (typeof s[v[i] + p] == 'string') {
return true;
}
}
return false;
}
function requestAnimFrame(cb) {
if(window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame) {
return requestAnimationFrame(cb) ||
webkitRequestAnimationFrame(cb) ||
mozRequestAnimationFrame(cb);
} else {
return setTimeout(cb, 1000 / 60);
}
}
function toggleTransition($el, remove) {
if(!remove) {
$content.css({
'-webkit-transition': 'max-height ' + opts.transitionSpeed + 'ms ' + opts.transitionEasing,
'transition': 'max-height ' + opts.transitionSpeed + 'ms ' + opts.transitionEasing
});
} else {
$content.css({
'-webkit-transition': '',
'transition': ''
});
}
}
function calculateHeight($el) {
var height = 0;
$el.children().each(function() {
height = height + $(this).outerHeight(true);
});
$el.data('oHeight', height);
}
function updateParentHeight($parentAccordion, $currentAccordion, qty, operation) {
var $content = $parentAccordion.filter('.open').find('> [data-content]'),
$childs = $content.find('[data-accordion].open > [data-content]'),
$matched;
if(!opts.singleOpen) {
$childs = $childs.not($currentAccordion.siblings('[data-accordion].open').find('> [data-content]'));
}
$matched = $content.add($childs);
if($parentAccordion.hasClass('open')) {
$matched.each(function() {
var currentHeight = $(this).data('oHeight');
switch (operation) {
case '+':
$(this).data('oHeight', currentHeight + qty);
break;
case '-':
$(this).data('oHeight', currentHeight - qty);
break;
default:
throw 'updateParentHeight method needs an operation';
}
$(this).css('max-height', $(this).data('oHeight'));
});
}
}
function refreshHeight($accordion) {
if($accordion.hasClass('open')) {
var $content = $accordion.find('> [data-content]'),
$childs = $content.find('[data-accordion].open > [data-content]'),
$matched = $content.add($childs);
calculateHeight($matched);
$matched.css('max-height', $matched.data('oHeight'));
}
}
function closeAccordion($accordion, $content) {
$accordion.trigger('accordion.close');
if(CSStransitions) {
if(accordionHasParent) {
var $parentAccordions = $accordion.parents('[data-accordion]');
updateParentHeight($parentAccordions, $accordion, $content.data('oHeight'), '-');
}
$content.css(closedCSS);
$accordion.removeClass('open');
} else {
$content.css('max-height', $content.data('oHeight'));
$content.animate(closedCSS, opts.transitionSpeed);
$accordion.removeClass('open');
}
}
function openAccordion($accordion, $content) {
$accordion.trigger('accordion.open');
if(CSStransitions) {
toggleTransition($content);
if(accordionHasParent) {
var $parentAccordions = $accordion.parents('[data-accordion]');
updateParentHeight($parentAccordions, $accordion, $content.data('oHeight'), '+');
}
requestAnimFrame(function() {
$content.css('max-height', $content.data('oHeight'));
});
$accordion.addClass('open');
} else {
$content.animate({
'max-height': $content.data('oHeight')
}, opts.transitionSpeed, function() {
$content.css({'max-height': 'none'});
});
$accordion.addClass('open');
}
}
function closeSiblingAccordions($accordion) {
var $accordionGroup = $accordion.closest(opts.groupElement);
var $siblings = $accordion.siblings('[data-accordion]').filter('.open'),
$siblingsChildren = $siblings.find('[data-accordion]').filter('.open');
var $otherAccordions = $siblings.add($siblingsChildren);
$otherAccordions.each(function() {
var $accordion = $(this),
$content = $accordion.find(opts.contentElement);
closeAccordion($accordion, $content);
});
$otherAccordions.removeClass('open');
}
function toggleAccordion() {
var isAccordionGroup = (opts.singleOpen) ? $accordion.parents(opts.groupElement).length > 0 : false;
calculateHeight($content);
if(isAccordionGroup) {
closeSiblingAccordions($accordion);
}
if($accordion.hasClass('open')) {
closeAccordion($accordion, $content);
} else {
openAccordion($accordion, $content);
}
}
function addEventListeners() {
$controls.on('click', toggleAccordion);
$controls.on('accordion.toggle', function() {
if(opts.singleOpen && $controls.length > 1) {
return false;
}
toggleAccordion();
});
$(window).on('resize', debounce(function() {
refreshHeight($accordion);
}));
}
function setup() {
$content.each(function() {
var $curr = $(this);
if($curr.css('max-height') != 0) {
if(!$curr.closest('[data-accordion]').hasClass('open')) {
$curr.css({ 'max-height': 0, 'overflow': 'hidden' });
} else {
toggleTransition($curr);
calculateHeight($curr);
$curr.css('max-height', $curr.data('oHeight'));
}
}
});
if(!$accordion.attr('data-accordion')) {
$accordion.attr('data-accordion', '');
$accordion.find(opts.controlElement).attr('data-control', '');
$accordion.find(opts.contentElement).attr('data-content', '');
}
}
setup();
addEventListeners();
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Accordion( this, options ));
}
});
}
})( jQuery, window, document );
Hey check this demo
changes line 191 -> 194
setTimeout(function()
{
$('html, body').animate({ scrollTop: $content.prev().offset().top }, "fast");
},(1000/60)+200);

$.fn.<new_function> 'is not a function' jQuery

EDIT: code link with better formatting:
EDIT: code updated with improvements from JSHint
http://pastebin.com/hkDQfZy1
I am trying to use $.fn to create a new function on jQuery objects by using it like:
$.fn.animateAuto = function(x,y) { }
And calling it by:
var card = $(id);
.....
var expanderButton = card.find(".dock-bottom");
.....
expanderButton.animateAuto('height', 500);
and I get:
Uncaught TypeError: expanderButton.animateAuto is not a function
What am I doing incorrectly? The $.cssHooks extension works just fine along with $.fx.
Here is the code:
var CSS_VIS = 'visibility'
var CSS_VIS_VIS = 'visible';
var CSS_VIS_HID = 'hidden';
var CSS_TEXTBOX_CONTAINER = ".text-box-container";
$.cssHooks['rotate'] = {
get: function (elem, computed, extra) {
var property = getTransformProperty(elem);
if (property) {
return elem.style[property].replace(/.*rotate\((.*)deg\).*/, '$1');
} else {
return '';
}
},
set: function (elem, value) {
var property = getTransformProperty(elem);
if (property) {
value = parseInt(value);
$(elem).data('rotatation', value);
if (value == 0) {
elem.style[property] = '';
} else {
elem.style[property] = 'rotate(' + value % 360 + 'deg)';
}
} else {
return '';
}
}
};
$.fn.animateAuto = function (prop, speed) {
return this.each(function (i, el) {
el = jQuery(el);
var element = el.clone().css({ 'height': 'auto' }).appendTo("body");
var height = element.css("height");
var width = element.css("width");
element.remove();
if (prop === "height") {
el.animate({ 'height': height }, speed);
} else if (prop = "width") {
el.animate({ 'width': width }, speed);
} else if (prop = "both") {
el.animate({ 'height': height, 'width:': width }, speed);
}
});
}
$.fx.step['rotate'] = function (fx) {
$.cssHooks['rotate'].set(fx.elem, fx.now);
};
function getTransformProperty(element) {
var properties = [
'transform',
'WebkitTransform',
'MozTransform',
'msTransform',
'OTransform'];
var p;
while (p = properties.shift()) {
if (element.style[p] !== undefined) {
return p;
}
}
return false;
}
function isExpanded(card) {
return card.find(CSS_TEXTBOX_CONTAINER).css(CSS_VIS) == CSS_VIS_VIS;
}
function expandCard(id) {
var card = $(id);
var isCardExpanded = isExpanded(card);
var expanderButton = card.find(".dock-bottom");
card.animate({
height: isCardExpanded ? '80px' : '270px'
}, 500);
var startValue = isCardExpanded ? 1 : 0;
var endValue = isCardExpanded ? 0 : 1;
var visibilityValue = isCardExpanded ? CSS_VIS_HID : CSS_VIS_VIS;
var textBoxes = card.find(CSS_TEXTBOX_CONTAINER);
textBoxes.fadeTo(0, startValue);
textBoxes.css(CSS_VIS, visibilityValue).fadeTo(500, endValue);
var topValue = isCardExpanded ? 'auto' : '200px';
if (isCardExpanded) {
expanderButton.animateAuto('height', 500);
} else {
expanderButton.animate({
top: '200px'
}, 500);
}
expanderButton.find("span").text(isCardExpanded ? "More Info" : "Less Info");
var buttonthing = expanderButton.find("button");
expanderButton.find("button").animate({ rotate: isCardExpanded ? 0 : -180 });
};
The issue is that jQuery was loaded multiple times. I am using ASP.NET MVC5 and was loading jQuery in the PartialView (re-usable UI control) and the main page which was causing my extension to be overriden.
I would post code but it would be too verbose and has nothing to do with jQuery or JavaScript. To solve though, all I did was remove the jQuery script import from the PartialView since jQuery is imported on every page by the master page.
Thanks everyone for helping out though, you all proved to me that this was not a simple problem that I was overthinking and that more research was necessary.

JavaScript double function call overrides first function call

Before I get into details, please take a look at the live example where this problem occurs - http://jsfiddle.net/66HFU/ (Script code at the bottom of this post)
Now if you would click on any image at last row, it would display these. However if you would click on upper row images, below row images are shown.
Further investigation shows that for somewhat reason the letter called function selector elements only get binded with event listener while the firstly called functions selector elements do not.
So, I would like to know is there are any ways to make the function call independent so the latter function call does not override first one (if that would fix the problem, of-course)?
The place where the event function gets bind on the element can be found in function f_AddEvents first lines.
And the the main function calls that are used to initialize Light Box is at the bottom of the code like this:
LightBox.init({
selector: "[data-simplbox='demo1']",
boxId: "simplbox"
});
LightBox.init({
selector: "[data-simplbox='demo2']",
boxId: "simplbox",
imageLoadStart: activityIndicatorOn,
imageLoadEnd: activityIndicatorOff
});
All code:
;(function (window, document, undefined) {
var docElem = document.documentElement;
var DomM = (function() {
var f_ToDOMStyle = function (p_Style) {
return p_Style.replace(/\-[a-z]/g, function (p_Style) {
return p_Style.charAt(1).toUpperCase();
});
};
return {
event: {
set: function (p_Element, p_Events, p_Function) {
var i = 0,
j = 0;
p_Events = p_Events.split(" ");
if (!p_Element.length) {
for (i = 0; i < p_Events.length; i++) {
p_Element.addEventListener(p_Events[i], p_Function, false);
}
} else {
for (i = 0; i < p_Element.length; i++) {
for (j = 0; j < p_Events.length; j++) {
p_Element[i].addEventListener(p_Events[j], p_Function, false);
}
}
}
}
},
css: {
set: function (p_Element, p_Style) {
var j;
if (!p_Element.length) {
for (j in p_Style) {
if (p_Style.hasOwnProperty(j)) {
j = f_ToDOMStyle(j);
p_Element.style[j] = p_Style[j];
}
}
} else {
for (var i = 0; i < p_Element.length; i++) {
for (j in p_Style) {
if (p_Style.hasOwnProperty(j)) {
j = f_ToDOMStyle(j);
p_Element[i].style[j] = p_Style[j];
}
}
}
}
}
}
};
}());
var _LightBox = {
f_MergeObjects: function (p_Original, p_Updates) {
for (var i in p_Updates) {
if (p_Updates.hasOwnProperty(i)) {
p_Original[i] = p_Updates[i];
}
}
return p_Original;
},
f_isFunction: function (p_Function) {
return !!(p_Function && p_Function.constructor && p_Function.call && p_Function.apply);
},
f_Initialize: function (p_Options) {
var base = this;
base.m_Options = base.f_MergeObjects(_LightBox.options, p_Options || {});
base.m_Elements = document.querySelectorAll(base.m_Options.selector);
base.m_ElementsLength = base.m_Elements.length - 1;
base.m_Body = document.getElementsByTagName("body")[0];
base.m_CurrentImageElement = false;
base.m_CurrentImageNumber = 0;
base.m_Direction = 1;
base.m_InProgress = false;
base.m_InstalledImageBox = false;
console.log(base.m_Elements);
// Check if hardware acceleration is supported and check if touch is enabled.
base.f_CheckBrowser();
// Adds events.
base.f_AddEvents();
},
f_CheckBrowser: function () {
var base = this,
isTouch = "ontouchstart" in window || window.navigator.msMaxTouchPoints || navigator.maxTouchPoints || false,
vendors = ["ms", "O", "Moz", "Webkit", "Khtml"],
rootStyle = docElem.style,
hardwareAccelerated = false;
if ("transform" in rootStyle) {
hardwareAccelerated = true;
} else {
while (vendors.length) {
if (vendors.pop() + "Transform" in rootStyle) {
hardwareAccelerated = true;
}
}
}
base.browser = {
"isHardwareAccelerated": hardwareAccelerated,
"isTouch": isTouch
};
},
f_AddEvents: function () {
var base = this;
// Add open image event on images.
for (var i = 0; i < base.m_Elements.length; i++) {
(function (i) {
base.m_Elements[i].addEventListener("click", function (event) {
event.preventDefault();
console.log(base.m_Elements[i]);
if (base.f_isFunction(base.m_Options.onImageStart)) {
base.m_Options.onImageStart();
}
base.f_OpenImage(i);
}, false);
})(i);
}
// Resize event for window.
window.addEventListener("resize", function (event) {
event.preventDefault();
base.f_SetImage();
}, false);
// Add keyboard support.
if (base.m_Options.enableKeyboard) {
var keyBoard = {
left: 37,
right: 39,
esc: 27
};
window.addEventListener("keydown", function (event) {
event.preventDefault();
if (base.m_CurrentImageElement) {
if (base.m_InProgress) {
return false;
}
switch (event.keyCode) {
case keyBoard.left:
// If the previous one is out of target range then go to the last image.
if ((base.m_CurrentImageNumber - 1) < 0) {
base.f_OpenImage(base.m_ElementsLength, "left");
} else {
base.f_OpenImage(base.m_CurrentImageNumber - 1, "left");
}
return false;
case keyBoard.right:
// If the next one is out of target range then go to the first image.
if ((base.m_CurrentImageNumber + 1) > base.m_ElementsLength) {
base.f_OpenImage(0, "right");
} else {
base.f_OpenImage(base.m_CurrentImageNumber + 1, "right");
}
return false;
case keyBoard.esc:
base.f_QuitImage();
return false;
}
}
return false;
}, false);
}
// Add document click event.
if (base.m_Options.quitOnDocumentClick) {
document.body.addEventListener("click", function (event) {
var target = event.target ? event.target : event.srcElement;
event.preventDefault();
if (target && target.id != "imagelightbox" && base.m_CurrentImageElement && !base.m_InProgress && base.m_InstalledImageBox) {
base.f_QuitImage();
return false;
}
return false;
}, false);
}
},
f_OpenImage: function (p_WhichOne, p_Direction) {
var base = this,
newFragment = document.createDocumentFragment(),
newImageElement = document.createElement("img"),
target = base.m_Elements[p_WhichOne].getAttribute("href");
if (base.m_CurrentImageElement) {
base.f_RemoveImage();
}
if (base.f_isFunction(base.m_Options.imageLoadStart)) {
base.m_Options.imageLoadStart();
}
base.m_InProgress = true;
base.m_InstalledImageBox = false;
base.m_Direction = typeof p_Direction === "undefined" ? 1 : p_Direction == "left" ? -1 : 1;
newImageElement.setAttribute("src", target);
newImageElement.setAttribute("alt", "LightBox");
newImageElement.setAttribute("id", base.m_Options.boxId);
newFragment.appendChild(newImageElement);
base.m_Body.appendChild(newFragment);
base.m_CurrentImageElement = document.getElementById(base.m_Options.boxId);
base.m_CurrentImageElement.style.opacity = "0";
base.m_CurrentImageNumber = p_WhichOne;
if (base.m_Options.quitOnImageClick) {
base.f_ImageClickEvent = function (event) {
event.preventDefault();
base.f_QuitImage();
};
base.m_CurrentImageElement.addEventListener("click", base.f_ImageClickEvent, false);
}
if (base.browser.isHardwareAccelerated) {
DomM.css.set(base.m_CurrentImageElement, base.f_AddTransitionSpeed(base.m_Options.animationSpeed));
}
base.f_SetImage();
DomM.css.set(base.m_CurrentImageElement, base.f_doTranslateX(50 * base.m_Direction + "px"));
setTimeout(function () {
if (base.browser.isHardwareAccelerated) {
setTimeout(function () {
DomM.css.set(base.m_CurrentImageElement, base.f_doTranslateX("0px"));
}, 50);
}
if (base.f_isFunction(base.m_Options.imageLoadEnd)) {
base.m_Options.imageLoadEnd();
}
}, 20);
setTimeout(function () {
base.m_InProgress = false;
base.m_InstalledImageBox = true;
}, base.m_Options.animationSpeed - 200);
},
f_SetImage: function () {
var base = this,
screenHeight = window.innerHeight || docElem.offsetHeight,
screenWidth = window.innerWidth || docElem.offsetWidth,
tmpImage = new Image(),
imageWidth, imageHeight, imageSizeRatio;
if (!base.m_CurrentImageElement) {
return;
}
tmpImage.onload = function () {
imageWidth = this.width;
imageHeight = this.height;
imageSizeRatio = imageWidth / imageHeight;
if (Math.floor(screenWidth/imageSizeRatio) > screenHeight) {
imageWidth = screenHeight * imageSizeRatio * 0.7;
imageHeight = screenHeight * 0.7;
} else {
imageWidth = screenWidth * 0.7;
imageHeight = screenWidth / imageSizeRatio * 0.7;
}
DomM.css.set(base.m_CurrentImageElement, {
"top": ((screenHeight - imageHeight) / 2) + "px",
"left": ((screenWidth - imageWidth) / 2) + "px",
"width": Math.floor(imageWidth) + "px",
"height": Math.floor(imageHeight) + "px",
"opacity": 1
});
};
tmpImage.src = base.m_CurrentImageElement.getAttribute("src");
},
f_RemoveImage: function () {
var base = this;
if (base.m_CurrentImageElement) {
if (base.f_isFunction(base.m_Options.quitOnImageClick)) {
base.m_CurrentImageElement.removeEventListener("click", base.f_ImageClickEvent, false);
}
base.m_CurrentImageElement.parentNode.removeChild(base.m_CurrentImageElement);
base.m_CurrentImageElement = false;
}
return false;
},
f_QuitImage: function () {
var base = this;
if (base.m_CurrentImageElement) {
setTimeout(function () {
DomM.css.set(base.m_CurrentImageElement, {
"opacity": 0,
"transition": ("opacity " + base.m_Options.fadeOutSpeed + "ms ease")
});
setTimeout(function () {
base.f_RemoveImage();
if (base.f_isFunction(base.m_Options.onImageQuit)) {
base.m_Options.onImageQuit();
}
}, base.m_Options.fadeOutSpeed);
}, 20);
}
},
f_IsValidSource: function (p_Src) {
return new RegExp().test(p_Src);
},
f_doTranslateX: function (p_Pixels) {
return {
"-webkit-transform": "translateX(" + p_Pixels + ")",
"-moz-transform": "translateX(" + p_Pixels + ")",
"-o-transform": "translateX(" + p_Pixels + ")",
"-ms-transform": "translateX(" + p_Pixels + ")",
"transform": "translateX(" + p_Pixels + ")"
};
},
f_AddTransitionSpeed: function (p_Speed) {
var base = this;
return {
"-webkit-transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease",
"-moz-transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease",
"-o-transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease",
"transition": "transform " + p_Speed + "ms ease, opacity " + base.m_Options.fadeInSpeed + "ms ease"
};
}
};
_LightBox.options = {
selector: "[data-imagelightbox]",
boxId: "imagelightbox",
allowedTypes: "png|jpg|jpeg|gif",
quitOnImageClick: true,
quitOnDocumentClick: true,
enableKeyboard: true,
animationSpeed: 750,
fadeInSpeed: 500,
fadeOutSpeed: 200,
imageLoadStart: function () {},
imageLoadEnd: function () {},
onImageQuit: function () {},
onImageStart: function () {}
};
LightBox.init = function (p_Options) {
_LightBox.f_Initialize(p_Options);
};
})(window, document, window.LightBox = window.LightBox || {});
var activityIndicatorOn = function () {
var newE = document.createElement("div"),
newB = document.createElement("div");
newE.setAttribute("id", "imagelightbox-loading");
newE.appendChild(newB);
document.body.appendChild(newE);
},
activityIndicatorOff = function () {
var elE = document.getElementById("imagelightbox-loading");
elE.parentNode.removeChild(elE);
};
LightBox.init({
selector: "[data-simplbox='demo1']",
boxId: "simplbox"
});
LightBox.init({
selector: "[data-simplbox='demo2']",
boxId: "simplbox",
imageLoadStart: activityIndicatorOn,
imageLoadEnd: activityIndicatorOff
});
Your code is almost working. What you handled badly is the fact that you can perform several init. On each init, you overwrite some items, especially with this line :
base.m_Elements = document.querySelectorAll(base.m_Options.selector);
So base.m_Elements will only have the elements of the last init.
( Based on the name 'init' i wonder if the real use case wouldn't be to allow just one call of init... )
Quick-fix is to do one single init with :
LightBox.init({
selector: "[data-simplbox='demo1'],[data-simplbox='demo2']",
boxId: "simplbox"
});
(erase the two calls to init)
And here it works.
http://jsfiddle.net/gamealchemist/66HFU/1/
So i guess either you want to support several init, or (easier to maintain in fact), throw exception on multiple init and expect the lib user to write the right selector in the single init call.
Edit : Super quick fix for your issue : rather than having LightBox as a singleton, have it as a Class :
function LightBox( initArguments ) {
// something like what was done in init
}
LightBox.prototype = {
f_RemoveImage : function() {
} ,
f_OpenImage : function( ..., ... ) {
} ,
...
}
then you can call with no issue :
var demo1LB = new LightBox({ selector: "[data-simplbox='demo1']",
boxId: "simplbox" });
var demo2LB = new LightBox({ selector: "[data-simplbox='demo2']",
boxId: "simplbox" });

jQuery .data() is being overwritten

I currently have the following code for a jQuery tooltip plugin I am writing. I am storing the config for each tooltip with jQuery's .data() method. However, when I go to retrieve the data it has been overwritten by the most recently stored data from a completely different selector. I can't figure out the issue as it was working prior and then suddenly stopped. The main areas to look in are the addTooltip(), removeTooltip(), and displayTooltip().
Example:
$('#tooltip1').addTooltip('tooltip', { 'direction': 'bottom' });
$('#tooltip2').addTooltip('tooltip', { 'direction': 'left' });
In the above example I am selecting two completely different elements however when I display the #tooltip1 tooltip it will be using #tooltip2's config which in this case is 'direction': 'left'.
Any help is appreciated.
(function($) {
// Used as a template for addTooltip()
var tooltipDefaults = {
'class': null,
'showOn': 'mouseenter',
'hideOn': 'mouseleave',
'direction': 'top',
'offset': 0
}
// Store generated IDs to avoid conflicting IDs
var tooltipIds = new Array();
// Keep track of displayed popups
var displayedTooltips = new Array();
function generateUniqueId()
{
var id;
do {
id = Math.floor(Math.random()*90000) + 10000;
} while ($.inArray(id, tooltipIds) !== -1);
tooltipIds.push(id);
return id;
}
function getUniqueId(id)
{
return parseInt(id.substr(0, 5));
}
function isUniqueId(id)
{
return !NaN(getUniqueId(id));
}
function removeUniqueId(id)
{
var id = getUniqueId(id);
var idIndex = $.inArray(id, tooltipIds);
if (idIndex !== -1) {
tooltipIds.splice(idIndex);
}
}
$.fn.displayTooltip = function()
{
var element = $(this);
var tooltip = $('#' + element.attr('data-tooltip-id'));
var config = element.data('config');
var offset = element.offset();
var left;
var top;
switch (config.direction) {
case 'left':
top = offset.top + "px";
left = offset.left - tooltip.outerWidth() - config.offset + "px";
break;
case 'top':
top = offset.top - element.outerHeight() - config.offset + "px";
left = offset.left + ((element.outerWidth() / 2) - (tooltip.outerWidth() / 2)) + "px";
break;
case 'right':
top = offset.top + "px";
left = offset.left + element.outerWidth() + config.offset + "px";
break;
case 'bottom':
top = offset.top + element.outerHeight() + config.offset + "px";
left = offset.left + ((element.outerWidth() / 2) - (tooltip.outerWidth() / 2)) + "px";
break;
}
tooltip.css({
'position': 'absolute',
'left': left,
'top': top,
'z-index': 5000
});
if (element.isTooltipDisplayed()) {
return;
}
tooltip.show();
displayedTooltips.push(element.attr('id'));
}
$.fn.hideTooltip = function()
{
var element = $(this);
var idIndex = $.inArray(element.attr('id'), displayedTooltips);
if (idIndex !== -1) {
displayedTooltips.splice(idIndex);
}
$('#' + element.attr('data-tooltip-id')).hide();
}
$.fn.addTooltip = function(content, params)
{
var config = $.extend(tooltipDefaults, params);
return this.each(function() {
var element = $(this);
// If the element already has a tooltip change the content inside of it
if (element.hasTooltip()) {
$('#' + element.attr('data-tooltip-id')).html(content);
return;
}
var tooltipId = (element.is('[id]') ? element.attr('id') : generateUniqueId()) + '-tooltip';
element.attr('data-tooltip-id', tooltipId);
var tooltip = $('<div>', {
id: tooltipId,
role: 'tooltip',
class: config.class
}).html(content);
$('body').append(tooltip);
/**
* If showOn and hideOn are the same events bind a toggle
* listener else bind the individual listeners
*/
if (config.showOn === config.hideOn) {
element.on(config.showOn, function() {
if (!element.isTooltipDisplayed()) {
element.displayTooltip();
} else {
element.hideTooltip();
}
});
} else {
element.on(config.showOn, function() {
element.displayTooltip();
}).on(config.hideOn, function() {
element.hideTooltip();
});
}
// Store config for other functions use
element.data('config', config);
// Saftey check incase the element recieved focus from the code running above
element.hideTooltip();
});
}
$.fn.hasTooltip = function()
{
return $(this).is('[data-tooltip-id]');
}
$.fn.isTooltipDisplayed = function()
{
var element = $(this);
if (!element.hasTooltip()) {
return false;
}
return ($.inArray(element.attr('id'), displayedTooltips) === -1) ? false : true;
}
$.fn.removeTooltip= function()
{
return this.each(function() {
var element = $(this);
var tooltipId = element.attr('data-tooltip-id');
var config = element.data('config');
$('#' + tooltipId).remove();
if (isUniqueId(tooltpId)) {
removeUniqueId(tooltipId);
}
element.removeAttr('data-tooltip-id');
if (config.showOn === config.hideOn) {
element.off(config.showOn);
} else {
element.off(config.showOn);
element.off(config.hideOn);
}
element.removeData('config');
});
}
// Reposition tooltip on window resize
$(window).on('resize', function() {
if (displayedTooltips.length < 1) {
return;
}
for (var i = 0; i < displayedTooltips.length; i++) {
$('#' + displayedTooltips[i]).displayTooltip();
console.log(displayedTooltips);
}
});
}(jQuery));
When you do this:
element.data('config', config);
config will be prone to unwanted modification whenever we call:
var config = $.extend(tooltipDefaults, params);
An example of this: http://jsfiddle.net/j8v4s/1/
You can solve this by creating a new object that inherits from tooltipDefaults but when modified, only itself will be changed. You can make your tooltipDefaults object a constructor like so:
function TooltipDefaults() {
this.class = null;
this.showOn = 'mouseenter';
this.hideOn = 'mouseleave';
this.direction = 'top';
this.offset = 0;
}
Now we can just do this:
var config = new TooltipDefaults();
$.extend(config, params);
Example: http://jsfiddle.net/sXSFy/4/
And here's a working example of your plugin: http://jsfiddle.net/DWtL5/2/
put the declaration of config inside the each loop
return this.each(function() {
var element = $(this);
var config = $.extend(tooltipDefaults, params);
...
otherwise the config in each of the elements data is going to reference that single config object, and when you change it the changes will be seen by each of the references.
You can also use the extend method again to make a clone of the config
var defConfig = $.extend(tooltipDefaults, params);
return this.each(function() {
var element = $(this);
var config = $.extend({}, defConfig);

Categories