I am updating a client's site to include alt tags to bring their site to ADA compliance. I have a few pages that use Lightbox2 from https://lokeshdhakar.com/projects/lightbox2. I added the ALT attribute to my array, but it's not being called in the script, so didn't get added.
<img src="images/slide-show/at-the-beach-boys-th.jpg" alt="Small boys use sand toys on Long Sands Beach." width="256" height="176" />
I have tried to edit the lightbox.js to include the alt tag call, but have not been successful.
Contents of lightbox.js
// -----------------------------------------------------------------------------------
//
// Lightbox v2.03.3
// by Lokesh Dhakar - http://www.huddletogether.com
// 5/21/06
//
// For more information on this script, visit:
// http://huddletogether.com/projects/lightbox2/
//
// Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//
// Credit also due to those who have helped, inspired, and made their code available to the public.
// Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), Thomas Fuchs(mir.aculo.us), and others.
//
//
// -----------------------------------------------------------------------------------
/*
Table of Contents
-----------------
Configuration
Global Variables
Extending Built-in Objects
- Object.extend(Element)
- Array.prototype.removeDuplicates()
- Array.prototype.empty()
Lightbox Class Declaration
- initialize()
- updateImageList()
- start()
- changeImage()
- resizeImageContainer()
- showImage()
- updateDetails()
- updateNav()
- enableKeyboardNav()
- disableKeyboardNav()
- keyboardAction()
- preloadNeighborImages()
- end()
Miscellaneous Functions
- getPageScroll()
- getPageSize()
- getKey()
- listenKey()
- showSelectBoxes()
- hideSelectBoxes()
- showFlash()
- hideFlash()
- pause()
- initLightbox()
Function Calls
- addLoadEvent(initLightbox)
*/
// -----------------------------------------------------------------------------------
//
// Configuration
//
var fileLoadingImage = "../lightbox_assets/images/loading.gif";
var fileBottomNavCloseImage = "../lightbox_assets/images/closelabel.gif";
var overlayOpacity = 0.8; // controls transparency of shadow overlay
var animate = true; // toggles resizing animations
var resizeSpeed = 7; // controls the speed of the image resizing animations (1=slowest and 10=fastest)
var borderSize = 10; //if you adjust the padding in the CSS, you will need to update this variable
// -----------------------------------------------------------------------------------
//
// Global Variables
//
var imageArray = new Array;
var activeImage;
if(animate == true){
overlayDuration = 0.2; // shadow fade in/out duration
if(resizeSpeed > 10){ resizeSpeed = 10;}
if(resizeSpeed < 1){ resizeSpeed = 1;}
resizeDuration = (11 - resizeSpeed) * 0.15;
} else {
overlayDuration = 0;
resizeDuration = 0;
}
// -----------------------------------------------------------------------------------
//
// Additional methods for Element added by SU, Couloir
// - further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
getWidth: function(element) {
element = $(element);
return element.offsetWidth;
},
setWidth: function(element,w) {
element = $(element);
element.style.width = w +"px";
},
setHeight: function(element,h) {
element = $(element);
element.style.height = h +"px";
},
setTop: function(element,t) {
element = $(element);
element.style.top = t +"px";
},
setLeft: function(element,l) {
element = $(element);
element.style.left = l +"px";
},
setSrc: function(element,src) {
element = $(element);
element.src = src;
},
setHref: function(element,href) {
element = $(element);
element.href = href;
},
setInnerHTML: function(element,content) {
element = $(element);
element.innerHTML = content;
}
});
// -----------------------------------------------------------------------------------
//
// Extending built-in Array object
// - array.removeDuplicates()
// - array.empty()
//
Array.prototype.removeDuplicates = function () {
for(i = 0; i < this.length; i++){
for(j = this.length-1; j>i; j--){
if(this[i][0] == this[j][0]){
this.splice(j,1);
}
}
}
}
// -----------------------------------------------------------------------------------
Array.prototype.empty = function () {
for(i = 0; i <= this.length; i++){
this.shift();
}
}
// -----------------------------------------------------------------------------------
//
// Lightbox Class Declaration
// - initialize()
// - start()
// - changeImage()
// - resizeImageContainer()
// - showImage()
// - updateDetails()
// - updateNav()
// - enableKeyboardNav()
// - disableKeyboardNav()
// - keyboardNavAction()
// - preloadNeighborImages()
// - end()
//
// Structuring of code inspired by Scott Upton (http://www.uptonic.com/)
//
var Lightbox = Class.create();
Lightbox.prototype = {
// initialize()
// Constructor runs on completion of the DOM loading. Calls updateImageList and then
// the function inserts html at the bottom of the page which is used to display the shadow
// overlay and the image container.
//
initialize: function() {
this.updateImageList();
// Code inserts html at the bottom of the page that looks similar to this:
//
// <div id="overlay"></div>
// <div id="lightbox">
// <div id="outerImageContainer">
// <div id="imageContainer">
// <img id="lightboxImage" alt="container for enlarged images">
// <div style="" id="hoverNav">
//
//
// </div>
// <div id="loading">
// <a href="#" id="loadingLink">
// <img src="images/loading.gif" alt"Waiting to load">
// </a>
// </div>
// </div>
// </div>
// <div id="imageDataContainer">
// <div id="imageData">
// <div id="imageDetails">
// <span id="caption"></span>
// <span id="numberDisplay"></span>
// </div>
// <div id="bottomNav">
// <a href="#" id="bottomNavClose">
// <img src="../images/close.gif" alt="X graphic to close lightbox">
// </a>
// </div>
// </div>
// </div>
// </div>
var objBody = document.getElementsByTagName("body").item(0);
var objOverlay = document.createElement("div");
objOverlay.setAttribute('id','overlay');
objOverlay.style.display = 'none';
objOverlay.onclick = function() { myLightbox.end(); }
objBody.appendChild(objOverlay);
var objLightbox = document.createElement("div");
objLightbox.setAttribute('id','lightbox');
objLightbox.style.display = 'none';
objLightbox.onclick = function(e) { // close Lightbox is user clicks shadow overlay
if (!e) var e = window.event;
var clickObj = Event.element(e).id;
if ( clickObj == 'lightbox') {
myLightbox.end();
}
};
objBody.appendChild(objLightbox);
var objOuterImageContainer = document.createElement("div");
objOuterImageContainer.setAttribute('id','outerImageContainer');
objLightbox.appendChild(objOuterImageContainer);
// When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
// If animations are turned off, it will be hidden as to prevent a flicker of a
// white 250 by 250 box.
if(animate){
Element.setWidth('outerImageContainer', 250);
Element.setHeight('outerImageContainer', 250);
} else {
Element.setWidth('outerImageContainer', 1);
Element.setHeight('outerImageContainer', 1);
}
var objImageContainer = document.createElement("div");
objImageContainer.setAttribute('id','imageContainer');
objOuterImageContainer.appendChild(objImageContainer);
var objLightboxImage = document.createElement("img");
objLightboxImage.setAttribute('id','lightboxImage');
objImageContainer.appendChild(objLightboxImage);
var objHoverNav = document.createElement("div");
objHoverNav.setAttribute('id','hoverNav');
objImageContainer.appendChild(objHoverNav);
var objPrevLink = document.createElement("a");
objPrevLink.setAttribute('id','prevLink');
objPrevLink.setAttribute('href','#');
objHoverNav.appendChild(objPrevLink);
var objNextLink = document.createElement("a");
objNextLink.setAttribute('id','nextLink');
objNextLink.setAttribute('href','#');
objHoverNav.appendChild(objNextLink);
var objLoading = document.createElement("div");
objLoading.setAttribute('id','loading');
objImageContainer.appendChild(objLoading);
var objLoadingLink = document.createElement("a");
objLoadingLink.setAttribute('id','loadingLink');
objLoadingLink.setAttribute('href','#');
objLoadingLink.onclick = function() { myLightbox.end(); return false; }
objLoading.appendChild(objLoadingLink);
var objLoadingImage = document.createElement("img");
objLoadingImage.setAttribute('src', fileLoadingImage);
objLoadingImage.setAttribute('alt', 'Image Loading icon');
objLoadingLink.appendChild(objLoadingImage);
var objImageDataContainer = document.createElement("div");
objImageDataContainer.setAttribute('id','imageDataContainer');
objLightbox.appendChild(objImageDataContainer);
var objImageData = document.createElement("div");
objImageData.setAttribute('id','imageData');
objImageDataContainer.appendChild(objImageData);
var objImageDetails = document.createElement("div");
objImageDetails.setAttribute('id','imageDetails');
objImageData.appendChild(objImageDetails);
var objCaption = document.createElement("span");
objCaption.setAttribute('id','caption');
objImageDetails.appendChild(objCaption);
var objNumberDisplay = document.createElement("span");
objNumberDisplay.setAttribute('id','numberDisplay');
objImageDetails.appendChild(objNumberDisplay);
var objBottomNav = document.createElement("div");
objBottomNav.setAttribute('id','bottomNav');
objImageData.appendChild(objBottomNav);
var objBottomNavCloseLink = document.createElement("a");
objBottomNavCloseLink.setAttribute('id','bottomNavClose');
objBottomNavCloseLink.setAttribute('href','#');
objBottomNavCloseLink.onclick = function() { myLightbox.end(); return false; }
objBottomNav.appendChild(objBottomNavCloseLink);
var objBottomNavCloseImage = document.createElement("img");
objBottomNavCloseImage.setAttribute('src', fileBottomNavCloseImage);
objBottomNavCloseImage.setAttribute('alt', 'CLOSE X');
objBottomNavCloseLink.appendChild(objBottomNavCloseImage);
},
//
// updateImageList()
// Loops through anchor tags looking for 'lightbox' references and applies onclick
// events to appropriate links. You can rerun after dynamically adding images w/ajax.
//
updateImageList: function() {
if (!document.getElementsByTagName){ return; }
var anchors = document.getElementsByTagName('a');
var areas = document.getElementsByTagName('area');
// loop through all anchor tags
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i];
var relAttribute = String(anchor.getAttribute('rel'));
// use the string.match() method to catch 'lightbox' references in the rel attribute
if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
anchor.onclick = function () {myLightbox.start(this); return false;}
}
}
// loop through all area tags
// todo: combine anchor & area tag loops
for (var i=0; i< areas.length; i++){
var area = areas[i];
var relAttribute = String(area.getAttribute('rel'));
// use the string.match() method to catch 'lightbox' references in the rel attribute
if (area.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
area.onclick = function () {myLightbox.start(this); return false;}
}
}
},
//
// start()
// Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
//
start: function(imageLink) {
hideSelectBoxes();
hideFlash();
// stretch overlay to fill page and fade in
var arrayPageSize = getPageSize();
Element.setWidth('overlay', arrayPageSize[0]);
Element.setHeight('overlay', arrayPageSize[1]);
new Effect.Appear('overlay', { duration: overlayDuration, from: 0.0, to: overlayOpacity });
imageArray = [];
imageNum = 0;
if (!document.getElementsByTagName){ return; }
var anchors = document.getElementsByTagName( imageLink.tagName);
// if image is NOT part of a set..
if((imageLink.getAttribute('rel') == 'lightbox')){
// add single image to imageArray
imageArray.push(new Array(imageLink.getAttribute('href'), imageLink.getAttribute('title')));
} else {
// if image is part of a set..
// loop through anchors, find other images in set, and add them to imageArray
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i];
if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))){
imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title')));
}
}
imageArray.removeDuplicates();
while(imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;}
}
// calculate top and left offset for the lightbox
var arrayPageScroll = getPageScroll();
var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
var lightboxLeft = arrayPageScroll[0];
Element.setTop('lightbox', lightboxTop);
Element.setLeft('lightbox', lightboxLeft);
Element.show('lightbox');
this.changeImage(imageNum);
},
//
// changeImage()
// Hide most elements and preload image in preparation for resizing image container.
//
changeImage: function(imageNum) {
activeImage = imageNum; // update global var
// hide elements during transition
if(animate){ Element.show('loading');}
Element.hide('lightboxImage');
Element.hide('alt');
Element.hide('hoverNav');
Element.hide('prevLink');
Element.hide('nextLink');
Element.hide('imageDataContainer');
Element.hide('numberDisplay');
imgPreloader = new Image();
// once image is preloaded, resize image container
imgPreloader.onload=function(){
Element.setSrc('lightboxImage', imageArray[activeImage][0]);
myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);
imgPreloader.onload=function(){}; // clear onLoad, IE behaves irratically with animated gifs otherwise
}
imgPreloader.src = imageArray[activeImage][0];
},
//
// resizeImageContainer()
//
resizeImageContainer: function( imgWidth, imgHeight) {
// get curren width and height
this.widthCurrent = Element.getWidth('outerImageContainer');
this.heightCurrent = Element.getHeight('outerImageContainer');
// get new width and height
var widthNew = (imgWidth + (borderSize * 2));
var heightNew = (imgHeight + (borderSize * 2));
// scalars based on change from old to new
this.xScale = ( widthNew / this.widthCurrent) * 100;
this.yScale = ( heightNew / this.heightCurrent) * 100;
// calculate size difference between new and old image, and resize if necessary
wDiff = this.widthCurrent - widthNew;
hDiff = this.heightCurrent - heightNew;
if(!( hDiff == 0)){ new Effect.Scale('outerImageContainer', this.yScale, {scaleX: false, duration: resizeDuration, queue: 'front'}); }
if(!( wDiff == 0)){ new Effect.Scale('outerImageContainer', this.xScale, {scaleY: false, delay: resizeDuration, duration: resizeDuration}); }
// if new and old image are same size and no scaling transition is necessary,
// do a quick pause to prevent image flicker.
if((hDiff == 0) && (wDiff == 0)){
if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);}
}
Element.setHeight('prevLink', imgHeight);
Element.setHeight('nextLink', imgHeight);
Element.setWidth( 'imageDataContainer', widthNew);
this.showImage();
},
//
// showImage()
// Display image and begin preloading neighbors.
//
showImage: function(){
Element.hide('loading');
new Effect.Appear('lightboxImage', { duration: resizeDuration, queue: 'end', afterFinish: function(){ myLightbox.updateDetails(); } });
this.preloadNeighborImages();
},
//
// updateDetails()
// Display caption, image number, and bottom nav.
//
updateDetails: function() {
// if caption is not null
if(imageArray[activeImage][1]){
Element.show('caption');
Element.setInnerHTML( 'caption', imageArray[activeImage][1]);
}
// if image is part of set display 'Image x of x'
if(imageArray.length > 1){
Element.show('numberDisplay');
Element.setInnerHTML( 'numberDisplay', "Image " + eval(activeImage + 1) + " of " + imageArray.length);
}
new Effect.Parallel(
[ new Effect.SlideDown( 'imageDataContainer', { sync: true, duration: resizeDuration, from: 0.0, to: 1.0 }),
new Effect.Appear('imageDataContainer', { sync: true, duration: resizeDuration }) ],
{ duration: resizeDuration, afterFinish: function() {
// update overlay size and update nav
var arrayPageSize = getPageSize();
Element.setHeight('overlay', arrayPageSize[1]);
myLightbox.updateNav();
}
}
);
},
//
// updateNav()
// Display appropriate previous and next hover navigation.
//
updateNav: function() {
Element.show('hoverNav');
// if not first image in set, display prev image button
if(activeImage != 0){
Element.show('prevLink');
document.getElementById('prevLink').onclick = function() {
myLightbox.changeImage(activeImage - 1); return false;
}
}
// if not last image in set, display next image button
if(activeImage != (imageArray.length - 1)){
Element.show('nextLink');
document.getElementById('nextLink').onclick = function() {
myLightbox.changeImage(activeImage + 1); return false;
}
}
this.enableKeyboardNav();
},
//
// enableKeyboardNav()
//
enableKeyboardNav: function() {
document.onkeydown = this.keyboardAction;
},
//
// disableKeyboardNav()
//
disableKeyboardNav: function() {
document.onkeydown = '';
},
//
// keyboardAction()
//
keyboardAction: function(e) {
if (e == null) { // ie
keycode = event.keyCode;
escapeKey = 27;
} else { // mozilla
keycode = e.keyCode;
escapeKey = e.DOM_VK_ESCAPE;
}
key = String.fromCharCode(keycode).toLowerCase();
if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){ // close lightbox
myLightbox.end();
} else if((key == 'p') || (keycode == 37)){ // display previous image
if(activeImage != 0){
myLightbox.disableKeyboardNav();
myLightbox.changeImage(activeImage - 1);
}
} else if((key == 'n') || (keycode == 39)){ // display next image
if(activeImage != (imageArray.length - 1)){
myLightbox.disableKeyboardNav();
myLightbox.changeImage(activeImage + 1);
}
}
},
//
// preloadNeighborImages()
// Preload previous and next images.
//
preloadNeighborImages: function(){
if((imageArray.length - 1) > activeImage){
preloadNextImage = new Image();
preloadNextImage.src = imageArray[activeImage + 1][0];
}
if(activeImage > 0){
preloadPrevImage = new Image();
preloadPrevImage.src = imageArray[activeImage - 1][0];
}
},
//
// end()
//
end: function() {
this.disableKeyboardNav();
Element.hide('lightbox');
new Effect.Fade('overlay', { duration: overlayDuration});
showSelectBoxes();
showFlash();
}
}
// -----------------------------------------------------------------------------------
//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
function getPageScroll(){
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
arrayPageScroll = new Array(xScroll,yScroll)
return arrayPageScroll;
}
// -----------------------------------------------------------------------------------
//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
// console.log(self.innerWidth);
// console.log(document.documentElement.clientWidth);
if (self.innerHeight) { // all except Explorer
if(document.documentElement.clientWidth){
windowWidth = document.documentElement.clientWidth;
} else {
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
// console.log("xScroll " + xScroll)
// console.log("windowWidth " + windowWidth)
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = xScroll;
} else {
pageWidth = windowWidth;
}
// console.log("pageWidth " + pageWidth)
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
return arrayPageSize;
}
// -----------------------------------------------------------------------------------
//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
key = String.fromCharCode(keycode).toLowerCase();
if(key == 'x'){
}
}
// -----------------------------------------------------------------------------------
//
// listenKey()
//
function listenKey () { document.onkeypress = getKey; }
// ---------------------------------------------------
function showSelectBoxes(){
var selects = document.getElementsByTagName("select");
for (i = 0; i != selects.length; i++) {
selects[i].style.visibility = "visible";
}
}
// ---------------------------------------------------
function hideSelectBoxes(){
var selects = document.getElementsByTagName("select");
for (i = 0; i != selects.length; i++) {
selects[i].style.visibility = "hidden";
}
}
// ---------------------------------------------------
function showFlash(){
var flashObjects = document.getElementsByTagName("object");
for (i = 0; i < flashObjects.length; i++) {
flashObjects[i].style.visibility = "visible";
}
var flashEmbeds = document.getElementsByTagName("embed");
for (i = 0; i < flashEmbeds.length; i++) {
flashEmbeds[i].style.visibility = "visible";
}
}
// ---------------------------------------------------
function hideFlash(){
var flashObjects = document.getElementsByTagName("object");
for (i = 0; i < flashObjects.length; i++) {
flashObjects[i].style.visibility = "hidden";
}
var flashEmbeds = document.getElementsByTagName("embed");
for (i = 0; i < flashEmbeds.length; i++) {
flashEmbeds[i].style.visibility = "hidden";
}
}
// ---------------------------------------------------
//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Help from Ran Bar-On [ran2103#gmail.com]
//
function pause(ms){
var date = new Date();
curDate = null;
do{var curDate = new Date();}
while( curDate - date < ms);
}
/*
function pause(numberMillis) {
var curently = new Date().getTime() + sender;
while (new Date().getTime();
}
*/
// ---------------------------------------------------
function initLightbox() { myLightbox = new Lightbox(); }
//Event.observe(window, 'load', initLightbox, false);
I've continued to work on this and have a temporary solution until the mainframe of Lightbox2 has a working alt tag on the overlay (tried up to current version 11.1 but they weren't working). I added a setAlt section after line 122
setAlt: function(element,alt) {
element = $(element);
element.alt = alt;
},
and then added the alt call in the image preloader section (around line 440). I tried calling a value for the ALT in this code, but best I could get was 'undefined', so I've set a static value.
imgPreloader = new Image();
// once image is preloaded, resize image container
imgPreloader.onload=function(){
Element.setSrc('lightboxImage', imageArray[activeImage][0]);
Element.setAlt('lightboxImage', 'Caption below');
// Element.setAlt ('lightboxImage', imageArray[activeImage][0].alt);
//which returned alt="undefined". Couldn't figure out setting VAR
myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Fist time i am using phaser.io, i am repeating background and also loading other thing in update function but after few second later my game is slowing time . it look like background is not moving more. Please have a look of my code and help me in for sort out this problem. Or please give any idea to change background repeatedly without changing other thing.
I have some code indentation problem sorry for that but please try to manage and help me.
Game.js
var scoreTxt, score, speed, scoreTextValue, ques_label, ques_label_pizza, scoreTextKey, timerTextValue, timerTextKey, textStyle_Key, textStyle_Value, anscloud, astroid1, astroid2, astroid3, astroid4;
/*var gameType;*/ //Pizza or Noun
var bullets, quesTextValue, ansTextValue, sprite;
var fireRate = 100;
var nextFire = 0;
var xAxis = [];
var yAxis = [];
var tempQues = [];
var tempAns = [];
var result = [];
var answear = [];
var ques = [];
var astroidContains = [];
var astroidContainsText = []; //['right', 'wrong', 'wrong', 'wrong']
var astroid, spaceShip, quesbar, diamond, randomAnsPosition;
var s1Copy;
var cloudContains = []; //['noun', 'pronoun', 'pronoun']
var QbarContainsQue = [];
var ans,rightans;
var isAnswerCorrect = false;
var allowClick = false;
var spaceShipXAxis = 40, loader1Width = 85, loader2Width = 70;
var bar, loader1, loader2, timer, timerSprite, timerSpriteCount = 0;
var timerCounter = 45; //timer counter will be of 45 seconds.
//var timerCounter_ = 100; //timer counter will be of 45 seconds.
var questCounter = 0; //question counter no. of question played.
var maxQuest = 10;//max questions will be displayed is 10.
var diamondTextColor = "#8D4FA8";
var defTextColor = "#5BEFFE";
var ansTextColor = "#9E13DA";
var errTextColor = '#FF0000';
var corrTextColor = '#228B22';
var corr_ans_fst;
var corr_ans_sec;
var fun_bckg, randQues;
var wrong_ans;
var barre1_x = 150;
var barre1_y = 115;
var healthValue = 100;
var x_loader = 180;
var check =0;
var setAns = [];
var setOne = [['12+16=','28'], ['15+11=','26'], ['16+22=','38'], ['13+14=','27'], ['15+24=','39'], ['14+12=','26'], ['10+17=','27'], ['11+11=','22'],
['13+15=','28'], ['12+21=','33'], ['24+13=','37'], ['33+21=','54'], ['40+18=','58'], ['34+31=','65'], ['25+42=','67'], ['22+15=','37'],
['24+12=','36'], ['20+15=','35'], ['25+14=','39'], ['21+21=','42'], ['41+25=','66'], ['53+24=','77'], ['35+31=','66'], ['62+37=','99'],
['54+35=','89']];
var setTwo = [['15+18=','33'], ['17+17=','34'], ['13+19=','32'], ['18+14=','32'], ['15+27=','42'], ['18+17=','35'], ['27+29=','56'], ['23+28=','51'],
['36+37=','73'], ['45+25=','70'], ['46+45=','91'], ['38+57=','95'], ['49+43=','92'], ['37+53=','90'], ['48+33=','81']];
var Game = {
preload : function() {
// Load the needed image for this(play) game screen.
//load the menu screen
this.load.image('menu', './assets/images/menu.png');
// Here we load all the needed resources for the level.
// background image screen
this.load.image('playgame', './assets/images/back.png');
// globe image screen
this.load.image('playgame', './assets/images/back.png');
// win image screen
//this.load.image('win', './assets/images/win.png');
// spaceship image screen
this.load.image('spaceship', './assets/images/spaceship.png');
// Question bar image screen
this.load.image('quesbar', './assets/images/quesbar.png');
// Diamond image screen
this.load.image('diamond', './assets/images/diamond.png');
// Astroid image screen
this.load.image('astroid1', 'assets/images/asteroid1.png');
this.load.image('astroid2', 'assets/images/asteroid2.png');
this.load.image('astroid3', 'assets/images/asteroid3.png');
this.load.image('astroid4', 'assets/images/asteroid4.png');
// Loader image screen
this.load.image('loaderbck', 'assets/images/loaderbck.png');
this.load.image('loader1', 'assets/images/loader1.png');
this.load.image('loader2', 'assets/images/loader2.png');
//Load the bullet
this.load.image('bullet', 'assets/images/bullet.png');
},
create : function() {
// By setting up global variables in the create function, we initialise them on game start.
// We need them to be globally available so that the update function can alter them.
textStyle_Value = { font: "bold 20px Segoe UI", fill: defTextColor, align: "center" };
textStyleAns = { font: "bold 22px 'Comic Sans MS', 'Comic Sans'", fill: ansTextColor, wordWrap: true, wordWrapWidth: 10, align: "center"};
textStyleQues = { font: "bold 20px 'Comic Sans MS', 'Comic Sans'", fill: defTextColor, wordWrap: true, wordWrapWidth: 10, align: "center"};
sprite = game.add.sprite(310, 485, 'spaceship');
sprite.anchor.set(0.5);
// Loading backround image
this.playBackground();
this.playBackground1();
// Additional Sprites, like cloud
this.addSprites();
// Loading spaceship image
//this.spaceship();
// Loading questionbar image
this.questionbar();
// Call fun. for ques
this.comeQus();
// csll fun. for place astroid
// this.astroid();
// call fun. for Ans
this.generateQues();
this.generateAns();
// Loading Diamond image
this.diamond();
// Start timer
this.startTimer();
// Set timer.
this.setTimer();
this.initLoader();
},
update: function() {
// The update function is called constantly at a high rate (somewhere around 60fps),
// updating the game field every time - also destroying previous objects and creating new.
// Our bullet group
//bullets.destroy();
sprite.destroy();
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(200, 'bullet', 100, false);
bullets.setAll('anchor.x',0);
bullets.setAll('anchor.y', 0.9);
bullets.setAll('outOfBoundsKill', true);
bullets.setAll('checkWorldBounds', true);
//Repeating background..
if(playgame != null && playgame.body.y > 600) {
playgame.destroy();
this.playBackground();
}
if(playgame1.body.y > 0) {
playgame1.destroy();
this.playBackground1();
this.initLoader();
}
if(astroid1 != undefined) astroid1.destroy();
if(astroid2 != undefined) astroid2.destroy();
if(astroid3 != undefined) astroid3.destroy();
if(astroid4 != undefined) astroid4.destroy();
this.addSprites();
//timerTextValue.text = "00:" + timerCounter;
this.initLoader();
//destroing old diamond obj and creating new while change background
//diamond.destroy();
this.diamond();
//destroing old questionbar obj and creating new while change background
quesbar.destroy();
this.questionbar();
//Call comeQus, comeAns for show ques and ans at every background change
// quesTextValue.destroy();
if(quesTextValue != undefined) quesTextValue.destroy();
this.comeQus();
//ansTextValue.destroy();
if(ansTextValue != undefined) ansTextValue.destroy();
this.comeAns();
if (game.input.activePointer.isDown) {
this.fire();
}
allowClick = true;
},
playBackground: function() {
// console.log("playBackground called");
playgame = this.add.sprite(0, 0, 'playgame', 5);
playgame.scale.set(1);
playgame.smoothed = false;
anim_playgame = playgame.animations.add('walk');
anim_playgame.play(10, true);
this.physics.enable(playgame, Phaser.Physics.ARCADE);
playgame.body.velocity.y = 50;
},
playBackground1: function() {
//console.log("playBackground1 called");
//Second background..
playgame1 = this.add.sprite(0, -600, 'playgame', 5);
playgame1.scale.set(1);
playgame1.smoothed = false;
anim_playgame1 = playgame1.animations.add('walk');
anim_playgame1.play(10, true);
this.physics.enable(playgame1, Phaser.Physics.ARCADE);
playgame1.body.velocity.y = 50;
},
questionbar: function() {
quesbar = game.add.image(10, 530, 'quesbar');
},
diamond: function() {
diamond = game.add.image(680, 20, 'diamond');
},
addSprites: function() {
// loading answer cloud
astroid1 = this.add.button(30, 90, 'astroid1', this.astroidClicked, this);
astroid2 = this.add.button(220, 30, 'astroid2', this.astroidClicked, this);
astroid3 = this.add.button(400, 40, 'astroid3', this.astroidClicked, this);
astroid4 = this.add.button(600, 90, 'astroid4', this.astroidClicked, this);
},
inCorrectAnswerHit: function(index) {
allowClick = false;
isAnswerCorrect = false;
//this.playFx('wrong_ans');
for(i=0; i<=3; i++) {
if(cloudContains[i] == "right") {
//cloudContainsText[i].fill = corrTextColor;
console.log("right ans hit");
break;
}
}
},
checkAnswer: function(index) {
// If clicked Ans is right so astroid will destroy.
if(astroidContainsText[index] == "wrong") {
//Here collization function will call
isAnswerCorrect = true;
}
// If clicked word is noun (correct answer) and obstacle is redbird or blackbird - the dude will slide.
else {
this.inCorrectAnswerHit(index);
}
},
generateQues: function(){
var que;
// Generating random questions from given list of ques - setOne.
s1Copy = setOne.slice();
//var result = [];
for (var i = 0; i < 3; i++) {result.push(s1Copy.splice(~~(Math.random()*s1Copy.length),1)[0]);}
s1Copy.push(...setTwo);
for (var i = 0; i < 7; i++) {result.push(s1Copy.splice(~~(Math.random()*s1Copy.length),1)[0]);}
result.toString();
for(var i = 0; i < result.length ; i++ ) {
que = result[i];
ques.push(que[0]);
ques.toString();
//console.log(ques);
answear.push(que[1]);
}
},
comeQus: function() {
quesTextValue = this.add.text(50,541, ques[0],textStyleQues);
this.generateQues();
//tempNoun = [];
},
generateAns: function() {
//Generate two digitd rendom no. and create an array of ans setAns[]
// Add digitd in array
for(var i = 0; i < 3 ; i++) {
var digit = Math.floor(Math.random() * 90 + 10);
//console.log(digit);
setAns.push(digit);
astroidContains[i] = "wrong";
}
console.log(astroidContains);
//console.log(answear);
setAns.push(answear[0]);
astroidContains[i] = "right";
console.log(astroidContains);
shuffle(setAns);
randomAnsPosition = [0, 1, 2, 3];
shuffle(randomAnsPosition);
},
comeAns: function() {
// x and y axis param for placing Answers text.
xAxis = [ 85, 255, 453, 675];
yAxis = [130, 48, 60, 120];
// console.log(setAns);
// Set Answers from above array of Ans - setAns.
for (var i = 0; i < setAns.length; i++) {
var ans = setAns[i];
//console.log(ans);
ansTextValue = this.add.text(xAxis[randomAnsPosition[i]], yAxis[randomAnsPosition[i]], ans, textStyleAns);
astroidContainsText[i] = ansTextValue;
//console.log(ansTextValue.text);
}
},
// Observing which cloud is clicked and checking answer accordingly.
astroidClicked: function() {
// alert("HEllo called");
if(!allowClick) {
return;
}
if(astroid1.game.input._x > 85 && astroid1.game.input._x < 130) {
console.log("cloud_1_Clicked, Clicked:" + astroidContains[0]);
this.checkAnswer(0);
}
else if(astroid2.game.input._x > 255 && astroid2.game.input._x < 48) {
//console.log("cloud_2_Clicked, Clicked:" + astroidContains[1]);
this.checkAnswer(1);
}
else if(astroid3.game.input._x > 453 && astroid3.game.input._x < 60) {
//console.log("cloud_3_Clicked, Clicked:" + astroidContains[2]);
this.checkAnswer(2);
}
else if(astroid4.game.input._x > 675 && astroid4.game.input._x < 120) {
//console.log("cloud_3_Clicked, Clicked:" + astroidContains[2]);
this.checkAnswer(3);
}
allowClick = false;
},
startTimer: function() {
// Create our Timer
timer = game.time.create(false);
// Set a TimerEvent to occur after 1 seconds
timer.loop(1000, this.updateCounter, this);
// Set a TimerEvent to occur after 1 seconds
// timer.loop(100, this.timerStripeChange, this);
// Start the timer running - this is important!
// It won't start automatically, allowing you to hook it to button events and the like.
timer.start();
},
gameOver: function() {
//Gameover screen
this.state.start('Game_Over', true, false);
},
initLoader: function() {
//*******Loader
check +=1;
var bmd = this.game.add.bitmapData(185, 30);
bmd.ctx.beginPath();
bmd.ctx.rect(0, 0, 185, 36);
bmd.ctx.fillStyle = '#00685e';
bmd.ctx.fill();
var bglife = this.game.add.sprite(100, 38, bmd);
bglife.anchor.set(0.5);
if(check != 0)
bmd = this.game.add.bitmapData(x_loader-4, 26);
else
bmd = this.game.add.bitmapData(x_loader, 26);
bmd.ctx.beginPath();
bmd.ctx.rect(0, 0, 180, 26);
if(x_loader <= 120 && x_loader > 60) {
bmd.ctx.fillStyle = "#FFFF00";
} else if(x_loader <= 60) {
bmd.ctx.fillStyle = "#EA0B1E";
} else {
bmd.ctx.fillStyle = '#00f910';
}
bmd.ctx.fill();
this.widthLife = new Phaser.Rectangle(0, 0, bmd.width, bmd.height);
this.totalLife = bmd.width;
//x_loader = ;
/*console.log(this.totalLife);
console.log(this.widthLife);*/
this.life = this.game.add.sprite(93 - bglife.width/2 + 10, 38, bmd);
this.life.anchor.y = 0.5;
this.life.cropEnabled = true;
this.life.crop(this.widthLife);
// this.game.time.events.loop(1450, this.cropLife, this);
},
updateCounter: function() {
if(timerCounter <= 0) {
this.gameOver();
return;
}
timerCounter--;
if(this.widthLife.width <= 0){
this.widthLife.width = this.totalLife;
}
else{
//this.game.add.tween(this.widthLife).to( { width: (x_loader - 4) }, 200, Phaser.Easing.Linear.None, true);
//console.log(this.widthLife.width);
this.widthLife.width = x_loader - 4;
x_loader = this.widthLife.width;
}
},
fire: function () {
if (game.time.now > nextFire && bullets.countDead() > 0)
{
nextFire = game.time.now + fireRate;
var bullet = bullets.getFirstDead();
bullet.reset(sprite.x - 80, sprite.y - 80);
game.physics.arcade.moveToPointer(bullet, 300);
}
}
}
/**
* Shuffles array in place.
* #param {Array} a items The array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length; i; i -= 1) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
}
As already noted it is a lot of code.
So far what I can see, is a memory leak in the update() function:
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(200, 'bullet', 100, false);
bullets.setAll('anchor.x',0);
bullets.setAll('anchor.y', 0.9);
bullets.setAll('outOfBoundsKill', true);
bullets.setAll('checkWorldBounds', true);
With that you are constantly creating new bullets. Put that in the create() function and try again.
I am trying to wrap a canvas function in a jquery plugin, so that it can be invoked via multiple instances.
I want to be able to loop through found items and call the plugin like this
http://jsfiddle.net/M99EY/69/
HTML...
<div id="select1" class="foo" data-init="multi">A</div>
<div id="select2" class="foo" data-init="multi">B</div>
<div id="select3" class="foo" data-init="multi">C</div>
<div id="select4" class="foo" data-init="multi">D</div>
JS
...
var complicatedObj = {
init: function(element){
this.el = element;
console.log("init method", this.el);
//start a complicated process
//like rendering a canvas applicaation
this.bindEvent();
this.addRandom(this.el);
},
addRandom: function(el){
$(el).text(Math.random());
},
reInit: function(){
console.log("re-initialize method");
},
bindEvent: function(){
$(this.el).click(function() {
console.log("Letter.", $(this).text());
});
}
}
//An application with complicated functions -- initialize, re-initialize
$.multiInstance = {
id: 'multiInstance',
version: '1.0',
defaults: { // default settings
foo: 'bar'
}
};
(function ($) {
//Attach this new method to jQuery
$.fn.extend({
multiInstance: function (params) {
//Merge default and user parameters
var otherGeneralVars = 'example';
return this.each(function () {
var $this = $(this), opts = $.extend({},$.multiInstance.defaults, params);
switch (params) {
case "init":
complicatedObj.init($this);
break;
case "reInit":
complicatedObj.addRandom($this);
break;
}
//console.log("$this", $this);
console.log("params", params);
//$this.text(opts.foo);
});
}
})
})(jQuery);
/*
$("#select1").multiInstance();
$("#select2").multiInstance({foo:"foobar"})
$("#select3").multiInstance("init");*/
$('[data-init="multi"]').each(function( index ) {
//console.log( index + ": " + $( this ).text());
$(this).multiInstance("init");
});
setTimeout(function(){ $('#select3').multiInstance("reInit"); }, 2000);
but I need to be able to invoke different methods, pass arguments to these methods -- and then when a change has occurred - provide a callback to catch changes to the instance
Is this the correct way of building the plugin... I want to be able to create multiple instances of the app -- but also control it externally - and also pull values out of it for external results.
This is the application I am trying to wrap into its own jquery plugin.
https://jsfiddle.net/7a4738jo/10/
css..
body {
background-color: #CCCCCC;
margin: 0;
padding: 0;
overflow: hidden;
}
canvas{
background: grey;
}
html..
<script type="text/javascript" src="https://code.createjs.com/easeljs-0.6.0.min.js"></script>
<canvas id='canvas1' data-init="canvas360" width="465" height="465"></canvas>
<canvas id='canvas2' data-init="canvas360" width="465" height="465"></canvas>
js...
var stage;
function init(element) {
var canvas = $(element)[0];
if (!canvas || !canvas.getContext) return;
stage = new createjs.Stage(canvas);
stage.enableMouseOver(true);
stage.mouseMoveOutside = true;
createjs.Touch.enable(stage);
var imgList = ["http://jsrun.it/assets/N/b/D/X/NbDXj.jpg",
"http://jsrun.it/assets/f/K/7/y/fK7yE.jpg",
"http://jsrun.it/assets/j/U/q/d/jUqdG.jpg",
"http://jsrun.it/assets/q/o/4/j/qo4jP.jpg",
"http://jsrun.it/assets/i/Q/e/1/iQe1f.jpg",
"http://jsrun.it/assets/5/k/y/R/5kyRi.jpg",
"http://jsrun.it/assets/x/T/I/h/xTIhA.jpg",
"http://jsrun.it/assets/4/X/G/F/4XGFt.jpg",
"http://jsrun.it/assets/6/7/n/r/67nrO.jpg",
"http://jsrun.it/assets/k/i/r/8/kir8T.jpg",
"http://jsrun.it/assets/2/3/F/q/23Fqt.jpg",
"http://jsrun.it/assets/c/l/d/5/cld59.jpg",
"http://jsrun.it/assets/e/J/O/f/eJOf1.jpg",
"http://jsrun.it/assets/o/j/Z/x/ojZx4.jpg",
"http://jsrun.it/assets/w/K/2/m/wK2m3.jpg",
"http://jsrun.it/assets/w/K/2/m/wK2m3.jpg",
"http://jsrun.it/assets/4/b/g/V/4bgVf.jpg",
"http://jsrun.it/assets/4/m/1/8/4m18z.jpg",
"http://jsrun.it/assets/4/w/b/F/4wbFX.jpg",
"http://jsrun.it/assets/4/k/T/G/4kTGQ.jpg",
"http://jsrun.it/assets/s/n/C/r/snCrr.jpg",
"http://jsrun.it/assets/7/f/H/u/7fHuI.jpg",
"http://jsrun.it/assets/v/S/d/F/vSdFm.jpg",
"http://jsrun.it/assets/m/g/c/S/mgcSp.jpg",
"http://jsrun.it/assets/t/L/t/P/tLtPF.jpg",
"http://jsrun.it/assets/j/7/e/H/j7eHx.jpg",
"http://jsrun.it/assets/m/o/8/I/mo8Ij.jpg",
"http://jsrun.it/assets/n/P/7/h/nP7ht.jpg",
"http://jsrun.it/assets/z/f/K/S/zfKSP.jpg",
"http://jsrun.it/assets/2/3/4/U/234U6.jpg",
"http://jsrun.it/assets/d/Z/y/m/dZymk.jpg"];
var images = [], loaded = 0, currentFrame = 0, totalFrames = imgList.length;
var rotate360Interval, start_x;
var bg = new createjs.Shape();
stage.addChild(bg);
var bmp = new createjs.Bitmap();
stage.addChild(bmp);
var myTxt = new createjs.Text("HTC One", '24px Ubuntu', "#ffffff");
myTxt.x = myTxt.y =20;
myTxt.alpha = 0.08;
stage.addChild(myTxt);
function load360Image() {
var img = new Image();
img.src = imgList[loaded];
img.onload = img360Loaded;
images[loaded] = img;
}
function img360Loaded(event) {
loaded++;
bg.graphics.clear()
bg.graphics.beginFill("#222").drawRect(0,0,stage.canvas.width * loaded/totalFrames, stage.canvas.height);
bg.graphics.endFill();
if(loaded==totalFrames) start360();
else load360Image();
}
function start360() {
document.body.style.cursor='none';
// 360 icon
var iconImage = new Image();
iconImage.src = "http://jsrun.it/assets/y/n/D/c/ynDcT.png";
iconImage.onload = iconLoaded;
// update-draw
update360(0);
// first rotation
rotate360Interval = setInterval(function(){ if(currentFrame===totalFrames-1) { clearInterval(rotate360Interval); addNavigation(); } update360(1); }, 25);
}
function iconLoaded(event) {
var iconBmp = new createjs.Bitmap();
iconBmp.image = event.target;
iconBmp.x = 20;
iconBmp.y = canvas.height - iconBmp.image.height - 20;
stage.addChild(iconBmp);
}
function update360(dir) {
currentFrame+=dir;
if(currentFrame<0) currentFrame = totalFrames-1;
else if(currentFrame>totalFrames-1) currentFrame = 0;
bmp.image = images[currentFrame];
}
//-------------------------------
function addNavigation() {
stage.onMouseOver = mouseOver;
stage.onMouseDown = mousePressed;
document.body.style.cursor='auto';
}
function mouseOver(event) {
document.body.style.cursor='pointer';
}
function mousePressed(event) {
start_x = event.rawX;
stage.onMouseMove = mouseMoved;
stage.onMouseUp = mouseUp;
document.body.style.cursor='w-resize';
}
function mouseMoved(event) {
var dx = event.rawX - start_x;
var abs_dx = Math.abs(dx);
if(abs_dx>5) {
update360(dx/abs_dx);
start_x = event.rawX;
}
}
function mouseUp(event) {
stage.onMouseMove = null;
stage.onMouseUp = null;
document.body.style.cursor='pointer';
}
function handleTick() {
stage.update();
}
document.body.style.cursor='progress';
load360Image();
// TICKER
createjs.Ticker.addEventListener("tick", handleTick);
createjs.Ticker.setFPS(60);
createjs.Ticker.useRAF = true;
}
// Init
$(document).ready(function() {
//create multiple instances of canvas
$('[data-init="canvas360"]').each(function(index) {
init(this);
});
});