function &ID in javascript - javascript

I have a Javascript function to change colors of a svg ellipse object with id="eye"
document.getElementById("eye").onmouseover = function() {
changeColor()
};
function changeColor() {
document.getElementById("eye").style.fill = "red";
}
document.getElementById("eye").onmouseout = function() {
changeColor2()
};
function changeColor2() {
document.getElementById("eye").style.fill = "green";
}
Now there are 2 more svg objects with id="nose" and id="mouth", how can I apply the same change color founction on these 2 objects? Yes I can repeat the founction 2 more times but there must be a better way to do it. Note The 3 objects shouldn't change color at the same time, which means there no need for loop.

you mean like that? :
document.getElementById("eye").onmouseover = function() {
changeColor("eye")
};
document.getElementById("nose").onmouseover = function() {
changeColor("nose")
};
document.getElementById("mouth").onmouseover = function() {
changeColor("mouth")
};
document.getElementById("eye").onmouseout = function() {
changeColor2()
};
document.getElementById("nose").onmouseout = function() {
changeColor2("nose")
};
document.getElementById("mouth").onmouseout = function() {
changeColor2("mouth")
};
function changeColor(element) {
document.getElementById(element).style.fill = "red";
}
function changeColor2(element) {
document.getElementById(element).style.fill = "green";
}

You could add a parameter to your functions:
function changeColor(element, color) {
element.style.backgroundColor = color;
}
document.getElementById("eye").onmouseover = function(){changeColor(this, "red")};
document.getElementById("eye").onmouseout = function(){changeColor(this, "green")};
document.getElementById("nose").onmouseover = function(){changeColor(this, "blue")};
document.getElementById("nose").onmouseout = function(){changeColor(this, "orange")};
UPDATED
Syntax for background colour fixed(instead of .style.fill it is .style.backgroundColor)
See Demo Fiddle
Reducing element look-ups

Try to make a closure like this:
// Caching elements and closures
var eye = document.getElementById("eye"),
nose = document.getElementById("nose"),
mouth = document.getElementById("mouth"),
change_to_green = change_group_color("green"),
change_to_red = change_group_color("red");
eye.onmouseover = change_to_green;
eye.onmouseout = change_to_red;
nose.onmouseover = change_to_green;
eye.onmouseout = change_to_red;
mouth.onmouseover = change_to_green;
mouth.onmouseout = change_to_red;
function change_group_color(color){
var elem_group = [eye, nose, mouth];
return function(){
var i,l;
for(i=0, l=elem_group.length ; i<l ; i++){
elem_group[i].style.fill = color;
}
}
}

this inside the handler will point to the element that you registered the event with
function onMouseOver() {
this.style.fill = "red";
}
function onMouseOut {
this.style.fill = "green";
}
var eye = document.getElementById("eye");
var nose = document.getElementById("nose");
eye.onmouseover = nose.onmouseover = onMouseOver;
eye.onmouseout = nose.onmouseout = onMouseOout;

Related

javascript audio gets lauder each click

I was implementing some audio files today in my Javascript and it works fine. But
I noticed that with each subsequent click the sound gets louder. I alreadio used the "Audio.volume" method but no luck.
My Code:
var AppController = (function () {
var correctItem, secondItem, thirdItem, selectedItems, selectedItemsShuffled;
var rotateImage = function() {
var i = 0;
var randomNumbers = createThreeRandomNumbers();
var interval = window.setInterval(function () {
i++;
document.getElementById("imageToRotate").src= "img/" + items.images[i].imageLink;
if (i === items.images.length -1) {
i = -1;
}
}, 125);
var clearData = function () {
correctItem = "";
secondItem = "";
thirdItem = "";
selectedItems = "";
selectedItemsShuffled = "";
removeNodeChildren("button-1");
removeNodeChildren("button-2");
removeNodeChildren("button-3");
};
var removeNodeChildren = function (obj) {
var myNode = document.getElementById(obj);
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
};
var resetGame = function () {
clearData();
document.getElementById("buttonWrapper").classList.remove("show");
rotateImage();
}
document.getElementById("imageToRotate").addEventListener("click", function (e) {
// select 3 items
correctItem = getSelectedItemDetails(e);
secondItem = getRandomItem(correctItem);
thirdItem = getSecondRandomItem(correctItem, secondItem);
selectedItems = [correctItem, secondItem, thirdItem];
selectedItemsShuffled = shuffleArray(selectedItems);
// create the numbers 1 to 3 randomly
var order = createThreeRandomNumbers();
// remove the rotating effect
clearInterval(interval);
// set the images to the buttons in a random order.
setItemsToButtons(order, selectedItemsShuffled);
//show the buttons
showButtons();
// Create an event which triggers when a button is clicked.
document.getElementById("buttonWrapper").addEventListener("click", function(e) {
var valueOfButtonPressed = e.srcElement.innerText.toLowerCase();
var clickedButton = e.srcElement.id;
if (valueOfButtonPressed === correctItem) {
document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '<span class="icon"><i class="fa fa-check green" aria-hidden="true"></i></span>';
if (!audio) {
var audio = new Audio("audio/correct.mp3");
}
audio.play();
audio.volume = 0.5;
setTimeout(resetGame, 5000);
} else {
document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '<span class="icon"><i class="fa fa-times red" aria-hidden="true"></i></span>';
if (!audio) {
var audio = new Audio("audio/wrong.mp3");
}
audio.play();
audio.volume = 0.5;
setTimeout(resetGame, 5000);
}
});
});
};
// 1: hide the buttons
hidebuttons();
// 2: Replace the title
replaceTitle("Animals");
// 3: set up image rotation until it's clicked.
rotateImage();
})();
Any help will be much appreciated. Cheers!
I'm fairly certain the reason is that you're making a new Audio object with every single click.
Instead of doing this with every click:
var audio = new Audio("audio/correct.mp3");
do a check to see if audio already exists. if it does, then simply do audio.play(). If it does not, THEN you make a new audio object.

rotating SVG rect around its center using vanilla JavaScript

This is not a duplicate of the other question.
I found this talking about rotation about the center using XML, tried to implement the same using vanilla JavaScript like rotate(45, 60, 60) but did not work with me.
The approach worked with me is the one in the snippet below, but found the rect not rotating exactly around its center, and it is moving little bit, the rect should start rotating upon the first click, and should stop at the second click, which is going fine with me.
Any idea, why the item is moving, and how can I fix it.
var NS="http://www.w3.org/2000/svg";
var SVG=function(el){
return document.createElementNS(NS,el);
}
var svg = SVG("svg");
svg.width='100%';
svg.height='100%';
document.body.appendChild(svg);
class myRect {
constructor(x,y,h,w,fill) {
this.SVGObj= SVG('rect'); // document.createElementNS(NS,"rect");
self = this.SVGObj;
self.x.baseVal.value=x;
self.y.baseVal.value=y;
self.width.baseVal.value=w;
self.height.baseVal.value=h;
self.style.fill=fill;
self.onclick="click(evt)";
self.addEventListener("click",this,false);
}
}
Object.defineProperty(myRect.prototype, "node", {
get: function(){ return this.SVGObj;}
});
Object.defineProperty(myRect.prototype, "CenterPoint", {
get: function(){
var self = this.SVGObj;
self.bbox = self.getBoundingClientRect(); // returned only after the item is drawn
self.Pc = {
x: self.bbox.left + self.bbox.width/2,
y: self.bbox.top + self.bbox.height/2
};
return self.Pc;
}
});
myRect.prototype.handleEvent= function(evt){
self = evt.target; // this returns the `rect` element
this.cntr = this.CenterPoint; // backup the origional center point Pc
this.r =5;
switch (evt.type){
case "click":
if (typeof self.moving == 'undefined' || self.moving == false) self.moving = true;
else self.moving = false;
if(self.moving == true){
self.move = setInterval(()=>this.animate(),100);
}
else{
clearInterval(self.move);
}
break;
default:
break;
}
}
myRect.prototype.step = function(x,y) {
return svg.createSVGTransformFromMatrix(svg.createSVGMatrix().translate(x,y));
}
myRect.prototype.rotate = function(r) {
return svg.createSVGTransformFromMatrix(svg.createSVGMatrix().rotate(r));
}
myRect.prototype.animate = function() {
self = this.SVGObj;
self.transform.baseVal.appendItem(this.step(this.cntr.x,this.cntr.y));
self.transform.baseVal.appendItem(this.rotate(this.r));
self.transform.baseVal.appendItem(this.step(-this.cntr.x,-this.cntr.y));
};
for (var i = 0; i < 10; i++) {
var x = Math.random() * 100,
y = Math.random() * 300;
var r= new myRect(x,y,10,10,'#'+Math.round(0xffffff * Math.random()).toString(16));
svg.appendChild(r.node);
}
UPDATE
I found the issue to be calculating the center point of the rect using the self.getBoundingClientRect() there is always 4px extra in each side, which means 8px extra in the width and 8px extra in the height, as well as both x and y are shifted by 4 px, I found this talking about the same, but neither setting self.setAttribute("display", "block"); or self.style.display = "block"; worked with me.
So, now I've one of 2 options, either:
Find a solution of the extra 4px in each side (i.e. 4px shifting of both x and y, and total 8px extra in both width and height),
or calculating the mid-point using:
self.Pc = {
x: self.x.baseVal.value + self.width.baseVal.value/2,
y: self.y.baseVal.value + self.height.baseVal.value/2
};
The second option (the other way of calculating the mid-point worked fine with me, as it is rect but if other shape is used, it is not the same way, I'll look for universal way to find the mid-point whatever the object is, i.e. looking for the first option, which is solving the self.getBoundingClientRect() issue.
Here we go…
FIDDLE
Some code for documentation here:
let SVG = ((root) => {
let ns = root.getAttribute('xmlns');
return {
e (tag) {
return document.createElementNS(ns, tag);
},
add (e) {
return root.appendChild(e)
},
matrix () {
return root.createSVGMatrix();
},
transform () {
return root.createSVGTransformFromMatrix(this.matrix());
}
}
})(document.querySelector('svg.stage'));
class Rectangle {
constructor (x,y,w,h) {
this.node = SVG.add(SVG.e('rect'));
this.node.x.baseVal.value = x;
this.node.y.baseVal.value = y;
this.node.width.baseVal.value = w;
this.node.height.baseVal.value = h;
this.node.transform.baseVal.initialize(SVG.transform());
}
rotate (gamma, x, y) {
let t = this.node.transform.baseVal.getItem(0),
m1 = SVG.matrix().translate(-x, -y),
m2 = SVG.matrix().rotate(gamma),
m3 = SVG.matrix().translate(x, y),
mtr = t.matrix.multiply(m3).multiply(m2).multiply(m1);
this.node.transform.baseVal.getItem(0).setMatrix(mtr);
}
}
Thanks #Philipp,
Solving catching the SVG center can be done, by either of the following ways:
Using .getBoundingClientRect() and adjusting the dimentions considering 4px are extra in each side, so the resulted numbers to be adjusted as:
BoxC = self.getBoundingClientRect();
Pc = {
x: (BoxC.left - 4) + (BoxC.width - 8)/2,
y: (BoxC.top - 4) + (BoxC.height - 8)/2
};
or by:
Catching the .(x/y).baseVal.value as:
Pc = {
x: self.x.baseVal.value + self.width.baseVal.value/2,
y: self.y.baseVal.value + self.height.baseVal.value/2
};
Below a full running code:
let ns="http://www.w3.org/2000/svg";
var root = document.createElementNS(ns, "svg");
root.style.width='100%';
root.style.height='100%';
root.style.backgroundColor = 'green';
document.body.appendChild(root);
//let SVG = function() {}; // let SVG = new Object(); //let SVG = {};
class SVG {};
SVG.matrix = (()=> { return root.createSVGMatrix(); });
SVG.transform = (()=> { return root.createSVGTransformFromMatrix(SVG.matrix()); });
SVG.translate = ((x,y)=> { return SVG.matrix().translate(x,y) });
SVG.rotate = ((r)=> { return SVG.matrix().rotate(r); });
class Rectangle {
constructor (x,y,w,h,fill) {
this.node = document.createElementNS(ns, 'rect');
self = this.node;
self.x.baseVal.value = x;
self.y.baseVal.value = y;
self.width.baseVal.value = w;
self.height.baseVal.value = h;
self.style.fill=fill;
self.transform.baseVal.initialize(SVG.transform()); // to generate transform list
this.transform = self.transform.baseVal.getItem(0), // to be able to read the matrix
this.node.addEventListener("click",this,false);
}
}
Object.defineProperty(Rectangle.prototype, "draw", {
get: function(){ return this.node;}
});
Object.defineProperty(Rectangle.prototype, "CenterPoint", {
get: function(){
var self = this.node;
self.bbox = self.getBoundingClientRect(); // There is 4px shift in each side
self.bboxC = {
x: (self.bbox.left - 4) + (self.bbox.width - 8)/2,
y: (self.bbox.top - 4) + (self.bbox.height - 8)/2
};
// another option is:
self.Pc = {
x: self.x.baseVal.value + self.width.baseVal.value/2,
y: self.y.baseVal.value + self.height.baseVal.value/2
};
return self.bboxC;
// return self.Pc; // will give same output of bboxC
}
});
Rectangle.prototype.animate = function () {
let move01 = SVG.translate(this.CenterPoint.x,this.CenterPoint.y),
move02 = SVG.rotate(10),
move03 = SVG.translate(-this.CenterPoint.x,-this.CenterPoint.y);
movement = this.transform.matrix.multiply(move01).multiply(move02).multiply(move03);
this.transform.setMatrix(movement);
}
Rectangle.prototype.handleEvent= function(evt){
self = evt.target; // this returns the `rect` element
switch (evt.type){
case "click":
if (typeof self.moving == 'undefined' || self.moving == false) self.moving = true;
else self.moving = false;
if(self.moving == true){
self.move = setInterval(()=>this.animate(),100);
}
else{
clearInterval(self.move);
}
break;
default:
break;
}
}
for (var i = 0; i < 10; i++) {
var x = Math.random() * 100,
y = Math.random() * 300;
var r= new Rectangle(x,y,10,10,'#'+Math.round(0xffffff * Math.random()).toString(16));
root.appendChild(r.draw);
}

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

Changes to Javascript created element doesn't reflect to DOM

I have a class, that is supposed to display grey overlay over page and display text and loading gif. Code looks like this:
function LoadingIcon(imgSrc) {
var elem_loader = document.createElement('div'),
elem_messageSpan = document.createElement('span'),
loaderVisible = false;
elem_loader.style.position = 'absolute';
elem_loader.style.left = '0';
elem_loader.style.top = '0';
elem_loader.style.width = '100%';
elem_loader.style.height = '100%';
elem_loader.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
elem_loader.style.textAlign = 'center';
elem_loader.appendChild(elem_messageSpan);
elem_loader.innerHTML += '<br><img src="' + imgSrc + '">';
elem_messageSpan.style.backgroundColor = '#f00';
this.start = function () {
document.body.appendChild(elem_loader);
loaderVisible = true;
};
this.stop = function() {
if (loaderVisible) {
document.body.removeChild(elem_loader);
loaderVisible = false;
}
};
this.setText = function(text) {
elem_messageSpan.innerHTML = text;
};
this.getElems = function() {
return [elem_loader, elem_messageSpan];
};
}
Problem is, when I use setText method, it sets innerHTML of elem_messageSpan, but it doesn't reflect to the span, that was appended to elem_loader. You can use getElems method to find out what both elements contains.
Where is the problem? Because I don't see single reason why this shouldn't work.
EDIT:
I call it like this:
var xml = new CwgParser('cwg.geog.cz/cwg.xml'),
loader = new LoadingIcon('./ajax-loader.gif');
xml.ondataparse = function() {
loader.stop();
document.getElementById('cover').style.display = 'block';
};
loader.setText('Loading CWG list...');
loader.start();
xml.loadXML();
xml.loadXML() is function that usually takes 3 - 8 seconds to execute (based on download speed of client), thats why I'm displaying loading icon.

Using tween on class object, function definiton?

I am trying to do scene effects opening and closing scenes. But something is wrong with my self and this values. It says not defined or not working. How can ı define these functions.
Ways I tried to define
First way:
var tween = createjs.Tween.get(this.scene).to({alpha : 0}, 5000).call(menuOutCompleted(nextScreen,isNextScreenPopUp));
It is throwing "menuOutCompleted is not defined";
Second way:
var tween = createjs.Tween.get(this.scene).to({alpha : 0}, 5000).call(self.menuOutCompleted(nextScreen,isNextScreenPopUp));
It is not throwing any exception but does not do tween. It directly execute menuOutCompleted.
Third way:
var tween = createjs.Tween.get(this.scene).to({alpha : 0}, 5000).call(this.menuOutCompleted(nextScreen,isNextScreenPopUp));
It works like second way.
My js class
function CreditsScreen(SceneContainer)
{
var closePopUp_Button, background;
this.name = "CreditsScreen";
var self = this;
this.scene = new createjs.Container();
this.loadScreen = function()
{
background = new createjs.Shape();
background.graphics.beginBitmapFill(loader.getResult("coronaLogo")).drawRect(0,0,512,512);
background.x = 200;
background.y = 0;
closePopUp_Button = new createjs.Sprite(buttonData, "exitIdle");
closePopUp_Button.framerate = 30;
closePopUp_Button.x = 400;
closePopUp_Button.y = 22;
// play.addEventListener("click", handleClickPlay);
this.scene.alpha = 0;
this.scene.addChild(background);
this.scene.addChild(closePopUp_Button);
}
this.menuIn = function()
{
console.log("menuIn CreditsScreen" );
stage.addChild(this.scene);
//ptoblemetic part with self.menuInCompleted?
var tween = createjs.Tween.get(this.scene).to({y : 0, x : 0, alpha : 1}, 5000).call(self.menuInCompleted);
}
this.menuInCompleted = function()
{
console.log("menuInCompleted CreditsScreen" );
self.addButtonEventListeners();
}
this.menuOut = function(nextScreen,isNextScreenPopUp)
{
console.log("menuOut CreditsScreen" );
self.removeButtonEventListeners();
if(isNextScreenPopUp == true)
{
self.menuOutCompleted(nextScreen,isNextScreenPopUp);
}
else
{
//problematic part with menuInCompleted?
var tweenSplash = createjs.Tween.get(this.scene).to({alpha : 0}, 5000).call(menuOutCompleted(nextScreen,isNextScreenPopUp));
}
}
this.menuOutCompleted = function(nextScreen,isNextScreenPopUp)
{
console.log("menuOutCompleted CreditsScreen" );
if (isNextScreenPopUp)
{
}
else
{
stage.removeChild(this.scene);
this.scene.x = 0;
this.scene.y = 0;
this.scene.alpha = 1;
}
changeMenu(nextScreen, this.name, isNextScreenPopUp, true);
}
Ok. I solved the problem. Itis my call function. I send the parameters like menuoutcompleted(a,b) but in tween structure it must be (menuoutCompleted,[a,b]).
Now, It works :)

Categories

Resources