Related
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)
i have this javascript that I called cookiebar.js, it shows a sticky bar message for cookies, (source code)
(function (context) {
"use strict";
var win = context,
doc = win.document;
var global_instance_name = "cbinstance";
function contentLoaded(win, fn) {
var done = false,
top = true,
doc = win.document,
root = doc.documentElement,
add = doc.addEventListener ? "addEventListener" : "attachEvent",
rem = doc.addEventListener ? "removeEventListener" : "detachEvent",
pre = doc.addEventListener ? "" : "on",
init = function (e) {
if (e.type == "readystatechange" && doc.readyState != "complete") return;
(e.type == "load" ? win : doc)[rem](pre + e.type, init, false);
if (!done && (done = true)) fn.call(win, e.type || e);
},
poll = function () {
try {
root.doScroll("left");
} catch (e) {
setTimeout(poll, 50);
return;
}
init("poll");
};
if (doc.readyState == "complete") fn.call(win, "lazy");
else {
if (doc.createEventObject && root.doScroll) {
try {
top = !win.frameElement;
} catch (e) {}
if (top) poll();
}
doc[add](pre + "DOMContentLoaded", init, false);
doc[add](pre + "readystatechange", init, false);
win[add](pre + "load", init, false);
}
}
var Cookies = {
get: function (key) {
return decodeURIComponent(doc.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
set: function (key, val, end, path, domain, secure) {
if (!key || /^(?:expires|max\-age|path|domain|secure)$/i.test(key)) {
return false;
}
var expires = "";
if (end) {
switch (end.constructor) {
case Number:
expires = end === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + end;
break;
case String:
expires = "; expires=" + end;
break;
case Date:
expires = "; expires=" + end.toUTCString();
break;
}
}
doc.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(val) + expires + (domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "") + (secure ? "; secure" : "");
return true;
},
has: function (key) {
return new RegExp("(?:^|;\\s*)" + encodeURIComponent(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=").test(doc.cookie);
},
remove: function (key, path, domain) {
if (!key || !this.has(key)) {
return false;
}
doc.cookie = encodeURIComponent(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "");
return true;
},
};
var Utils = {
merge: function () {
var obj = {},
i = 0,
al = arguments.length,
key;
if (0 === al) {
return obj;
}
for (; i < al; i++) {
for (key in arguments[i]) {
if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
obj[key] = arguments[i][key];
}
}
}
return obj;
},
str2bool: function (str) {
str = "" + str;
switch (str.toLowerCase()) {
case "false":
case "no":
case "0":
case "":
return false;
default:
return true;
}
},
fade_in: function (el) {
if (el.style.opacity < 1) {
el.style.opacity = (parseFloat(el.style.opacity) + 0.05).toFixed(2);
win.setTimeout(function () {
Utils.fade_in(el);
}, 50);
}
},
get_data_attribs: function (script) {
var data = {};
if (Object.prototype.hasOwnProperty.call(script, "dataset")) {
data = script.dataset;
} else {
var attribs = script.attributes;
var key;
for (key in attribs) {
if (Object.prototype.hasOwnProperty.call(attribs, key)) {
var attr = attribs[key];
if (/^data-/.test(attr.name)) {
var camelized = Utils.camelize(attr.name.substr(5));
data[camelized] = attr.value;
}
}
}
}
return data;
},
normalize_keys: function (options_object) {
var camelized = {};
for (var key in options_object) {
if (Object.prototype.hasOwnProperty.call(options_object, key)) {
var camelized_key = Utils.camelize(key);
camelized[camelized_key] = options_object[camelized_key] ? options_object[camelized_key] : options_object[key];
}
}
return camelized;
},
camelize: function (str) {
var separator = "-",
match = str.indexOf(separator);
while (match != -1) {
var last = match === str.length - 1,
next = last ? "" : str[match + 1],
upnext = next.toUpperCase(),
sep_substr = last ? separator : separator + next;
str = str.replace(sep_substr, upnext);
match = str.indexOf(separator);
}
return str;
},
find_script_by_id: function (id) {
var scripts = doc.getElementsByTagName("script");
for (var i = 0, l = scripts.length; i < l; i++) {
if (id === scripts[i].id) {
return scripts[i];
}
}
return null;
},
};
var script_el_invoker = Utils.find_script_by_id("cookiebanner");
var Cookiebanner = (context.Cookiebanner = function (opts) {
this.init(opts);
});
Cookiebanner.prototype = {
cookiejar: Cookies,
init: function (opts) {
this.inserted = false;
this.closed = false;
this.test_mode = false;
var default_text = "This site uses cookies.";
var default_link = "Detail";
this.default_options = {
cookie: "cookiebanner-accepted",
closeText: "✖",
cookiePath: "/",
debug: false,
expires: Infinity,
zindex: 255,
mask: false,
maskOpacity: 0.5,
maskBackground: "#000",
height: "auto",
minHeight: "21px",
bg: "#000",
fg: "#ddd",
link: "#aaa",
position: "bottom",
message: default_text,
linkmsg: default_link,
moreinfo: "http://www.examplesite123.com/cookie-policy/",
effect: null,
fontSize: "14px",
fontFamily: "arial, sans-serif",
instance: global_instance_name,
textAlign: "center",
acceptOnScroll: true,
};
this.options = this.default_options;
this.script_el = script_el_invoker;
if (this.script_el) {
var data_options = Utils.get_data_attribs(this.script_el);
this.options = Utils.merge(this.options, data_options);
}
if (opts) {
opts = Utils.normalize_keys(opts);
this.options = Utils.merge(this.options, opts);
}
global_instance_name = this.options.instance;
this.options.zindex = parseInt(this.options.zindex, 10);
this.options.mask = Utils.str2bool(this.options.mask);
if ("string" === typeof this.options.expires) {
if ("function" === typeof context[this.options.expires]) {
this.options.expires = context[this.options.expires];
}
}
if ("function" === typeof this.options.expires) {
this.options.expires = this.options.expires();
}
if (this.script_el) {
this.run();
}
},
log: function () {
if ("undefined" !== typeof console) {
console.log.apply(console, arguments);
}
},
run: function () {
if (!this.agreed()) {
var self = this;
contentLoaded(win, function () {
self.insert();
});
}
},
build_viewport_mask: function () {
var mask = null;
if (true === this.options.mask) {
var mask_opacity = this.options.maskOpacity;
var bg = this.options.maskBackground;
var mask_markup =
'<div id="cookiebanner-mask" style="' +
"position:fixed;top:0;left:0;width:100%;height:100%;" +
"background:" +
bg +
";zoom:1;filter:alpha(opacity=" +
mask_opacity * 100 +
");opacity:" +
mask_opacity +
";" +
"z-index:" +
this.options.zindex +
';"></div>';
var el = doc.createElement("div");
el.innerHTML = mask_markup;
mask = el.firstChild;
}
return mask;
},
agree: function () {
this.cookiejar.set(this.options.cookie, 1, this.options.expires, this.options.cookiePath);
return true;
},
agreed: function () {
return this.cookiejar.has(this.options.cookie);
},
close: function () {
if (this.inserted) {
if (!this.closed) {
if (this.element) {
this.element.parentNode.removeChild(this.element);
}
if (this.element_mask) {
this.element_mask.parentNode.removeChild(this.element_mask);
}
this.closed = true;
}
}
return this.closed;
},
agree_and_close: function () {
this.agree();
return this.close();
},
cleanup: function () {
this.close();
return this.unload();
},
unload: function () {
if (this.script_el) {
this.script_el.parentNode.removeChild(this.script_el);
}
context[global_instance_name] = undefined;
return true;
},
insert: function () {
this.element_mask = this.build_viewport_mask();
var zidx = this.options.zindex;
if (this.element_mask) {
zidx += 1;
}
var el = doc.createElement("div");
el.className = "cookiebanner";
el.style.position = "fixed";
el.style.left = 0;
el.style.right = 0;
el.style.height = this.options.height;
el.style.minHeight = this.options.minHeight;
el.style.zIndex = zidx;
el.style.background = this.options.bg;
el.style.color = this.options.fg;
el.style.lineHeight = el.style.minHeight;
el.style.padding = "5px 16px";
el.style.fontFamily = this.options.fontFamily;
el.style.fontSize = this.options.fontSize;
el.style.textAlign = this.options.textAlign;
if ("top" === this.options.position) {
el.style.top = 0;
} else {
el.style.bottom = 0;
}
el.innerHTML = '<div class="cookiebanner-close" style="float:right;padding-left:5px;">' + this.options.closeText + "</div>" + "<span>" + this.options.message + " <a>" + this.options.linkmsg + "</a></span>";
this.element = el;
var el_a = el.getElementsByTagName("a")[0];
el_a.href = this.options.moreinfo;
el_a.target = "_blank";
el_a.style.textDecoration = "none";
el_a.style.color = this.options.link;
var el_x = el.getElementsByTagName("div")[0];
el_x.style.cursor = "pointer";
function on(el, ev, fn) {
var add = el.addEventListener ? "addEventListener" : "attachEvent",
pre = el.addEventListener ? "" : "on";
el[add](pre + ev, fn, false);
}
var self = this;
on(el_x, "click", function () {
self.agree_and_close();
});
if (this.element_mask) {
on(this.element_mask, "click", function () {
self.agree_and_close();
});
doc.body.appendChild(this.element_mask);
}
if (this.options.acceptOnScroll) {
on(window, "scroll", function () {
self.agree_and_close();
});
}
doc.body.appendChild(this.element);
this.inserted = true;
if ("fade" === this.options.effect) {
this.element.style.opacity = 0;
Utils.fade_in(this.element);
} else {
this.element.style.opacity = 1;
}
},
};
if (script_el_invoker) {
if (!context[global_instance_name]) {
context[global_instance_name] = new Cookiebanner();
}
}
})(window);
I load it in this way in functions.php in Wordpress:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
It works fine.
Now i duplicate the same javascript code and i called it stickybar.js. I add some modifications, also change class with name "stickybar":
The code of the stickybar.js is here (i pasted it in jsfiddle because there is too much text for stackoverflow)
Then i show this second bar (stickybar.js) only on mobile device and after 8 second with this CSS:
.stickybar { display: none; }
#media only screen and (max-device-width:480px) {
.stickybar {
display: block;
animation: cssAnimation 0s 8s forwards;
visibility: hidden;
}
#keyframes cssAnimation {
to { visibility: visible; }
}
}
I load it in Wordpress with this code in functions.php:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
It works fine.
If i load one by one of this codes, they work fine.
The problem is that when i load the two scripts together in this way in functions.php, only the first works:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
How can i load the two scripts together?
The comment thread on this question is semantically correct, you can only have one instance of each html id attribute, they must be unique, and your find_script_by_id methods are both searching for the same thing.
However, you're doing what's generally called "baking in" the scripts into your header which is at best, a faux pas, at least as far as WordPress is concerned. Properly Enqueueing Scripts (and styles) is very easy in WordPress, and your future self, web clients, and other people who look at your code will thank you for doing it.
It's not unlike how you're "baking in" the scripts now:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
But with a few things changed:
function enqueue_my_scripts(){
wp_enqueue_script( 'cookie-bar', 'https://www.examplesite123.com/cookiebar.js', array(), '1.0', true );
wp_enqueue_script( 'sticky-bar', 'https://www.examplesite123.com/stickybar.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_scripts' );
Namely, it uses the wp_enqueue_script() function on the wp_enqueue_scripts hook. This lets you defer the script to the footer, load in the header, add version numbers to prevent caching issues, add dependencies, allows you to dynamically add/remove them programatically,gives them unique ID's based on the handle, and much more. (You do still need to update your find_script_by_id functions to use these new handles instead cookie-bar, sticky-bar, change the global_instance_name, etc. (more on that in a second)
With that said, if the .js files are on your server, you'll want to use site_url(), plugins_url(), get_stylesheet_directory_uri(), or similar functions to grab the URL of the file instead of typing it out. If you're using a remote resource, don't worry about it, but if they're on you're site, you should swap out the baked in version for that so you don't have issues if you ever move your site, and it allows you easier methods to edit the version to prevent caching problems if you change them.
Back to your variables, you may also want to replace your find_script_by_id type functions with document.currentScript instead, to allow them to be more abstract and not rely on typo/duplicate prone element IDs, and instead reference the currently running <script> tag.
I am testing my page in Chrome. I right click on the element that I am having issues with and I get this:
element.style {
height: 147px;
position: relative;
width: 100%;
overflow: hidden;
}
without a file attached to it. This tells me that the element style is coming from either an inline code (my page has none) or a js file (which my page has a number).
When I turn off the position: relative, I no longer have any issues.
I think I have narrowed it down to one js file that is screwing up my page, but I don't have a clue as to how to fix it or how to figure it out.
Here are some images better describing the issue:
http://i.imgur.com/Yxv2zLe.png
http://i.imgur.com/wtqkqw5.png
If you look at the first image, the blue box over the image needs to be directly over the orange box so that everything lines up properly.
In the second image, when I turn off the position, the image is positions correctly under the overlay.
My problem is that I don't know enough about js to fix the code to fix the position.
Here is the code that I think is responsible, if it helps.
/* ---------------------------------------------------------------------- */
/* Entry Slider
/* ---------------------------------------------------------------------- */
if ($().cycle) {
var entrySliders = $('.entry-slider > ul');
$.fn.cycle.transitions.scrollHorizontal = function ($cont, $slides, opts) {
$cont.css('overflow', 'hidden');
opts.before.push($.fn.cycle.commonReset);
var w = $cont.width();
opts.cssFirst.left = 0;
opts.cssBefore.left = w;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
opts.animOut.left = 0 - w;
if ($cont.data('dir') === 'prev') {
opts.cssBefore.left = -w;
opts.animOut.left = w;
}
};
function initEntrySlider(entrySliders, isFirstTime) {
entrySliders.each(function (i) {
var slider = $(this);
var initPerformed = isFirstTime && slider.data('initInvoked');
if (!initPerformed) {
slider.data('initInvoked', 'true');
var sliderId = 'entry-slider-' + i;
slider.attr('id', sliderId);
var prevButtonId = sliderId + '-prev';
var nextButtonId = sliderId + '-next';
if (slider.data('enable') === 'false') {
return;
}
slider.css('height', slider.children('li:first').height());
var firstSlide = slider.children('li')[0];
var lastSlide = slider.children('li')[slider.children('li').length - 1];
if (slider.children('li').length > 1) {
if (slider.parent().find('#' + prevButtonId).length == 0) {
slider.parent().append('<div class="entry-slider-nav"><a id="' + prevButtonId + '" class="prev">Prev</a><a id="' + nextButtonId + '" class="next">Next</a></div>');
}
}
slider.cycle({
onPrevNextEvent: function (isNext, zeroBasedSlideIndex, slideElement) {
$(slideElement).parent().data('dir', isNext ? 'next' : 'prev');
},
before: function (curr, next, opts, forwardFlag) {
var $this = $(this);
var sliderId = $this.closest('ul').attr('id');
// set the container's height to that of the current slide
$this.parent().stop().animate({height: $this.height()}, opts.speed);
if (opts['nowrap']) {
var prevButton = $('#' + sliderId + '-prev');
var nextButton = $('#' + sliderId + '-next');
if ((firstSlide == next) && (!prevButton.hasClass('disabled'))) {
prevButton.addClass('disabled');
} else {
prevButton.removeClass('disabled');
}
if ((lastSlide == next) && (!nextButton.hasClass('disabled'))) {
nextButton.addClass('disabled');
} else {
nextButton.removeClass('disabled');
}
}
},
containerResize: false,
pauseOnPagerHover: true,
nowrap: false, // if true, the carousel will not be circular
easing: 'easeInOutExpo',
fx: 'scrollHorizontal',
speed: 600,
timeout: 0,
fit: true,
width: '100%',
pause: true,
slideResize: true,
slideExpr: 'li',
prev: '#' + prevButtonId,
next: '#' + nextButtonId
});
}
});
if (Modernizr.touch && $().swipe) {
function doEntrySliderSwipe(e, dir) {
var sliderId = $(e.currentTarget).attr('id');
if (dir == 'left') {
$('#' + sliderId + '-next').trigger('click');
}
if (dir == 'right') {
$('#' + sliderId + '-prev').trigger('click');
}
}
entrySliders.each(function () {
var slider = $(this);
var initPerformed = isFirstTime && slider.data('swipeInvoked');
if (!initPerformed) {
slider.data('swipeInvoked', 'true');
slider.swipe({
click: function (e, target) {
$(target).trigger('click');
},
swipeLeft: doEntrySliderSwipe,
swipeRight: doEntrySliderSwipe,
allowPageScroll: 'auto'
});
}
});
}
}
function initAllEntrySliders(isFirstTime) {
if (isFirstTime) {
var timer = window.setTimeout(function () {
window.clearTimeout(timer);
initEntrySlider($('.entry-slider > ul'), isFirstTime);
}, 100);
} else {
initEntrySlider($('.entry-slider > ul'), isFirstTime);
}
}
function resizeEntrySlider(entrySliders) {
entrySliders.each(function () {
var slider = $(this);
slider.css('height', slider.children('li:first').height());
});
}
function loadEntrySlider() {
var entrySliderImages = $('.entry-slider > ul > li> a > img');
var unloadedImagesCount = 0;
var unloadedImages = [];
entrySliderImages.each(function () {
if (!this.complete && this.complete != undefined) {
unloadedImages.push(this);
unloadedImagesCount++;
}
});
if (unloadedImagesCount == 0) {
initAllEntrySliders(true);
} else {
var initAllEntrySlidersInvoked = false;
var loadedImagesCount = 0;
$(unloadedImages).bind('load', function () {
loadedImagesCount++;
if (loadedImagesCount === unloadedImagesCount) {
if (!initAllEntrySlidersInvoked) {
initAllEntrySlidersInvoked = true;
initAllEntrySliders(true);
}
}
});
var timer = window.setTimeout(function () {
window.clearTimeout(timer);
$(unloadedImages).each(function () {
if (this.complete || this.complete === undefined) {
$(this).trigger('load');
}
});
}, 50);
}
}
loadEntrySlider();
$(window).on('resize', function () {
var timer = window.setTimeout(function () {
window.clearTimeout(timer);
resizeEntrySlider(entrySliders);
}, 30);
});
}
And if I should be asking this somewhere else or something, let me know.
I'm facing weird behaviour of Jit Infovis i'm using. I have two different html files that include a load json function from a Javascript file. The function is using infovis library to display a hypertree map from a json file. Both two html files load the same json file.
One html file has been succeeded rendering the map properly. But another one has not. It renders the map almost properly, but after i debugged it, i got it not iterating over the root node. Then, the root node becames inactive without label and clickability.
This is the js function i'm using.
var labelType, useGradients, nativeTextSupport, animate;
(function () {
var ua = navigator.userAgent,
iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
typeOfCanvas = typeof HTMLCanvasElement,
nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
textSupport = nativeCanvasSupport
&& (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
//I'm setting this based on the fact that ExCanvas provides text support for IE
//and that as of today iPhone/iPad current text support is lame
labelType = (!nativeCanvasSupport || (textSupport && !iStuff)) ? 'Native' : 'HTML';
nativeTextSupport = labelType == 'Native';
useGradients = nativeCanvasSupport;
animate = !(iStuff || !nativeCanvasSupport);
})();
var Log = {
elem: false,
write: function (text) {
if (!this.elem)
this.elem = document.getElementById('log');
this.elem.innerHTML = text;
this.elem.style.left = (350 - this.elem.offsetWidth / 2) + 'px';
}
};
function init(slugParam, pageParam) {
var isFirst = true;
var isSetAsRoot = false;
// alert(slugParam+ " | "+pageParam);
var url = Routing.generate('trade_map_buyer_json', { slug : slugParam, page : pageParam });
//init data
$.getJSON(url, function (json) {
var type = 'Buyer';
//end
var infovis = document.getElementById('infovis');
infovis.style.align = "center";
infovis.innerHTML = '';
// infovis.innerHTML = '<img align="center" id="gifloader" style="margin-left:50%; margin-top:50%" src="{{ asset('/bundles/jariffproject/frontend/images/preloader.gif') }}" width="30px" height="30px"/>'
var w = infovis.offsetWidth - 50, h = infovis.offsetHeight - 50;
url = url.replace("/json/", "/");
window.history.pushState("object or string", "Title", url);
//init Hypertree
var ht = new $jit.Hypertree({
//id of the visualization container
injectInto: 'infovis',
Navigation: {
enable: false,
panning: 'avoid nodes',
},
//canvas width and height
width: w,
height
: h,
//Change node and edge styles such as
//color, width and dimensions.
Node: {
dim: 9,
overridable: true,
color: "#66FF33"
},
Tips: {
enable: true,
type: 'HTML',
offsetX: 0,
offsetY: 0,
onShow: function(tip, node) {
// dump(tip);
tip.innerHTML = "<div style='background-color:#F8FFC9;text-align:center;border-radius:5px; padding:10px 10px;' class='node-tip'><p style='font-size:100%;font-weight:bold;'>"+node.name+"</p><p style='font-size:50%pt'>"+node.data.address+"</p></div>";
}
},
Events: {
enable: true,
type: 'HTML',
onMouseEnter: function(node, eventInfo, e){
var nodeId = node.id;
var menu1 = [
{'set as Root':function(menuItem,menu) {
menu.hide();
isSetAsRoot = true;
console.log(nodeId);
init(nodeId, 0);
}},
$.contextMenu.separator,
{'View details':function(menuItem,menu) {
}}
];
$('.node').contextMenu(menu1,{theme:'vista'});
}
},
Edge: {
lineWidth: 1,
color: "#52D5DE",
overridable: true,
},
onBeforePlotNode: function(node)
{
if (isFirst) {
console.log(node._depth);
var odd = isOdd(node._depth);
if (odd) {
node.setData('color', "#66FF33"); // hijau (supplier)
} else {
node.setData('color', "#FF3300"); // merah (buyer)
}
isFirst = false;
}
},
onPlotNode: function(node)
{
if (isSetAsRoot) {
var nodeInstance = node.getNode();
var nodeId = nodeInstance.id;
init(nodeId, 0);
isSetAsRoot = false;
}
},
onBeforeCompute: function (domElement, node) {
var dot = ht.graph.getClosestNodeToOrigin("current");
type = isOdd(dot._depth) ? 'Supplier' : 'Buyer';
},
//Attach event handlers and add text to the
//labels. This method is only triggered on label
//creation
onCreateLabel: function (domElement, node) {
var odd = isOdd(node._depth);
if (odd) {
node.setData('color', "#66FF33"); // hijau (supplier)
} else {
node.setData('color', "#FF3300"); // merah (buyer)
}
domElement.innerHTML = node.name;
// if (node._depth == 1) {
console.log("|"+node.name+"|"+node._depth+"|");
// }
$jit.util.addEvent(domElement, 'click', function () {
ht.onClick(node.id, {
onComplete: function () {
console.log(node.id);
ht.controller.onComplete(node);
}
});
});
},
onPlaceLabel: function (domElement, node) {
var style = domElement.style;
style.display = '';
style.cursor = 'pointer';
if (node._depth <= 1) {
style.fontSize = "0.8em";
style.color = "#000";
style.fontWeight = "normal";
} else if (node._depth == 2) {
style.fontSize = "0.7em";
style.color = "#555";
} else {
style.display = 'none';
}
var left = parseInt(style.left);
var w = domElement.offsetWidth;
style.left = (left - w / 2) + 'px';
},
onComplete: function (node) {
var dot = ht.graph.getClosestNodeToOrigin("current");
console.log(dot._depth);
var connCount = dot.data.size;
var showingCount = '';
if (connCount != undefined) {
var pageParamInt = (parseInt(pageParam)+1) * 10;
var modulus = connCount%10;
showingCount = (pageParamInt - 9) + " - " + pageParamInt;
if (connCount - (pageParamInt - 9) < 10) {
showingCount = (pageParamInt - 10) + " - " + ((pageParamInt - 10) + modulus);
}
} else {
connCount = '0';
showingCount = 'No Connections Shown'
}
}
});
//load JSON data.
ht.loadJSON(json);
//compute positions and plot.
ht.refresh();
//end
ht.controller.onComplete();
});
}
function isEven(n)
{
return isNumber(n) && (n % 2 == 0);
}
function isOdd(n)
{
return isNumber(n) && (n % 2 == 1);
}
function isNumber(n)
{
return n === parseFloat(n);
}
function processAjaxData(response, urlPath){
}
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
out = out + "\n\n"
console.log(out);
// or, if you wanted to avoid alerts...
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre)
}
What's probably causing this?
Please check whether there is conflict id. Basically infovis render each nodes by the id.
And if there is an DOM element that has the same id with one DOM element of a node. It would conflict and won't render
you can check it by duming dom element iterating over the nodes.
I'm trying to call an external JS function from flash using the ExternalInterface.call() method in action script. The function should open a modal window that has been written in jQuery. My problem is two fold:
How do I open this modal window without attaching the action to a link? I just want the window open and to pass in the URL.
Is there a better way to do this?
(Code below - I only included the relevent functions. If more if needed, let me know)
ActionScript:
import flash.external.ExternalInterface;
function openMapWindowLink(thingName):Void {
ExternalInterface.call("openMapWindow",locationURL);
}
jQuery:
// Add the action to a link (this works)
function initAjaxPopups() {
$('.ajax-popup').simpleLightbox({
closeLink:'a.btn-close, a.close-popup',
faderOpacity: 0.7,
faderBackground: '#000',
href:true,
onClick: null
});
}
// Open the lightbox from flash with url (not working correctly)
function openMapWindow(locationURL) {
//alert('Clicked '+locationURL);
$simpleLightbox({
closeLink:'a.btn-close, a.close-popup',
faderOpacity: 0.7,
faderBackground: '#000',
href:locationURL,
onClick: null
});
}
/* ajax lightbox plugin */
jQuery.fn.simpleLightbox = function(_options){
var _options = jQuery.extend({
lightboxContentBlock: '.lightbox',
faderOpacity: 0.8,
faderBackground: '#ffffff',
closeLink:'a.close-btn, a.cancel',
href:true,
onClick: null
},_options);
var _popupCounter = 1;
return this.each(function(i, _this){
var _this = jQuery(_this);
if (!_options.href)
_this.lightboxContentBlock = _options.lightboxContentBlock;
else _this.lightboxContentBlock = _this.attr('href');
if (_this.lightboxContentBlock != '' && _this.lightboxContentBlock.length > 1) {
_this.faderOpacity = _options.faderOpacity;
_this.faderBackground = _options.faderBackground;
_this.closeLink = _options.closeLink;
var _fader;
var _lightbox = $(_this.lightboxContentBlock);
if (!jQuery('div.lightbox-fader').length)
_fader = $('body').append('<div class="lightbox-fader"></div>');
_fader = jQuery('div.lightbox-fader');
_lightbox.css({
'zIndex':999
});
_fader.css({
opacity:_this.faderOpacity,
backgroundColor:_this.faderBackground,
display:'none',
position:'absolute',
top:0,
left:0,
zIndex:998,
textIndent: -9999
}).text(' ');
_lightbox.shownFlag = false;
_this.click(function(){
if (jQuery.isFunction(_options.onClick)) {
_options.onClick.apply(_this);
}
var _popupURL = _this.attr('href');
if(jQuery('div[rel*="'+_popupURL+'"]').length == 0) {
$.ajax({
url: _popupURL,
global: false,
type: "GET",
dataType: "html",
success: function(msg){
// append loaded popup
_lightbox = $(msg);
_lightbox.attr('rel',_popupURL).css({
zIndex:999,
position:'absolute',
display:'block',
top: -9999,
left: -9999
});
_lightbox.attr('id','ajaxpopup'+_popupCounter);
jQuery('body').append(_lightbox);
// init js for lightbox
if(typeof initPopupJS == "function"){
initPopupJS(_lightbox);
}
_popupCounter++;
// attach close event
jQuery(_this.closeLink, _lightbox).click(function(){
_lightbox.fadeOut(400, function(){
_fader.fadeOut(300);
_scroll = false;
});
return false;
});
// show lightbox
_lightbox.hide();
_lightbox.shownFlag = true;
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
_fader.fadeIn(300, function(){
_lightbox.fadeIn(400);
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
if(typeof VSA_handleResize === 'function') {
VSA_handleResize();
}
});
},
error: function(msg){
alert('ajax error');
return false;
}
});
} else {
_lightbox = jQuery('div[rel*="'+_popupURL+'"]');
_lightbox.hide();
_lightbox.shownFlag = true;
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
_fader.fadeIn(300, function(){
_lightbox.fadeIn(400);
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
if(typeof VSA_handleResize === 'function') {
VSA_handleResize();
}
});
}
return false;
});
jQuery(_this.closeLink).click(function(){
_lightbox.fadeOut(400, function(){
_fader.fadeOut(300);
_scroll = false;
});
return false;
});
_fader.click(function(){
_lightbox.fadeOut(400, function(){
_fader.fadeOut(300);
});
return false;
});
var _scroll = false;
jQuery.fn.simpleLightbox.positionLightbox = function (_lbox) {
if(!_lbox.shownFlag) return false;
var _height = 0;
var _width = 0;
var _minWidth = $('body > div:eq(0)').outerWidth();
if (window.innerHeight) {
_height = window.innerHeight;
_width = window.innerWidth;
} else {
_height = document.documentElement.clientHeight;
_width = document.documentElement.clientWidth;
}
var _thisHeight = _lbox.outerHeight();
var _page = $('body');
if (_lbox.length) {
if (_width < _minWidth) {_fader.css('width',_minWidth);} else {_fader.css('width','100%');}
if (_height > _page.innerHeight()) _fader.css('height',_height); else _fader.css('height',_page.innerHeight());
if (_height > _thisHeight) {
if ($.browser.msie && $.browser.version < 7) {
_lbox.css({
position:'absolute',
top: (document.documentElement.scrollTop + (_height - _thisHeight) / 2)+"px"
});
} else {
_lbox.css({
position:'fixed',
top: ((_height - _lbox.outerHeight()) / 2)+"px"
});
}
}
else {
var _fh = parseInt(_fader.css('height'));
if (!_scroll) {
if (_fh - _thisHeight > parseInt($(document).scrollTop())) {
_fh = parseInt($(document).scrollTop())
_scroll = _fh;
} else {
_scroll = _fh - _thisHeight;
}
}
_lbox.css({
position:'absolute',
top: _scroll
});
}
if (_width > _lbox.outerWidth()) _lbox.css({left:((_width - _lbox.outerWidth()) / 2 + 10) + "px"});
else _lbox.css({position:'absolute',left: 0});
}
}
jQuery(window).resize(function(){
if (_lightbox.is(':visible'))
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
});
jQuery(window).scroll(function(){
if (_lightbox.is(':visible'))
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
});
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
$(document).keydown(function (e) {
if (!e) evt = window.event;
if (e.keyCode == 27) {
_lightbox.fadeOut(400, function(){
_fader.fadeOut(300);
});
}
});
}
});
}
If attaching lightBox to something which isn't a link it should be
$.simpleLightbox({...}) // with the "." after $
IF that doesnt work you could alter the lightBox plugin source, but this could be troublesome if you wish to update to a newer versions later.
This is a workaround that should work:
<a class="hidden" id="dummylink" href="#"> </a>
//on ready
$('#dummylink').simpleLightbox({...});
function openMapWindow(locationURL) {
$("#dummylink").attr("href", locationURL).trigger('click');
}