JQuery Function not be invoked through Javascript in IE7 - javascript

It works perfect in all major browsers, but not in IE7.
The Java script code is:
$(function() {
var $hdVid = jQuery.noConflict();
$hdVid(function() {
$hdVid('.hd-flv-player').hdVideo();
});
});
JQuery is:
(function($) {
// plugin definition
$.fn.hdVideo = function(options) {
// build main options before element iteration
var defaults = {
theme: 'simpledark',
childtheme: ''
};
var options = $.extend(defaults, options);
// iterate and reformat each matched element
return this.each(function() {
var $hdVideo = $(this);
$hdVideo.removeAttr('controls');
//create html structure
//main wrapper
var $video_wrap=$('<div id="hd-player"></div>');
var $video_hd_html_player = $('<div id="hd_html_player"></div>').addClass('hd-video-player').addClass(options.theme).addClass(options.childtheme);
//controls wraper
var $video_controls = $('<div class="hd-video-main-control"></div><div class="hd-video-controls"><div class="hd-video-seek-container"><div class="hd-video-seek"></div></div><div class="hd-video-buffer-container"><div class="hd-video-buffer"></div></div><div class="hd-video-options cf"><a class="hd-video-play" title="Play/Pause"></a><div class="hd-video-timer"><span class="hd-video-timer-curr">00:00</span><span class="hd-video-sep"> / </span><span class="hd-video-timer-tot-time">00:00</span></div><div class="hd-full-screen"><a class="hd-full-screen-button" title="Normal/FullScreen"></a></div><div class="hd-volume-box"><div class="hd-volume-slider-container"><div class="hd-volume-slider"></div></div><a class="hd-volume-button" title="Mute/Unmute"></a><div class="hd-volume-value-slider"></div></div><div class="hd-hd-swipe"><a class="hd-hd-swipe-button" title="High Definition / Low Definition"></a></div><div class="hd-flv-html5-switch"><a title="Switch to Flash"></a></div></div></div>');
$video_wrap.append($video_hd_html_player);
$hdVideo.wrap($video_wrap);
$hdVideo.after($video_controls);
var full_screen = 0;
//get new elements
var $video_container = $hdVideo.parent('.hd-video-player');
var $video_main_control = $('.hd-video-main-control', $video_container);
$video_controls = $('.hd-video-controls', $video_container);
var $hd_play_btn = $('.hd-video-play', $video_container);
var $hd_video_seek = $('.hd-video-seek', $video_container);
var $hd_video_buffer = $('.hd-video-buffer', $video_container);
var $hd_video_timer_curr = $('.hd-video-timer-curr', $video_container);
var $hd_video_timer_tot_time = $('.hd-video-timer-tot-time', $video_container);
var $hd_volume = $('.hd-volume-slider', $video_container);
var $hd_volume_value = $('.hd-volume-value-slider', $video_container);
var $hd_volume_btn = $('.hd-volume-button', $video_container);
var $hd_hd_swipe_btn = $('.hd-hd-swipe-button', $video_container);
var $hd_full_screen_btn = $('.hd-full-screen-button', $video_container);
var $player_change_btn = $('.hd-flv-html5-switch', $video_container);
$video_controls.hide(); // keep the controls hidden
var firstTime=1;
/* Video Elements Fetching */
var videoAttr = {};
videoAttr.poster = $("video").attr("poster");
videoAttr.src = $("source").map(function() {
return $(this).attr("src");
});
videoAttr.quality = $("source").map(function() {
return $(this).attr("data-quality");
});
videoAttr.type = $("source").map(function() {
return $(this).attr("type");
});
videoAttr.codecs = $("source").map(function() {
return $(this).attr("codecs");
});
/* Video Elements Fetching Ends */
/* Poster image into screen image */
var $video_bind_pst = $('<img class="hd-vid-poster-img" src="'+videoAttr.poster+'" data-width="544" data-height="306"><div class="hd-video-main-control"></div>');
//$hdVideo.before($video_bind_pst);
//var
//width: 630px !important; height: 354px !important; top: 0px !important; left: 0px !important; max-width: 630px !important;
/* Poster image into screen image ends*/
/* Play/Pause */
var gPlay = function() {
txt = navigator.platform ;
if(txt =='iPhone'|| txt =='Linux armv7l')
{
window.location.href = videoAttr.src[0];
}
else{
if($hdVideo.attr('paused') == false) {
$hdVideo[0].pause();
$video_main_control.removeClass("hd-video-main-control-none");
}
else {
if(firstTime)
{
$hdVideo.attr('src', vidStatistics.default_vid_src);
firstTime=0;
}
$hdVideo[0].play();
$hdVideo.attr('preload', 'auto');
$video_main_control.addClass("hd-video-main-control-none");
$hdVideo.addClass("video1-visible");
}
}
return false;
};
var hd_autoply =$("video").attr("play_auto");
if(hd_autoply=="autoplay"){
$hdVideo[0].play();
$video_main_control.addClass("hd-video-main-control-none");
$hd_play_btn.addClass('hd-paused-button');
}
$video_main_control.click(gPlay);
$hd_play_btn.click(gPlay);
$hdVideo.click(gPlay);
$hdVideo.bind('play', function() {
$hd_play_btn.addClass('hd-paused-button');
return false;
});
$hdVideo.bind('pause', function() {
$hd_play_btn.removeClass('hd-paused-button');
return false;
});
$hdVideo.bind('ended', function() {
$hd_play_btn.removeClass('hd-paused-button');
$(".hd-video-main-control").removeClass('hd-video-main-control-none');
return false;
});
var gTimeFormat=function(seconds){
var m=Math.floor(seconds/60)<10?"0"+Math.floor(seconds/60):Math.floor(seconds/60);
var s=Math.floor(seconds-(m*60))<10?"0"+Math.floor(seconds-(m*60)):Math.floor(seconds-(m*60));
return m+":"+s;
};
/* Play/Pause */
/* Progressbar Slider */
var seeksliding;
var createSeek = function() {
if($hdVideo.attr('readyState'))
{
$hd_video_timer_tot_time.text(gTimeFormat($hdVideo.attr('duration')));
var video_duration = $hdVideo.attr('duration');
$hd_video_seek.slider({
value: 0,
step: 0.01,
orientation: "horizontal",
range: "min",
max: video_duration,
animate: true,
slide: function(){
seeksliding = true;
},
stop:function(e,ui){
seeksliding = false;
$hdVideo.attr("currentTime",ui.value);
}
});
$video_controls.show();
}
else {
setTimeout(createSeek, 150);
}
return false;
};
createSeek();
var seekUpdate = function() {
var currenttime = $hdVideo.attr('currentTime');
if(!seeksliding)
{
$hd_video_seek.slider('value', currenttime);
$hd_video_timer_curr.text(gTimeFormat(currenttime));
}
return false;
};
$hdVideo.bind('timeupdate', seekUpdate);
/* Progressbar Slider */
/* Buffer Slider */
var buffersliding;
var createBuffer = function() {
if($hdVideo.attr('readyState'))
{
$hd_video_timer_tot_time.text(gTimeFormat($hdVideo.attr('duration')));
var video_duration = $hdVideo.attr('duration');
$hd_video_buffer.slider({
value: 0,
step: 0.01,
orientation: "horizontal",
range: "min",
max: video_duration,
animate: true,
disabled: true,
slide: function(){
buffersliding = true;
},
stop:function(e,ui){
buffersliding = false;
$hdVideo.attr("buffered",ui.value).end(0);
}
});
$video_controls.show();
}
else {
setTimeout(createBuffer, 150);
}
return false;
};
createBuffer();
// var buffertime = $hdVideo.get(0).buffered.end(0);
var buffertime = $hdVideo[0].buffered.end(0);
var currenttime = $hdVideo.attr('currentTime');
if(!buffersliding)
{
if(currenttime>buffertime){
$hd_video_buffer.slider('value', currenttime);
}
else{
$hd_video_buffer.slider('value', buffertime);
}
}
return false;
};
$hdVideo.bind('timeupdate', bufferUpdate);
/* Buffer Slider end*/
/* Volume Control */
var video_volume = 1;
$hd_volume.slider({
value: 0.4,
orientation: "horizontal",
range: "min",
max: 1,
step: 0.05,
animate: true,
slide:function(e,ui){
$hdVideo.attr('muted',false);
video_volume = ui.value;
$hdVideo.attr('volume',ui.value);
$hd_volume_btn.removeClass('hd-volume-mute');
if(ui.value*100 == 0) {
$hd_volume_btn.css('background-position', '-244px -126px');
}
else if(ui.value*100 <= 15) {
$hd_volume_btn.css('background-position', '-244px -96px');
}
else if (ui.value*100 <= 45) {
$hd_volume_btn.css('background-position', '-244px -66px');
}
else if (ui.value*100 <= 85) {
$hd_volume_btn.css('background-position', '-244px -36px');
}
else {
$hd_volume_btn.css('background-position', '-244px -6px');
}
}
});
var muteVolume = function() {
if($hdVideo.attr('muted')==true) {
$hdVideo.attr('muted', false);
$hd_volume.slider('value', video_volume);
$hd_volume_btn.removeClass('hd-volume-mute');
}else{
$hdVideo.attr('muted', true);
$hd_volume.slider('value', '0');
$hd_volume_btn.addClass('hd-volume-mute');
}
return false;
};
/* Volume Control */
/* Full Screen */
var fullScreen = function(){
if(full_screen == 0){
full_screen = 1;
$(".hd-video-player").addClass("fullscreen-video-container");
$(".hd-video-player video.hd-flv-player").addClass("fullscreen-video");
$(".hd-video-main-control").addClass("fullscreen-hd-video-main-control");
$(".hd-video-controls").addClass("fullscreen-control-elements");
}
else
{
full_screen = 0;
$(".hd-video-player").removeClass("fullscreen-video-container");
$(".hd-video-player video.hd-flv-player").removeClass("fullscreen-video");
$(".hd-video-main-control").removeClass("fullscreen-hd-video-main-control");
$(".hd-video-controls").removeClass("fullscreen-control-elements");
}
return false;
};
$('body').keydown(function(e){
if (e.keyCode == 27 && full_screen == 1) {
fullScreen();
}
console.log(e);
return false;
});
/* Full Screen Ends*/
/* Default Video Quality */
var defaultVideoQuality = function(videoAttr){
var vidStatistics = {};
vidStatistics.support_vid_count=0;
var i, isSupp, myVid=document.createElement('video');
for(i=videoAttr.quality.length-1; i>=0; i--)
{
path = videoAttr.src[i];
var path = videoAttr.src[i],
ext = path.substr(path.lastIndexOf('.') + 1);
isSupp = myVid.canPlayType('video/'+ext+';');
if(isSupp=="maybe" || isSupp=="probably" )
{
vidStatistics.default_vid_qty = videoAttr.quality[i];
vidStatistics.default_vid_src = videoAttr.src[i];
vidStatistics.support_vid_count++;
}
}
if(vidStatistics.default_vid_qty == "hd")
$("a.hd-hd-swipe-button").addClass("hd-hd-swipe-button-hd");
else
$("a.hd-hd-swipe-button").removeClass("hd-hd-swipe-button-hd");
return(vidStatistics);
};
/* Default Video Quality Ends*/
/* HD Available Check */
var hdAvailableCheck = function(videoAttr){
var k=0, i, isSupp, sdSupport = 0;
var myVid=document.createElement('video');
for(i=0; i<videoAttr.quality.length; i++)
{
path = videoAttr.src[i];
var path = videoAttr.src[i],
ext = path.substr(path.lastIndexOf('.') + 1);
isSupp = myVid.canPlayType('video/'+ext+';');
if(isSupp=="maybe" || isSupp=="probably" )
{
if(videoAttr.quality[i]=="hd")
k=1;
else
sdSupport=1;
}
}
if (k==0)
$hd_hd_swipe_btn.css('display', 'none');
if (sdSupport==0)
$hd_hd_swipe_btn.css('pointer-events', 'none').css('cursor', 'default');
return false;
}
/* HD Available Check Ends*/
/* Video Quality Check*/
var videoQualityCheck = function(){
var i, $currVid, currQuality;
$currVid = $hdVideo[0].currentSrc;
for(i=0; i<videoAttr.quality.length; i++) //Get current video quality
if($currVid == videoAttr.src[i])
currQuality=videoAttr.quality[i];
if(currQuality == "hd")
$("a.hd-hd-swipe-button").addClass("hd-hd-swipe-button-hd");
else
$("a.hd-hd-swipe-button").removeClass("hd-hd-swipe-button-hd");
return false;
}
/* Video Quality Check Ends*/
/* Quality Swipe */
var playerstage = 0;
var hdswipe = function(){
var currVid, currExt, currVidName, currQuality, i;
if($hdVideo.attr('paused')==false)
playerstage=1;
currVid = $hdVideo[0].currentSrc;
var currVidTime = $hdVideo.attr('currentTime');
currExt = currVid.substr(currVid.lastIndexOf('.') + 1);
for(i=0; i<videoAttr.quality.length; i++) //Get current video quality
if(currVid == videoAttr.src[i])
currQuality=videoAttr.quality[i];
for(i=0; i<videoAttr.quality.length; i++) //Swipe the Video
{
if((currExt==videoAttr.src[i].substr(videoAttr.src[i].lastIndexOf('.') + 1))&&(currQuality!= videoAttr.quality[i]))
{
$hdVideo.attr('src', videoAttr.src[i]);
resumeCurrTime(currVidTime);
gPlay();
createSeek();
createBuffer();
playerstage=0;
break;
}
}
alert(currQuality);
if(currQuality == "sd")
$("a.hd-hd-swipe-button").addClass("hd-hd-swipe-button-hd");
else
$("a.hd-hd-swipe-button").removeClass("hd-hd-swipe-button-hd");
return false;
}
var resumeCurrTime = function(currVidTime) {
if($hdVideo.attr('readyState'))
{
$hdVideo[0].currentTime = currVidTime;
}
else
setTimeout(function() { resumeCurrTime(currVidTime); }, 150);
return false;
}
/* Quality Swipe Ends */
/* HTML5 / FLV Swipe */
var playerChangeIntFn = function(){
if(full_screen==1)
fullScreen();
$hdVideo.attr('preload', 'none');
$hdVideo.load();
var trigger = "flash";
playerChange(trigger);
return false;
};
/* HTML5 / FLV Swipe Ends */
var vidStatistics = {};
vidStatistics = defaultVideoQuality(videoAttr);
hdAvailableCheck(videoAttr);
$hd_hd_swipe_btn.click(hdswipe); //HD On/Off
$hd_volume_btn.click(muteVolume); //Mute Volume
$hd_full_screen_btn.click(fullScreen); //Full Screen On/Off
$video_container.dblclick(fullScreen); //Full Screen On/Off
$player_change_btn.click(playerChangeIntFn); //Full Screen On/Off
});
};
// plugin defaults
$.fn.hdVideo.defaults = {
};
})(jQuery);
HTML is:
<video src="" width="830" height="354" class="hd-flv-player" poster="asserts/poster.png" controls="controls" data-name="demo video" data-uid="57fb2708" preload="none">
<source src="http://video-js.zencoder.com/oceans-clip.mp4" data-quality="hd"></source>
<source src="http://static.clipcanvas.com/sample/clipcanvas_14348_offline.mp4" data-quality="sd"></source>
<source src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" data-quality="hd"></source>
<source src="asserts/300_VP8.webm" data-quality="sd"></source>
</video>
Doctype: <!DOCTYPE html>
Note: I know that IE7 wont support HTML5 Video. But I just want the control code should be binded. So that I can use Flash Fall back.

Reply to your comment
That error is because of ie7 support for "myVid.canPlayType()" in
JQuery
Then that needs to be fixed, no? Even though it looks like a third-party library, you can still fix code in them, and even submit bug fixes to the developer. Maybe they even have a later version of the library out, you could check.
if (myVid.canPlayType)
will check for the existence of the function in the object. If it doesn't exist, like you said it probably doesn't support HTML video. You should then exit the plugin with an error, or have an option in the plugin which content should be used as a fallback.
DEMO

Related

Trying to add ALT tag within popup lightbox Lightbox2 for ADA Compliance Standards

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);

Define ImageSize in div dwtcontrolContainer Dynamic Web TWAIN SDK APIs

How can I adjust the size of scanned image in dwtcontrolContainer div? Because when I scroll down the screen, the selected area never follows the mouse and select an area above the mouse click.
Bellow is my AcquireImage function:
function AcquireImage() {
try {
if (DWObject) {
var _obj = {};
_obj.IfShowUI = false;
_obj.PixelType = 0;
_obj.Resolution = 300;
_obj.IfFeederEnabled = true;
_obj.IfDuplexEnabled = false;
_obj.IfDisableSourceAfterAcquire = true; // Scanner source will be disabled/closed automatically after the scan.
_obj.Brightness = 10000;
_obj.MaxImagesInBuffer = 3;
_obj.PageSize = 0;
_obj.Contrast = 1000;
DWObject.SelectSourceByIndex(document.getElementById("rdlScanner").selectedIndex);
DWObject.OpenSource();
DWObject.AcquireImage(_obj);
DWObject.SetViewMode(-1, -1);
DWObject.CurrentImageIndexInBuffer = 0;
updatePageInfo();
}
}
catch (err) {
alert("Error: " + err.message);
}
}
I found http://developer.dynamsoft.com/dwt/dynamic-web-twain-how-to-resize-the-viewer-automatically but even configure the .js dynamsoft.webtwain.config.js doesn't work
Your link is about how to change the size of the viewer, not the image size. Here I changed your viewer size to 600x800:
function AcquireImage() {
try {
if (DWObject) {
DWObject.Width = 600; // viewer width
DWObject.Height = 800; // viewer height
var _obj = {};
_obj.IfShowUI = false;
_obj.PixelType = 0;
_obj.Resolution = 300;
_obj.IfFeederEnabled = true;
_obj.IfDuplexEnabled = false;
_obj.IfDisableSourceAfterAcquire = true; // Scanner source will be disabled/closed automatically after the scan.
_obj.Brightness = 10000;
_obj.MaxImagesInBuffer = 3;
_obj.PageSize = 0;
_obj.Contrast = 1000;
DWObject.SelectSourceByIndex(document.getElementById("rdlScanner").selectedIndex);
DWObject.OpenSource();
DWObject.AcquireImage(_obj);
DWObject.SetViewMode(-1, -1);
DWObject.CurrentImageIndexInBuffer = 0;
updatePageInfo();
}
}
catch (err) {
alert("Error: " + err.message);
}
}
If you want to change the image size, visit this link: http://developer.dynamsoft.com/dwt/changeimagesize.
I created two buttons to change the image size:
function small() {
var DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
DWObject.ChangeImageSize(0, 300, 400, EnumDWT_InterpolationMethod.IM_NEARESTNEIGHBOUR);
}
function big() {
var DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
DWObject.ChangeImageSize(0, 600, 800, EnumDWT_InterpolationMethod.IM_NEARESTNEIGHBOUR);
}

Phaser game getting slow [closed]

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.

Javascript jQuery plugin - multiple instances, external control

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);
});
});

Make JavaScript/jQuery tabs return to position on mouse out

This post is about the 3 green tabs at the top of the page (link is below). I have almost got these moving tabs how I want them, but I am not able to get the tabs to return to original position on mouse out or on a click elsewhere. Instead they move back to position after a set amount of time. How difficult is it to have them move back on mouse out?
Site is here http://theveganproject.ca/wp/
Thanks!
var sliding = 0;
var slideTime = '';
// Set is sliding value
function setSliding(a_ISliding){
sliding = a_ISliding;
}
// Get is sliding value
function getSliding(){
return sliding;
}
// Carry out accordian styled effect
function accordion(evt) {
el = Event.element(evt);
var eldown = getNextSibling(el);
// If element is visible do nothing
if ($('visible') == el) {
return;
}
if ($('visible')) {
if( getSliding() == 1 ){
return false;
}
var elup = getNextSibling($('visible'));
setSliding( 1 );
parellelSlide( elup, eldown );
$('visible').id = '';
}
else{
setSliding( 1 );
singleSlide( eldown );
}
el.id = 'visible';
}
// Setup accordian initial state
function init() {
var bodyPanels = document.getElementsByClassName('panel_body');
var panels = document.getElementsByClassName('panel');
var noPanels = panels.length;
var percentageWidth = 100 / noPanels;
var position = 0;
// Loop through body panels and panels applying required styles and adding event listeners
for (i = 0; i < bodyPanels.length; i++) {
bodyPanels[i].hide();
panels[i].style.width = percentageWidth + '%';
panels[i].style.position = 'absolute';
panels[i].style.left = position + '%';
Event.observe(panels[i].getElementsByTagName('h3')[0], 'mouseover', accordion, false);
Event.observe(panels[i].getElementsByTagName('h3')[0], 'mousemove', accordion, false);
Event.observe(document.body, 'mousemove', resetIdle, false);
position += percentageWidth;
}
if( $('visible') ){
// Set panel with id of visible to be initial displayed
var vis = $('visible').parentNode.id+'-body';
$(vis).show();
}
setIdle();
}
// Next sibling method to work around firefox issues
function getNextSibling(startBrother){
var endBrother=startBrother.nextSibling;
while(endBrother.nodeType!=1){
endBrother = endBrother.nextSibling;
}
return endBrother;
}
function parellelSlide( elup, eldown ){
new Effect.Parallel(
[
new Effect.SlideUp(elup),
new Effect.SlideDown(eldown)
], {
duration: 0.3,
afterFinish: function() { setSliding( 0 );}
});
}
function singleSlide( eldown ){
new Effect.Parallel(
[
new Effect.SlideDown(eldown)
], {
duration: 0.3,
afterFinish: function() { setSliding( 0 );}
});
}
function resetTabs(){
var resetEl = getNextSibling( $('visible') );
setSliding( 1 );
new Effect.Parallel(
[
new Effect.SlideUp( resetEl )
], {
duration: 0.3,
afterFinish: function() { setSliding( 0 );}
});
$('visible').id = '';
}
function resetIdle(){
if( $('visible') ){
window.clearTimeout( slideTime );
slideTime = window.setTimeout( "resetTabs()", 1000 );
}
}
function setIdle(){
if( $('visible') ){
slideTime = window.setTimeout( "resetTabs()", 1000 );
}
}
Event.observe(window, 'load', init, false);

Categories

Resources