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?
Related
I am making an app on visual studio 2012. I am navigating from home page to levelOne. On a button click on level one i'm doing some animation,during animation if i get back to home page using windows back button, and then again come back to level one i get the animation running ,i want this animation to get stopped.
This is my first page where the animation will occur:
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/levelOne/levelOne.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function initiazlize(element, options) {
document.getElementById("play").addEventListener("click",function initial(){
roundCount++;
if (flag1 == false) {
//if flag1 is false that means its time for next storyboard
j = 0;
var r3 = Math.random();
if (r3 <= 0.333) {
$(Left).animate({ marginTop: '-=100px' }, 500);
$(Left).animate({ marginTop: '+=100px' }, 500, animateAsync);
//document.getElementById("play").disabled = false;
}
else if (r3 <= 0.666) {
$(midle).animate({ marginTop: '-=100px' }, 500);
$(midle).animate({ marginTop: '+=100px' }, 500, animateAsync);
//document.getElementById("play").disabled = false;
}
else {
$("#bowlThree").animate({ marginTop: '-=100px' }, 500);
$("#bowlThree").animate({ marginTop: '+=100px' }, 500, animateAsync);
//document.getElementById("play").disabled = false;
}
//inside animate Async(), some more animation on capOne,capTwo,capThree and on object, I want to stop animation on these
//There is a counter j, when j reachs 100 animation is stopped
}
});
document.onbeforeunload = function () {
j = 100;
flag1 = true;
$("#capOne").stop(true, false);
$("#capTwo").stop(true, false);
$("#capThree").stop(true, false);
clearTimeout(variableTimer);
window.cancelAnimationFrame(variableTimer);
Debug;
};
},
unload: function () {
// TODO: Respond to navigations away from this page.
$("#capOne").stop();
$("#capOne").css({ "margin-top": "360px", "margin-left": "250px" })
$("#capTwo").css({ "margin-top": "360px", "margin-left": "580px" })
$("#capThree").css({ "margin-top": "360px", "margin-left": "910px" })
////return false;
$("#capOne").fadeOut(100);
WinJS.UI.disableAnimations();
flag1 = true;//if flag1=false then animation is stopped
$("#capOne").stop(true, false);
$("#capTwo").stop(true, false);
$("#capThree").stop(true, false);
clearTimeout(document.variableTimer);
window.cancelAnimationFrame(document.variableTimer);
debugger;
},
updateLayout: function (element, viewState, lastViewState) {
/// <param name="element" domElement="true" />
// TODO: Respond to changes in viewState.
}
});
})();
Here is the navigator.js file
(function () {
"use strict";
var appView = Windows.UI.ViewManagement.ApplicationView;
var nav = WinJS.Navigation;
WinJS.Namespace.define("Application", {
PageControlNavigator: WinJS.Class.define(
// Define the constructor function for the PageControlNavigator.
function PageControlNavigator(element, options) {
this._element = element || document.createElement("div");
this._element.appendChild(this._createPageElement());
this.home = options.home;
this._lastViewstate = appView.value;
nav.onnavigated = this._navigated.bind(this);
window.onresize = this._resized.bind(this);
document.body.onkeyup = this._keyupHandler.bind(this);
document.body.onkeypress = this._keypressHandler.bind(this);
document.body.onmspointerup = this._mspointerupHandler.bind(this);
Application.navigator = this;
}, {
home: "",
/// <field domElement="true" />
_element: null,
_lastNavigationPromise: WinJS.Promise.as(),
_lastViewstate: 0,
// This is the currently loaded Page object.
pageControl: {
get: function () { return this.pageElement && this.pageElement.winControl; }
},
// This is the root element of the current page.
pageElement: {
get: function () { return this._element.firstElementChild; }
},
// Creates a container for a new page to be loaded into.
_createPageElement: function () {
var element = document.createElement("div");
element.style.width = "100%";
element.style.height = "100%";
return element;
},
// Retrieves a list of animation elements for the current page.
// If the page does not define a list, animate the entire page.
_getAnimationElements: function () { //IHDAr
if (this.pageControl && this.pageControl.getAnimationElements) {
return this.pageControl.getAnimationElements();
}
return this.pageElement;
},
// Navigates back whenever the backspace key is pressed and
// not captured by an input field.
_keypressHandler: function (args) {
if (args.key === "Backspace") {
nav.back();
}
},
// Navigates back or forward when alt + left or alt + right
// key combinations are pressed.
_keyupHandler: function (args) {
if ((args.key === "Left" && args.altKey) || (args.key === "BrowserBack")) {
nav.back();
} else if ((args.key === "Right" && args.altKey) || (args.key === "BrowserForward")) {
nav.forward();
}
},
// This function responds to clicks to enable navigation using
// back and forward mouse buttons.
_mspointerupHandler: function (args) {
if (args.button === 3) {
nav.back();
} else if (args.button === 4) {
nav.forward();
}
},
// Responds to navigation by adding new pages to the DOM.
_navigated: function (args) {
var newElement = this._createPageElement();
var parentedComplete;
var parented = new WinJS.Promise(function (c) { parentedComplete = c; });
this._lastNavigationPromise.cancel();
this._lastNavigationPromise = WinJS.Promise.timeout().then(function () {
return WinJS.UI.Pages.render(args.detail.location, newElement,args.detail.state, parented);
}).then(function parentElement(control) {
var oldElement = this.pageElement;
if (oldElement.winControl && oldElement.winControl.unload) {
oldElement.winControl.unload();
}
this._element.appendChild(newElement);
this._element.removeChild(oldElement);
oldElement.innerText = "";
this._updateBackButton();
parentedComplete();
var history = args.detail.state;
WinJS.UI.Animation.enterPage(this._getAnimationElements()).done(
function () {
}
);//IDHAR
}.bind(this));
args.detail.setPromise(this._lastNavigationPromise);//IDHAR BHI
},
// Responds to resize events and call the updateLayout function
// on the currently loaded page.
_resized: function (args) {
if (this.pageControl && this.pageControl.updateLayout) {
this.pageControl.updateLayout.call(this.pageControl, this.pageElement, appView.value, this._lastViewstate);
}
this._lastViewstate = appView.value;
},
// Updates the back button state. Called after navigation has
// completed.
_updateBackButton: function () {
var backButton = this.pageElement.querySelector("header[role=banner] .win-backbutton");
if (backButton) {
backButton.onclick = function () { nav.back(); };
if (nav.canGoBack) {
backButton.removeAttribute("disabled");
} else {
backButton.setAttribute("disabled", "disabled");
}
}
},
}
)
});
})();
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.
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.
For some reason my gallery isn't working on Mobile devices including iPad, works fine on desktop. Instead of allowing a user to click through, all images appear stacked. The link to my site. The code is
located here
// scroll gallery init
function initCarousel() {
var isTouchDevice = /MSIE 10.*Touch/.test(navigator.userAgent) || ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;
jQuery('div.view-gallery').scrollGallery({
mask: 'div.frame',
slider: '>ul',
slides: '>li',
btnPrev: 'a.btn-prev',
btnNext: 'a.btn-next',
pagerLinks: '.pagination li',
circularRotation: false,
autoRotation: false,
switchTime: 3000,
animSpeed: 500,
onInit: function(obj){
obj.resizeFlag = true;
obj.win = jQuery(window);
//obj.win.unbind('resize orientationchange load', obj.onWindowResize);
obj.resizeSlides = function(){
obj.slideOffset = obj.slides.eq(0).outerWidth(true) - obj.slides.eq(0).width();
if(!obj.resizeFlag) obj.slides.css({width: ''});
else obj.slides.css({width: obj.mask.width()/2 - obj.slideOffset});
obj.calculateOffsets();
obj.refreshPosition();
obj.refreshState();
}
if(isTouchDevice){
ResponsiveHelper.addRange({
'..767': {
on: function(){
setTimeout(function(){
obj.resizeFlag = true;
obj.resizeSlides();
obj.win.bind('resize orientationchange load', obj.resizeSlides);
}, 100);
}
},
'768..': {
on: function(){
obj.resizeFlag = false;
obj.win.unbind('resize orientationchange load', obj.resizeSlides);
obj.resizeSlides();
}
}
});
}
}
});
jQuery('.scrollable-gallery').scrollableGallery();
}
/*
* scrollableGallery
*/
;(function($) {
function ScrollableGallery(options) {
this.options = {
scrollableArea: '.frame',
listItems: '.list-items',
btnPrev: '.btn-prev',
btnNext: '.btn-next',
animSpeed: 500
}
$.extend(this.options, options);
this.init();
}
ScrollableGallery.prototype = {
init: function() {
this.findElements()
this.setStructure();
this.addEvents();
},
findElements: function() {
this.holder = $(this.options.holder);
this.scrollableArea = this.holder.find(this.options.scrollableArea);
this.listItems = this.scrollableArea.find(this.options.listItems);
this.items = this.listItems.children();
this.lastItem = this.items.last();
this.btnPrev = this.holder.find(this.options.btnPrev);
this.btnNext = this.holder.find(this.options.btnNext);
this.scrollAPI = new jcf.modules.customscroll({
replaces: this.scrollableArea[0]
});
},
setStructure: function() {
var that = this;
if (that.listItems.css('position') === 'static') {
that.listItems.css('position', 'relative');
}
setTimeout(function() {
that.refreshState();
}, 50);
},
refreshState: function() {
this.listItems.css('width', 32700);
this.listItems.css('width', this.lastItem.position().left + this.lastItem.outerWidth(true) + 1);
this.scrollableArea.add(this.scrollableArea.parent()).css({
width: '',
height: ''
});
this.scrollAPI.refreshState();
},
addEvents: function() {
var that = this;
that.btnPrev.bind('click', function(e) {
e.preventDefault();
that.prevSlide();
});
that.btnNext.bind('click', function(e) {
e.preventDefault();
that.nextSlide();
});
win.bind('resize orientationchange load', function() {
that.refreshState();
});
},
nextSlide: function() {
var that = this;
var curPos = this.scrollableArea.scrollLeft();
var pos;
for (var i = 0; i < that.items.length; i++) {
pos = that.items.eq(i).position().left;
if (pos > curPos) {
that.scrollAnimate(curPos, pos);
break;
}
}
},
prevSlide: function() {
var that = this;
var curPos = this.scrollableArea.scrollLeft();
var pos;
for (var i = that.items.length - 1; i >= 0; i--) {
pos = that.items.eq(i).position().left;
if (pos < curPos) {
that.scrollAnimate(curPos, pos);
break;
}
}
},
scrollAnimate: function(from, to) {
var that = this;
var start = new Date().getTime();
setTimeout(function() {
var now = (new Date().getTime()) - start;
var progress = now / that.options.animSpeed;
var result = (to - from) * progress + from;
that.scrollAPI.hScrollBar.scrollTo(result);
if (progress < 1) {
setTimeout(arguments.callee, 10);
} else {
that.scrollAPI.hScrollBar.scrollTo(to);
}
}, 10);
}
}
var win = $(window);
$.fn.scrollableGallery = function(options) {
return this.each(function() {
if (!$(this).data('ScrollableGallery')) {
$(this).data('ScrollableGallery', new ScrollableGallery($.extend({}, {holder: this}, options)));
}
});
}
}(jQuery));
After looking through your code, there were numerous errors with syntax. I have cleaned them up as best as I could, this should help you out.
http://jsfiddle.net/wvWrY/1/
For example, this area was missing a semicolon (no way to call the findElements function, as JS will simply skip to the next line without a semicolon there.)
init: function() {
this.findElements()
this.setStructure();
this.addEvents();
Run your code through a linter, it will greatly improve your syntax structure and ensure little leave out errors like semicolons and commas and brackets aren't omitted.
EDIT: Ok, having looked at your code it appears this is actually due to the !importants in your allmobile.css file. The width and height are set to max-width: 100% (this breaks it because the way the slider works is to extend the gallery as far off screen as possible) and the height to auto (this breaks it because it allows the images to just keep piling on). Once you remove those for the page, it become much much much better and actually works.
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');
}