here is my problem :)
i try to add "Apprise-v2" plugin to my website,
i include both files, css and js, this way :
<!--TOP OF MY PAGE-->
<html>
<body>
<link rel="stylesheet" type="text/css" href="css/apprise-v2.css"/>
<!--MY PAGE CONTENTS...-->
...........
<!--BOTTOM OF MY PAGE-->
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/raphael-min.js"></script>
<script src="js/tablesorter/jquery.tablesorter.js"></script>
<script src="js/tablesorter/tables.js"></script>
<script type="text/javascript" src="JS/jquery.fancybox.js"></script>
<script type="text/javascript" src="JS/jquery.fancybox.pack.js"></script>
<script src='js/apprise-v2.js'></script>
<script>Apprise("test");</script>
</body>
</html>
my firebug warns me with this :
TypeError: $Apprise is null
if($Apprise.is(':visible')) {
Thanks for help! :)
EDIT : Here is the apprise-v2.js file contents :
// Global Apprise variables
var $Apprise = null,
$overlay = null,
$body = null,
$window = null,
$cA = null,
AppriseQueue = [];
// Add overlay and set opacity for cross-browser compatibility
$(function() {
$Apprise = $('<div class="apprise">');
$overlay = $('<div class="apprise-overlay">');
$body = $('body');
$window = $(window);
$body.append( $overlay.css('opacity', '.94') ).append($Apprise);
});
function Apprise(text, options) {
// Restrict blank modals
if(text===undefined || !text) {
return false;
}
// Necessary variables
var $me = this,
$_inner = $('<div class="apprise-inner">'),
$_buttons = $('<div class="apprise-buttons">'),
$_input = $('<input type="text">');
// Default settings (edit these to your liking)
var settings = {
animation: 700, // Animation speed
buttons: {
confirm: {
action: function() { $me.dissapear(); }, // Callback function
className: null, // Custom class name(s)
id: 'confirm', // Element ID
text: 'Ok' // Button text
}
},
input: false, // input dialog
override: true // Override browser navigation while Apprise is visible
};
// Merge settings with options
$.extend(settings, options);
// Close current Apprise, exit
if(text=='close') {
$cA.dissapear();
return;
}
// If an Apprise is already open, push it to the queue
if($Apprise.is(':visible')) {
AppriseQueue.push({text: text, options: settings});
return;
}
// Width adjusting function
this.adjustWidth = function() {
var window_width = $window.width(), w = "20%", l = "40%";
if(window_width<=800) {
w = "90%", l = "5%";
} else if(window_width <= 1400 && window_width > 800) {
w = "70%", l = "15%";
} else if(window_width <= 1800 && window_width > 1400) {
w = "50%", l = "25%";
} else if(window_width <= 2200 && window_width > 1800) {
w = "30%", l = "35%";
}
$Apprise.css('width', w).css('left', l);
};
// Close function
this.dissapear = function() {
$Apprise.animate({
top: '-100%'
},
settings.animation, function() {
$overlay.fadeOut(300);
$Apprise.hide();
// Unbind window listeners
$window.unbind("beforeunload");
$window.unbind("keydown");
// If in queue, run it
if(AppriseQueue[0]) {
Apprise(AppriseQueue[0].text, AppriseQueue[0].options);
AppriseQueue.splice(0,1);
}
});
return;
};
// Keypress function
this.keyPress = function() {
$window.bind('keydown', function(e) {
// Close if the ESC key is pressed
if(e.keyCode===27) {
if(settings.buttons.cancel) {
$("#apprise-btn-" + settings.buttons.cancel.id).trigger('click');
} else {
$me.dissapear();
}
} else if(e.keyCode===13) {
if(settings.buttons.confirm) {
$("#apprise-btn-" + settings.buttons.confirm.id).trigger('click');
} else {
$me.dissapear();
}
}
});
};
// Add buttons
$.each(settings.buttons, function(i, button) {
if(button) {
// Create button
var $_button = $('<button id="apprise-btn-' + button.id + '">').append(button.text);
// Add custom class names
if(button.className) {
$_button.addClass(button.className);
}
// Add to buttons
$_buttons.append($_button);
// Callback (or close) function
$_button.on("click", function() {
// Build response object
var response = {
clicked: button, // Pass back the object of the button that was clicked
input: ($_input.val() ? $_input.val() : null) // User inputted text
};
button.action( response );
//$me.dissapear();
});
}
});
// Disabled browser actions while open
if(settings.override) {
$window.bind('beforeunload', function(e){
return "An alert requires attention";
});
}
// Adjust dimensions based on window
$me.adjustWidth();
$window.resize( function() { $me.adjustWidth() } );
// Append elements, show Apprise
$Apprise.html('').append( $_inner.append('<div class="apprise-content">' + text + '</div>') ).append($_buttons);
$cA = this;
if(settings.input) {
$_inner.find('.apprise-content').append( $('<div class="apprise-input">').append( $_input ) );
}
$overlay.fadeIn(300);
$Apprise.show().animate({
top: '20%'
},
settings.animation,
function() {
$me.keyPress();
}
);
// Focus on input
if(settings.input) {
$_input.focus();
}
} // end Apprise();
Make call after page loaded.
$(function() {
Apprise('hi there');
});
I think using Apprise V3 is a better idea.
https://github.com/exis9/Apprise_V3
Related
My script loads data from other html pages when the user activates the mousewheel.
It should work like this. Scroll up, load contact.html into home.html, scroll up again, load legal.html into home.html. But right now it only loads one time because the mouse wheel event listener is only working once.
How do I make my script listen for the mousewheel again after new pages are loaded into home.html?
javascript
$(document).ready(function() {
bind_events();
$(window).resize(function() {
adjust_div_height();
});
adjust_div_height();
});
function bind_events() {
var elem = $('.div-scrollable')[0];
hammertime = new Hammer(elem);
hammertime.get('swipe').set({ direction: Hammer.DIRECTION_VERTICAL
});
hammertime.on("swipeup", function(ev) {
load_page('next');
adjust_div_height();
});
hammertime.on("swipedown", function(ev) {
load_page('previous');
adjust_div_height();
});
addWheelListener(elem, function(e) {
var scrollUp = e.deltaY > 0;
var scrollDown = e.deltaY < 0;
if (scrollUp) {
load_page('next');
} else if (scrollDown) {
load_page('previous');
}
});
}
function load_page(page_to_load) {
// load contact page data
var loadContactPage = $('#loaded_content').load('contact.html #contact');
var loadHomePage = $('#loaded_content').load('home.html #home');
var homeIsCurrentPage = "$('#home').length)";
var contactIsCurrentPage = "$('#contact').length)";
var legalIsCurrentPage = "$('#contact').length)";
if (homeIsCurrentPage) {
var next = loadContactPage;
update_url('contact.html');
console.log('contact page was loaded!');
}
if (contactIsCurrentPage) {
var next = loadLegalPage;
update_url('legal.html');
console.log('legal page was loaded!');
}
if (legalIsCurrentPage) {
var previous = loadContactPage;
update_url('contact.html');
console.log('contact page was loaded!');
}
wheel_listener.js
// creates a global "addWheelListener" method
// example: addWheelListener( elem, function( e ) { console.log(
e.deltaY ); e.preventDefault(); } );
(function(window, document) {
var prefix = "",
_addEventListener, support;
// detect event model
if (window.addEventListener) {
_addEventListener = "addEventListener";
} else {
_addEventListener = "attachEvent";
prefix = "on";
}
// detect available wheel event
support = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
"DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
window.addWheelListener = function(elem, callback, useCapture) {
_addWheelListener(elem, support, callback, useCapture);
// handle MozMousePixelScroll in older Firefox
if (support == "DOMMouseScroll") {
_addWheelListener(elem, "MozMousePixelScroll", callback, useCapture);
}
};
function _addWheelListener(elem, eventName, callback, useCapture) {
elem[_addEventListener](prefix + eventName, support == "wheel" ? callback : function(originalEvent) {
!originalEvent && (originalEvent = window.event);
// create a normalized event object
var event = {
// keep a ref to the original event object
originalEvent: originalEvent,
target: originalEvent.target || originalEvent.srcElement,
type: "wheel",
deltaMode: originalEvent.type == "MozMousePixelScroll" ? 0 : 1,
deltaX: 0,
deltaY: 0,
deltaZ: 0,
preventDefault: function() {
originalEvent.preventDefault ?
originalEvent.preventDefault() :
originalEvent.returnValue = false;
}
};
// calculate deltaY (and deltaX) according to the event
if (support == "mousewheel") {
event.deltaY = -1 / 40 * originalEvent.wheelDelta;
// Webkit also support wheelDeltaX
originalEvent.wheelDeltaX && (event.deltaX = -1 / 40 * originalEvent.wheelDeltaX);
} else {
event.deltaY = originalEvent.deltaY || originalEvent.detail;
}
// it's time to fire the callback
return callback(event);
}, useCapture || false);
}
})(window, document);
I can understand what you tried on your code.
For a quick note, your code is not transparent for me. So, I can't simulate
addWheelListener function is defined but not used. I think you forgot to post it.
adjust_div_height function is used but not defined.
Same as for update_url, loadContactPage and loadLegalPage.
I tried to put as much as I can on Code Snippet as following.
Please check and let me know if you need more help.
Thanks
$(document).ready(function () {
bind_events();
$(window).resize(function () {
adjust_div_height();
});
adjust_div_height();
});
function bind_events() {
var elem = $('.div-scrollable')[0];
hammertime = new Hammer(elem);
hammertime.get('swipe').set({
direction: Hammer.DIRECTION_VERTICAL
});
hammertime.on("swipeup", function (ev) {
load_page('next');
adjust_div_height();
});
hammertime.on("swipedown", function (ev) {
load_page('previous');
adjust_div_height();
});
addWheelListener(elem, function (e) {
var scrollUp = e.deltaY > 0;
var scrollDown = e.deltaY < 0;
if (scrollUp) {
load_page('next');
} else if (scrollDown) {
load_page('previous');
}
});
}
function adjust_div_height() {
console.log('Adjust Div height function should be here.');
}
function addWheelListener(elem, callback) {
elem.addEventListener("wheel", callback);
}
function update_url(url) {
console.log('Update url to <' + url + '>');
}
function load_page(page_to_load) {
console.log('Scrolled to <' + page_to_load + '> page!');
// load contact page data
var loadContactPage = $('#loaded_content').load('contact.html #contact');
var loadHomePage = $('#loaded_content').load('home.html #home');
var homeIsCurrentPage = "$('#home').length)";
var contactIsCurrentPage = "$('#contact').length)";
var legalIsCurrentPage = "$('#contact').length)";
if (homeIsCurrentPage) {
var next = loadContactPage;
update_url('contact.html');
console.log('contact page was loaded!');
}
if (contactIsCurrentPage) {
var next = loadLegalPage;
update_url('legal.html');
console.log('legal page was loaded!');
}
if (legalIsCurrentPage) {
var previous = loadContactPage;
update_url('contact.html');
console.log('contact page was loaded!');
}
}
function loadContactPage() { /* Load Contact Page */ }
function loadLegalPage() { /* Load Legal Page */ }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://hammerjs.github.io/dist/hammer.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script>
</head>
<body>
<div id="home">Home</div>
<div class="div-scrollable" style="height: 200px; background: red;">
This is scrollable Div
</div>
</body>
</html>
When I reload the page with AJAX from my PHP, I can't seem to get my jQuery function that affects each item in the enlarge class.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Gallery</title>
<link rel="stylesheet" href="css/gallery.css"/>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script src="js/enlarge.js"></script>
<script>
function showImage(str) {
if (str.length == 0) {
document.getElementById("image").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("image").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "info.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="side-nav">
<div class="dropdown">
<select id="categories" onchange="showImage(this.value)">
<option value="All_Cat">All</option>
<option value="Inks">Inks</option>
</select>
</div>
<!-- IMAGE CONTAINER -->
<div id="image"></div>
</form>
</body>
</html>
PhP:
<?php
$folder = "";
$array = array();
// get the q parameter from URL
$q = $_REQUEST["q"];
$display_image = "";
//Switch Statement to evaluate $q
switch ($q) {
case "All_Cat":
$folder = './img_gallery/*';
foreach (glob($folder . '*.*') as $filename) {
$array[] = $filename;
}
foreach ($array as $image) {
if ($array === "") {
$display_image = $image;
} else {
$display_image .= " <img height=\"100\" width=\"100\" class=\"enlarge\" src='$image'/>";
}
}
break;
default:
echo "No images";
}
// Output "no suggestion" if no hint was found or output correct values
echo $display_image === "" ? "No images" : $display_image;
JavaScript/JQUERY:
jQuery.noConflict()
jQuery.imageEnlarge = {
dsettings: {
enlargeby: 4.3, //default increase factor of enlarged image
duration: 500, //default duration of animation, in millisec
imgopacity: 0.2 //opacify of original image when enlarged image overlays it
},
zIndexcounter: 100,
refreshoffsets: function ($window, $target, warpshell) {
var $offsets = $target.offset()
var winattrs = {x: $window.scrollLeft(), y: $window.scrollTop(), w: $window.width(), h: $window.height()}
warpshell.attrs.x = $offsets.left //update x position of original image relative to page
warpshell.attrs.y = $offsets.top
warpshell.newattrs.x = winattrs.x + winattrs.w / 2 - warpshell.newattrs.w / 2
warpshell.newattrs.y = winattrs.y + winattrs.h / 2 - warpshell.newattrs.h / 2
if (warpshell.newattrs.x < winattrs.x + 5) { //no space to the left?
warpshell.newattrs.x = winattrs.x + 5
}
else if (warpshell.newattrs.x + warpshell.newattrs.w > winattrs.x + winattrs.w) {//no space to the right?
warpshell.newattrs.x = winattrs.x + 5
}
if (warpshell.newattrs.y < winattrs.y + 5) { //no space at the top?
warpshell.newattrs.y = winattrs.y + 5
}
},
enlarge: function ($, $target, options) {
var setting = {} //create blank object to store combined settings
var setting = jQuery.extend(setting, this.dsettings, options)
var attrs = (options.thumbdimensions) ? {w: options.thumbdimensions[0], h: options.thumbdimensions[1]} : {w: $target.outerWidth(), h: $target.outerHeight()}
var newattrs = {}
newattrs.w = (setting.enlargeto) ? setting.enlargeto : Math.round(attrs.w * setting.enlargeby)
newattrs.h = (setting.enlargeto) ? Math.round(attrs.h * newattrs.w / attrs.w) : Math.round(attrs.h * setting.enlargeby)
$target.css('cursor', jQuery.imageEnlarge.cursorcss)
if ($target.data('imgshell')) {
$target.data('imgshell').$clone.remove()
$target.css({opacity: 1}).unbind('click.enlarge')
}
var $clone = $target.clone().css({position: 'absolute', left: 0, top: 0, visibility: 'hidden', border: '1px solid gray', cursor: 'pointer'}).appendTo(document.body)
$clone.data('$relatedtarget', $target) //save $target image this enlarged image is associated with
$target.data('imgshell', {$clone: $clone, attrs: attrs, newattrs: newattrs})
$target.bind('click.enlarge', function (e) { //action when original image is clicked on
var $this = $(this).css({opacity: setting.imgopacity})
var imageinfo = $this.data('imgshell')
jQuery.imageEnlarge.refreshoffsets($(window), $this, imageinfo) //refresh offset positions of original and warped images
var $clone = imageinfo.$clone
$clone.stop().css({zIndex: ++jQuery.imageEnlarge.zIndexcounter, left: imageinfo.attrs.x, top: imageinfo.attrs.y, width: imageinfo.attrs.w, height: imageinfo.attrs.h, opacity: 0, visibility: 'visible', display: 'block'})
.animate({opacity: 1, left: imageinfo.newattrs.x, top: imageinfo.newattrs.y, width: imageinfo.newattrs.w, height: imageinfo.newattrs.h}, setting.duration,
function () { //callback function after warping is complete
//none added
}) //end animate
}) //end click
$clone.click(function (e) { //action when enlarged image is clicked on
var $this = $(this)
var imageinfo = $this.data('$relatedtarget').data('imgshell')
jQuery.imageEnlarge.refreshoffsets($(window), $this.data('$relatedtarget'), imageinfo) //refresh offset positions of original and warped images
$this.stop().animate({opacity: 0, left: imageinfo.attrs.x, top: imageinfo.attrs.y, width: imageinfo.attrs.w, height: imageinfo.attrs.h}, setting.duration,
function () {
$this.hide()
$this.data('$relatedtarget').css({opacity: 1}) //reveal original image
}) //end animate
}) //end click
}
};
jQuery.fn.imageEnlarge = function (options) {
var $ = jQuery
return this.each(function () { //return jQuery obj
var $imgref = $(this)
if (this.tagName != "IMG")
return true //skip to next matched element
if (parseInt($imgref.css('width')) > 0 && parseInt($imgref.css('height')) > 0 || options.thumbdimensions) { //if image has explicit width/height attrs defined
jQuery.imageEnlarge.enlarge($, $imgref, options)
}
else if (this.complete) { //account for IE not firing image.onload
jQuery.imageEnlarge.enlarge($, $imgref, options)
}
else {
$(this).bind('load', function () {
jQuery.imageEnlarge.enlarge($, $imgref, options)
})
}
})
};
jQuery.fn.applyMagnifier = function (options) { //dynamic version of imageEnlarge() to apply enlarge effect to an image dynamically
var $ = jQuery
return this.each(function () { //return jQuery obj
var $imgref = $(this)
if (this.tagName != "IMG")
return true //skip to next matched element
})
};
//** The following applies the enlarge effect to images with class="enlarge" and optional "data-enlargeby" and "data-enlargeduration" attrs
//** It also looks for links with attr rel="enlarge[targetimageid]" and makes them togglers for that image
jQuery("document").ready(function ($) {
var $targets = $('.enlarge')
$targets.each(function (i) {
var $target = $(this)
var options = {}
if ($target.attr('data-enlargeto'))
options.enlargeto = parseFloat($target.attr('data-enlargeto'))
if ($target.attr('data-enlargeby'))
options.enlargeby = parseFloat($target.attr('data-enlargeby'))
if ($target.attr('data-enlargeduration'))
options.duration = parseInt($target.attr('data-enlargeduration'))
$target.imageEnlarge(options)
})
var $triggers = $('a[rel^="enlarge["]')
$triggers.each(function (i) {
var $trigger = $(this)
var targetid = $trigger.attr('rel').match(/\[.+\]/)[0].replace(/[\[\]']/g, '') //parse 'id' from rel='enlarge[id]'
$trigger.data('enlargeimageid', targetid)
$trigger.click(function (e) {
$('#' + $(this).data('enlargeimageid')).trigger('click.enlarge')
e.preventDefault()
})
})
})
The AJAX call function is within the HTML code that loads the images to the "image" container. I have the PHP respond with "class="enlarge" within the img item, but the query doesn't kick off. I have found out that this is because the jQuery is loading when the site is initially launched and the bindings are lost when AJAX is called.
Can anyone assist me with fixing this so the class="enlarge" feature works again?
EDITED CODE:
function addBehaviour() {
var $targets = $('.enlarge');
$targets.each(function (i) {
var $target = $(this);
var options = {};
if ($target.attr('data-enlargeto'))
options.enlargeto = parseFloat($target.attr('data-enlargeto'));
if ($target.attr('data-enlargeby'))
options.enlargeby = parseFloat($target.attr('data-enlargeby'));
if ($target.attr('data-enlargeduration'))
options.duration = parseInt($target.attr('data-enlargeduration'));
$target.imageEnlarge(options);
});
var $triggers = $('a[rel^="enlarge["]');
$triggers.each(function (i) {
var $trigger = $(this);
var targetid = $trigger.attr('rel').match(/\[.+\]/)[0].replace(/[\[\]']/g, ''); //parse 'id' from rel='enlarge[id]'
$trigger.data('enlargeimageid', targetid);
$trigger.click(function (e) {
$('#' + $(this).data('enlargeimageid')).trigger('click.enlarge');
e.preventDefault();
});
});
}
jQuery("document").ready(function ($) {
addBehaviour();
});
AJAX:
<script>
function showImage(str) {
if (str.length == 0) {
document.getElementById("image").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("image").innerHTML = xmlhttp.responseText;
addBehaviour();
}
}
xmlhttp.open("GET", "info.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
Answer:
Commented out jQuery.noConflict();
I suggest moving the application of behaviour to a seperate function, and using the on() and off() instead of click() like this:
function addBehaviour() {
console.log( 'addBehaviour is called' );
/* (... your other code...)
off() removes the behaviour if present, on() adds it.
This way it does not get applied multiple times: */
$trigger.off('click').on('click', function(e) {
$('#' + $(this).data('enlargeimageid')).trigger('click.enlarge')
e.preventDefault()
});
Call the function 'addBehaviour' on document load:
jQuery("document").ready(function($) {
//....(your other on document ready code)...
console.log( 'document ready' );
addBehaviour();
})
And call 'addBehaviour'every time after the data arrived via your ajax call so it can re-apply the behaviour.
(Assuming this is the part where you load the stuff with ajax)
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("image").innerHTML = xmlhttp.responseText;
// HERE: (after you have manipulated the dom)
addBehaviour();
}
}
You are attaching events to the .enlarge class on the document ready event, but the content that is loaded with AJAX is loaded after that event, so you need to "rerun" the function of the document ready event.
you can do it by putting it in a separate function, and attaching the document ready event and ajax callback events to the same function.
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");
}
}
},
}
)
});
})();
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');
}