Function not defined message in JavaScript - javascript

I am building a game in JavaScript along with html5. I want my front page to display a bit of text and then when I press any button suppose if p then the actual game starts.
I have used flag in this case to toggle between two functions one which brings the front page and another which is actually starting the game.
Here's my code:
var flag1 =true;
function init()
{
canvas = document.getElementById('canvas');
region = canvas.getContext('2d');
if(flag1==true)
{
front();
}
else
{
start();
}
}
function front()
{
document.write("press p to play");
document.onkeydown = function(event)
{
var keyCode;
if(event == null)
{
keyCode = window.event.keyCode;
}
else
{
keyCode = event.keyCode;
}
switch(keyCode)
{
case 80:
flag1=false;
init();
break;
default:
break;
}
}
}
function start()
{
*************
*********
*********
}
This code is giving an error in console whenever I press p, i.e.
init() is not defined
Can anyone sort this problem?

Answer: http://jsfiddle.net/morrison/HrRD6/
Notes:
There's no point in finding canvas again if you've already found it. Storing the canvas to lib.canvas and not retrieving it again seems to be what fixed the problem.
Use library-style functions. This helps avoid naming conflicts.
Tidy your code. I use jsfiddle a lot, so I run it through there, or you can try formatjavascript or javascriptbeautifier.

init() runs for me in chrome. Which browser are you using? What scope is the code in?
Also, as far as I know, JavaScript might be misparsed if it is not indented like so:
if (bool) {
// stuff
}
Try running your code through jslint.

Related

Move color of an HTML element to another page

Good evening,
i was working on a part of what i hope will be my future website and i wanted to add a "photograpy" section to it, and here comes the problem.
since the title in the main page constatly changes color, i'd like to grab its current color to transfer it to the title of the other page to play an animation later on.
the problem is that when i press the related button, i am taken to the photograpy page, but the title remains black.
i've tried seraching for help on google but i haven't been able to find much.
here is the JS
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function() {
loaded();
});
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
loaded();
});
}
function loaded() {
document.getElementById("PHtitle").style.color === titlecolor;
}
function script() {
const titlecolor = document.getElementById("title").style.color;
};
document.getElementById('photograpy').onclick = function () {
script();
};
The snippets don't allow for localStorage, so here is just the javascript.
First, I let the variables outside of a function. The titleColor function checks to see if titleColor was saved in localStorage, if not the default color is black.
Then I set the color of the phtitle to the contents of titleColor variable.
In the script function, I set the localStorage variable to the getComputedStyle color of the title.
Then last I use an event listener on the button to run the script for saving the color.
LocalStorage is a way to store data in the user's browser until they close their browser/clear their data etc.. Which will allow it to be usable on different pages then where it was saved.
let titleColor = localStorage.getItem("titleColor") || "#000000";
let PHtitle = document.querySelector("#PHtitle");
let title = document.querySelector("#title");
let btn = document.querySelector("#photography");
if(PHtitle){
PHtitle.style.color = titleColor;
}
function script() {
localStorage.setItem("titleColor", getComputedStyle(title).color)
}
if(btn && title){
btn.addEventListener("click", function() {
script();
})
}

Cannot resume game after pausing

I'm having issues resuming my game after pausing. It seems like the code never reads my else statement but I'm not sure how to fix it.
I've tried to use different keys and even clicking to pause/resume. I've also tried to add a function in both the create function and the update loop but I get the same issue from both.
this.input.keyboard.once('keydown_ESC', function () {
if (game.scene.isActive('default')){
game.scene.pause('default');
} else {
game.scene.resume('default');
}
});
I expect the game to resume after pressing the esc key a second time.
The reason is that the scene becomes inactive altogether, thus no function in it will run. In other words this scene's code dead stops from running. So you need some other part of the game, which will remain active (e.g running) to take over the 'resume' functionality. Without me being an expert in phaser 3. This is a workaround to achieve this by putting this inside your scripts but outside of any scene's class or code. Let's say you define your
var game = new Phaser.Game(config);
inside the script called game.html. So in there and still inside the javascript tag put this:
var global_scene_paused = false;
var global_time_paused = Date.now() - 10000;
function global_pause(scene){
if(Date.now() - global_time_paused > 2000 && game.scene.isActive(scene)){
game.scene.pause(scene);
console.log('--------- global_pause called');
global_time_paused = Date.now();
global_scene_paused = scene;
}
}
// keyCode 80 : P. Will resume by pressing 'P'
document.addEventListener('keydown', function(event) {
if(event.keyCode == 80 && Date.now() - global_time_paused > 2000 && global_scene_paused) {
game.scene.resume(global_scene_paused);
console.log('+++++++++++ RESUME');
global_scene_paused = false;
global_time_paused = Date.now();
}
});
Inside your scene add this call instead of pause:
this.input.keyboard.once('keydown_ESC', function () {
global_pause('default'); //will be unpaused in game.html
});

Issue with variables scope in Js/Jquery

Having issue with - what I supposed to be - basics scope fundamentals.
I am using Javascript with Require JS structure, here are where the issue occurs:
function GameManager() {
//This is the constructor of gamemanager.js file
this.body = $('body');
this.game = $('#game');
}
GameManager.prototype.createGame = function() {
//Code
//this line works
this.body.append(//Some HTML);
}
GameManager.prototype.showGame = function() {
//Code
//this line does not work wtf
this.game.removeClass("display-none");
//and this one does work.
$("#game").removeClass("display-none");
}
I am using this.body succefully so I want to use the same way for this.game but it doesnt work. I can manage to make it work by using directly $("#game") but it's making jquery running through the DOM everytime so not really optimized...
I certainly am missing some basics points here, can someone explain ?
Thanks
This is working for me. I can remove display-none class from div without a problem. It wont display however. You need to change css. this.body.css("display","block"); for example.
window.onload = function() {
function GameManager() {
//This is the constructor of gamemanager.js file
this.body = $('body');
this.game = $('#game');
}
GameManager.prototype.createGame = function() {
//Code
//this line works
this.body.append();
}
GameManager.prototype.showGame = function() {
//Code
this.body.css("display", "block");
//this line does not work wtf
this.game.removeClass("display-none");
//and this one does work.
//$("#game").removeClass("display-none");
}
var myGame = new GameManager();
myGame.showGame();
}

How to stop a requestAnimationFrame recursion/loop?

I'm using Three.js with the WebGL renderer to make a game which fullscreens when a play link is clicked. For animation, I use requestAnimationFrame.
I initiate it like this:
self.animate = function()
{
self.camera.lookAt(self.scene.position);
self.renderer.render(self.scene, self.camera);
if (self.willAnimate)
window.requestAnimationFrame(self.animate, self.renderer.domElement);
}
self.startAnimating = function()
{
self.willAnimate = true;
self.animate();
}
self.stopAnimating = function()
{
self.willAnimate = false;
}
When I want to, I call the startAnimating method, and yes, it does work as intended. But, when I call the stopAnimating function, things break! There are no reported errors, though...
The setup is basically like this:
There is a play link on the page
Once the user clicks the link, a renderer's domElement should fullscreen, and it does
The startAnimating method is called and the renderer starts rendering stuff
Once escape is clicked, I register an fullscreenchange event and execute the stopAnimating method
The page tries to exit fullscreen, it does, but the entire document is completely blank
I'm pretty sure my other code is OK, and that I'm somehow stopping requestAnimationFrame in a wrong way. My explanation probably sucked, so I uploaded the code to my website, you can see it happening here: http://banehq.com/Placeholdername/main.html.
Here is the version where I don't try to call the animation methods, and fullscreening in and out works: http://banehq.com/Correct/Placeholdername/main.html.
Once play is clicked the first time, the game initializes and it's start method is executed. Once the fullscreen exits, the game's stop method is executed. Every other time that play has been clicked, the game only executes it's start method, because there is no need for it to be initialized again.
Here's how it looks:
var playLinkHasBeenClicked = function()
{
if (!started)
{
started = true;
game = new Game(container); //"container" is an empty div
}
game.start();
}
And here's how the start and stop methods look like:
self.start = function()
{
self.container.appendChild(game.renderer.domElement); //Add the renderer's domElement to an empty div
THREEx.FullScreen.request(self.container); //Request fullscreen on the div
self.renderer.setSize(screen.width, screen.height); //Adjust screensize
self.startAnimating();
}
self.stop = function()
{
self.container.removeChild(game.renderer.domElement); //Remove the renderer from the div
self.renderer.setSize(0, 0); //I guess this isn't needed, but welp
self.stopAnimating();
}
The only difference between this and the working version is that startAnimating and stopAnimating method calls in start and stop methods are commented out.
One way to start/stop is like this
var requestId;
function loop(time) {
requestId = undefined;
...
// do stuff
...
start();
}
function start() {
if (!requestId) {
requestId = window.requestAnimationFrame(loop);
}
}
function stop() {
if (requestId) {
window.cancelAnimationFrame(requestId);
requestId = undefined;
}
}
Working example:
const timeElem = document.querySelector("#time");
var requestId;
function loop(time) {
requestId = undefined;
doStuff(time)
start();
}
function start() {
if (!requestId) {
requestId = window.requestAnimationFrame(loop);
}
}
function stop() {
if (requestId) {
window.cancelAnimationFrame(requestId);
requestId = undefined;
}
}
function doStuff(time) {
timeElem.textContent = (time * 0.001).toFixed(2);
}
document.querySelector("#start").addEventListener('click', function() {
start();
});
document.querySelector("#stop").addEventListener('click', function() {
stop();
});
<button id="start">start</button>
<button id="stop">stop</button>
<div id="time"></div>
Stopping is as simple as not calling requestAnimationFrame anymore, and restarting is to call it it again.
ex)
var pause = false;
function loop(){
//... your stuff;
if(pause) return;
window.requestionAnimationFrame(loop);
}
loop(); //to start it off
pause = true; //to stop it
loop(); //to restart it
var myAnim //your requestId
function anim()
{
//bla bla bla
//it's important to update the requestId each time you're calling reuestAnimationFrame
myAnim=requestAnimationFrame(anim)
}
Let's start it
myAnim=requestAnimationFrame(anim)
Let's stop it
//the cancelation uses the last requestId
cancelAnimationFrame(myAnim)
Reference
I played around with the tutorial of a 2D Breakout Game where they also used requestAnimationFrame and I stopped it with a simple return. The return statement ends function execution if the value of return is omitted.
if(!lives) {
alert("GAME OVER");
return;
}
// looping the draw()
requestAnimationFrame(draw);
I would suggest having a look at the requestAnimationFrame polyfill gibhub page. There are discussions about how this is implemented.
So, after doing some more testing, I've found out that it was, indeed, my other code that posed a problem, not the animation stopping (it was a simple recursion after all). The problem was in dynamically adding and removing the renderer's domElement from the page. After I've stopped doing that, for there was really no reason to do so, and included it once where the initialization was happening, everything started working fine.

Script just stops

I have a JavaScript script that will hopefully have multiple divs fade in/out every couple of seconds. Only one will be visible at once. I've created the following to do the job:
var tmnlSpDelay = 5000;
var $currentVis = null;
tmnlFadeIn = function ($re) {
$re.css("display", "inline");
$re.fadeIn('slow', "");
$currentVis = $re;
setTimeout("tmnlSpinner();", tmnlSpDelay);
}
tmnlSpinner = function () {
var $random_elem = $('.topcontent').eq(Math.floor(Math.random() * $('.topcontent').length));
if ($currentVis != null) {
$currentVis.fadeOut('slow', "function() { tmnlFadeIn($random_elem) }");
} else {
tmnlFadeIn($random_elem);
}
}
$(document).ready(function () {
tmnlSpinner();
});
As you can see, I'm utilizing jQuery as well to help me. The problem is after it has ran once and runs tmnlSpinner again (except, because it has already run once, currentVis is no longer null). When it runs the fadeOut on $currentVis, it just stops working. Google Chrome isn't giving me any feedback on any kind of error. Does anybody see any issues?
Remove the quotes around "function() { tmnlFadeIn($random_elem) }". You're passing a string where you should pass a callback.

Categories

Resources