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');
}
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 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 am trying to make a jquery modal plugin and can't understand why my callback functions are firing on page load? I need to fire two functions beforeStart before opening popup window and afterComplete after popup window opens not when page loads but all it occurs on page load. What's wrong with code. I googled whole day still can't get it. this stackoverflow also doesn't works for me.
Here is my code
<script>
$(document).ready(function (e) {
$(".selector").coolBox({
OverlayClose: false,
complete : function(){//this should called when my plugin finished its work
console.log("complete");
},
beforeStart: function(){
console.log("before Start");
}
});
})
</script>
Edit: Here is full plugin code
;(function ($, window) {
$.coolBox = function (options) {
}
$.coolBox.closeCoolBox = function () {
console.log("closeCoolBox closes");
$("#clBoxOverlay,#clBoxOuterWrapper").remove();
};
$.coolBox.openCoolBox = function (options) {
console.log("closeCoolBox opens");
$("#inlineOverlayCloseDisabled").trigger("click");
//$.fn.coolBox(options);
$(this).each(function () {
console.log($(this));
})
};
$.fn.coolBox = function (options) {
console.log("calls to opens");
var settings = {
complete: false,
beforeStart: false,
Background: "#333",
Opacity: "0.8",
Padding: "10px",
Height: "auto",
Width: "auto",
OverlayClose: true,
EscClose: true,
Zindex: "99991",
Border: "2px",
BorderColor: "black",
PopUp: "fixed"
};
var o = {};
$.extend(o, settings, options);
//is this not for event handling before starting my plugin to change DOM?
if (typeof o.beforeStart == 'function') {
o.beforeStart.call(this); // brings the scope to the callback
}
return this.each(function () {
var link = $(this);
link.click(function (event) {
var clBox = document.createElement('div');
clBox.setAttribute("id", "clBoxWrapper");
document.body.appendChild(clBox);
$clBoxWrapper = $("#clBoxWrapper");
$clBoxWrapper.wrap($("<div id='clBoxOuterWrapper'></div>"));
oBox = document.getElementById("clBoxOuterWrapper");
oBox.style.width = o.Width;
oBox.style.height = o.Height;
if (o.PopUp == "fixed") {
oBox.style.position = "fixed";
} else {
oBox.style.position = "absolute";
}
oBox.style.zIndex = o.Zindex + 1;
var olBox = document.createElement('div');
olBox.setAttribute("id", "clBoxOverlay");
olBox.style.width = "100%";
olBox.style.height = "100%";
olBox.style.position = "fixed";
olBox.style.zIndex = o.Zindex;
olBox.style.opacity = o.Opacity;
olBox.style.backgroundColor = o.Background;
olBox.style.top = "0px";
olBox.style.left = "0px";
document.body.appendChild(olBox);
$wrapContent = link.attr("href");
//alert($wrapContent);
if ($wrapContent.indexOf("#") == 0) {
$wrapContainer = $($wrapContent).html();
//alert($wrapContainer);
$oBoxWrapper = $("#clBoxOuterWrapper");
$clBoxOverlay = $("#clBoxOverlay");
$clBoxOverlay.css({
"height": $(document).innerHeight(),
"width": $(document).innerWidth(),
});
if ($oBoxWrapper.length) {
$clBoxWrapper.html($wrapContainer);
if (o.PopUp == "fixed") {
$oBoxWrapper.css({"maxHeight": $(window).height()});
if ($oBoxWrapper.innerHeight() >= $(window).height()) {
$oBoxWrapper.css("overflowY", "scroll");
}
if ($oBoxWrapper.innerWidth() >= $(window).width()) {
$oBoxWrapper.css("overflowX", "scroll");
}
}
$oBoxWrapper.css({
"left": ($(window).width() - $oBoxWrapper.innerWidth()) / 2,
"top": ($(window).height() - $oBoxWrapper.innerHeight()) / 2
});
}
}
event.preventDefault();
});
//is this not event handling code after my plugin finished it task?
if (typeof o.complete == 'function') {
o.complete.call(this); // brings the scope to the callback
}
});
}
})(jQuery, window)
It shows me the information in image when page loads but when i click on my selector link it does not fires my callback functions.
If you want to fire complete callback function when the click event is fired, just move the call inside:
;(function ($, window) {
$.fn.coolBox = function (options) {
console.log("calls to opens");
var settings = {
complete: false,
beforeStart: false,
Background: "#333",
Opacity: "0.8",
Padding: "10px",
Height: "auto",
Width: "auto",
OverlayClose: true,
EscClose: true,
Zindex: "99991",
Border: "2px",
BorderColor: "black",
PopUp: "fixed"
};
var o = {};
$.extend(o, settings, options);
//is this not for event handling before starting my plugin to change DOM?
if (typeof o.beforeStart == 'function') {
o.beforeStart.call(this); // brings the scope to the callback
}
return this.each(function () {
var link = $(this);
link.click(function (event) {
var clBox = document.createElement('div');
clBox.setAttribute("id", "clBoxWrapper");
document.body.appendChild(clBox);
$clBoxWrapper = $("#clBoxWrapper");
$clBoxWrapper.wrap($("<div id='clBoxOuterWrapper'></div>"));
oBox = document.getElementById("clBoxOuterWrapper");
oBox.style.width = o.Width;
oBox.style.height = o.Height;
if (o.PopUp == "fixed") {
oBox.style.position = "fixed";
} else {
oBox.style.position = "absolute";
}
oBox.style.zIndex = o.Zindex + 1;
var olBox = document.createElement('div');
olBox.setAttribute("id", "clBoxOverlay");
olBox.style.width = "100%";
olBox.style.height = "100%";
olBox.style.position = "fixed";
olBox.style.zIndex = o.Zindex;
olBox.style.opacity = o.Opacity;
olBox.style.backgroundColor = o.Background;
olBox.style.top = "0px";
olBox.style.left = "0px";
document.body.appendChild(olBox);
$wrapContent = link.attr("href");
//alert($wrapContent);
if ($wrapContent.indexOf("#") == 0) {
$wrapContainer = $($wrapContent).html();
//alert($wrapContainer);
$oBoxWrapper = $("#clBoxOuterWrapper");
$clBoxOverlay = $("#clBoxOverlay");
$clBoxOverlay.css({
"height": $(document).innerHeight(),
"width": $(document).innerWidth(),
});
if ($oBoxWrapper.length) {
$clBoxWrapper.html($wrapContainer);
if (o.PopUp == "fixed") {
$oBoxWrapper.css({"maxHeight": $(window).height()});
if ($oBoxWrapper.innerHeight() >= $(window).height()) {
$oBoxWrapper.css("overflowY", "scroll");
}
if ($oBoxWrapper.innerWidth() >= $(window).width()) {
$oBoxWrapper.css("overflowX", "scroll");
}
}
$oBoxWrapper.css({
"left": ($(window).width() - $oBoxWrapper.innerWidth()) / 2,
"top": ($(window).height() - $oBoxWrapper.innerHeight()) / 2
});
}
}
event.preventDefault();
// THIS IS THE CALLBACK CALLED AT THE END OF CLICK
if (typeof o.complete == 'function') {
o.complete.call(this); // brings the scope to the callback
}
});
});
}
})(jQuery, window);
You can check it here: http://jsfiddle.net/benjasHu/eyka9z0b/
Is that what you need?
Still very new at Javascript and jQuery, so this one is tough for me.
I'm using this Bootstrap Lightbox plugin: https://github.com/duncanmcdougall/Responsive-Lightbox
Trying to use it on this site (WIP): http://lastdetailwd.com/modernmetalfabricators/furniture.html
I'm looking to use the title attribute from the A tags as captions for this lightbox. Any clue on how to get this done?
jQuery:
(function ($) {
'use strict';
$.fn.lightbox = function (options) {
var opts = {
margin: 50,
nav: true,
blur: true,
minSize: 0
};
var plugin = {
items: [],
lightbox: null,
image: null,
current: null,
locked: false,
selector: "#lightbox",
init: function (items) {
plugin.items = items;
plugin.selector = "lightbox-"+Math.random().toString().replace('.','');
if (!plugin.lightbox) {
$('body').append(
'<div id="lightbox" class='+plugin.selector+' style="display:none;">'+
'' +
'<div class="lightbox-nav">'+
'' +
'' +
'</div>' +
'</div>'
);
plugin.lightbox = $("."+plugin.selector);
}
if (plugin.items.length > 1 && opts.nav) {
$('.lightbox-nav', plugin.lightbox).show();
} else {
$('.lightbox-nav', plugin.lightbox).hide();
}
plugin.bindEvents();
},
loadImage: function () {
if(opts.blur) {
$("body").addClass("blurred");
}
$("img", plugin.lightbox).remove();
plugin.lightbox.fadeIn('fast').append('<span class="lightbox-loading"></span>');
var img = $('<img src="' + $(plugin.current).attr('href') + '" draggable="false">');
$(img).load(function () {
$('.lightbox-loading').remove();
plugin.lightbox.append(img);
plugin.image = $("img", plugin.lightbox).hide();
plugin.resizeImage();
});
},
resizeImage: function () {
var ratio, wHeight, wWidth, iHeight, iWidth;
wHeight = $(window).height() - opts.margin;
wWidth = $(window).outerWidth(true) - opts.margin;
plugin.image.width('').height('');
iHeight = plugin.image.height();
iWidth = plugin.image.width();
if (iWidth > wWidth) {
ratio = wWidth / iWidth;
iWidth = wWidth;
iHeight = Math.round(iHeight * ratio);
}
if (iHeight > wHeight) {
ratio = wHeight / iHeight;
iHeight = wHeight;
iWidth = Math.round(iWidth * ratio);
}
plugin.image.width(iWidth).height(iHeight).css({
'top': ($(window).height() - plugin.image.outerHeight()) / 2 + 'px',
'left': ($(window).width() - plugin.image.outerWidth()) / 2 + 'px'
}).show();
plugin.locked = false;
},
getCurrentIndex: function () {
return $.inArray(plugin.current, plugin.items);
},
next: function () {
if (plugin.locked) {
return false;
}
plugin.locked = true;
if (plugin.getCurrentIndex() >= plugin.items.length - 1) {
$(plugin.items[0]).click();
} else {
$(plugin.items[plugin.getCurrentIndex() + 1]).click();
}
},
previous: function () {
if (plugin.locked) {
return false;
}
plugin.locked = true;
if (plugin.getCurrentIndex() <= 0) {
$(plugin.items[plugin.items.length - 1]).click();
} else {
$(plugin.items[plugin.getCurrentIndex() - 1]).click();
}
},
bindEvents: function () {
$(plugin.items).click(function (e) {
if(!$("#lightbox").is(":visible") && ($(window).width() < opts.minSize || $(window).height() < opts.minSize)) {
$(this).attr("target", "_blank");
return;
}
var self = $(this)[0];
e.preventDefault();
plugin.current = self;
plugin.loadImage();
// Bind Keyboard Shortcuts
$(document).on('keydown', function (e) {
// Close lightbox with ESC
if (e.keyCode === 27) {
plugin.close();
}
// Go to next image pressing the right key
if (e.keyCode === 39) {
plugin.next();
}
// Go to previous image pressing the left key
if (e.keyCode === 37) {
plugin.previous();
}
});
});
// Add click state on overlay background only
plugin.lightbox.on('click', function (e) {
if (this === e.target) {
plugin.close();
}
});
// Previous click
$(plugin.lightbox).on('click', '.lightbox-previous', function () {
plugin.previous();
return false;
});
// Next click
$(plugin.lightbox).on('click', '.lightbox-next', function () {
plugin.next();
return false;
});
// Close click
$(plugin.lightbox).on('click', '.lightbox-close', function () {
plugin.close();
return false;
});
$(window).resize(function () {
if (!plugin.image) {
return;
}
plugin.resizeImage();
});
},
close: function () {
$(document).off('keydown'); // Unbind all key events each time the lightbox is closed
$(plugin.lightbox).fadeOut('fast');
$('body').removeClass('blurred');
}
};
$.extend(opts, options);
plugin.init(this);
};
})(jQuery);
Author did just update it to include captions. Closing this.
I`m having a problem with ie9 not always loading preloaded images.
Sometimes I haft to refresh the page and then it works.
$jQuery.fn.img_preloader = function(options){
var defaults = {
repeatedCheck: 550,
fadeInSpeed: 1100,
delay: 200,
callback: ''
};
var options = jQuery.extend(defaults, options);
return this.each(function(){
var imageContainer = jQuery(this),
images = imageContainer.find('img').css({opacity:0, visibility:'hidden'}),
imagesToLoad = images.length;
imageContainer.operations = {
preload: function(){
var stopPreloading = true;
images.each(function(i, event){
var image = jQuery(this);
if(event.complete == true){
imageContainer.operations.showImage(image);
}else{
image.bind('error load',{currentImage: image}, imageContainer.operations.showImage);
}
});
return this;
},showImage: function(image){
imagesToLoad --;
if(image.data.currentImage != undefined) { image = image.data.currentImage;}
if (options.delay <= 0) image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
if(imagesToLoad == 0){
if(options.delay > 0){
images.each(function(i, event){
var image = jQuery(this);
setTimeout(function(){
image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
},
options.delay*(i+1));
});
if(options.callback != ''){
setTimeout(options.callback, options.delay*images.length);
}
}else if(options.callback != ''){
(options.callback)();
}
}
}
};
imageContainer.operations.preload();
});
}
Try commenting the event.complete validation and going directly to the showImage event. It's not the best solution, but worked for me.
$jQuery.fn.img_preloader = function(options)
{
var defaults = {
repeatedCheck: 550,
fadeInSpeed: 1100,
delay: 200,
callback: ''
};
var options = jQuery.extend(defaults, options);
return this.each(function()
{
var imageContainer = jQuery(this),
images = imageContainer.find('img').css({opacity:0, visibility:'hidden'}),
imagesToLoad = images.length;
imageContainer.operations = {
preload: function(){
var stopPreloading = true;
images.each(function(i, event){
var image = jQuery(this);
imageContainer.operations.showImage(image);
/*if(event.complete == true){
imageContainer.operations.showImage(image);
}else{
image.bind('error load',{currentImage: image}, imageContainer.operations.showImage);
}*/
});
return this;
},showImage: function(image){
imagesToLoad --;
if(image.data.currentImage != undefined) { image = image.data.currentImage;}
if (options.delay <= 0) image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
if(imagesToLoad == 0){
if(options.delay > 0){
images.each(function(i, event){
var image = jQuery(this);
setTimeout(function(){
image.css('visibility','visible').animate({opacity:1}, options.fadeInSpeed);
},
options.delay*(i+1));
});
if(options.callback != ''){
setTimeout(options.callback, options.delay*images.length);
}
}else if(options.callback != ''){
(options.callback)();
}
}
}
};
imageContainer.operations.preload();
});
}
Replace this showimage function..
showImage: function (g) {
d--;
if (g.data.currentImage != undefined) {
g = g.data.currentImage;
}
if (b.delay <= 0) {
g.css("visibility", "visible").animate({
opacity: 1
}, b.fadeInSpeed);
}
if (d != 0) {
if (b.delay != 0) {
e.each(function (k, j) {
var h = a(this);
setTimeout(function () {
h.css("visibility", "visible").animate({
opacity: 1
}, b.fadeInSpeed)
}, b.delay * (k + 1))
});
if (b.callback != "") {
setTimeout(b.callback, b.delay * e.length)
}
} else {
if (b.callback != "") {
b.callback()
}
}
}
}