Reputation: 97
I make a button in HTML, and I want it to call function in javascript:
index.html
<body onLoad="setGameAreaBounds()" onResize="setGameAreaBounds()">
<div id="scoreLabel">Score: 0 </div>
<!--div Group-->
<div>
<p id="pageTitle">Button Chaser</p>
<input type="button" id="startButton" onClick="start()" value="Start"/>
</div>
<!--The following: gameArea and dot is grouped together-->
<div id="gameArea">
<button id="dot" onClick="detectHit()"></button>
</div>
</body>
buttonChaser.js
function detectHit() {
//Increase the var score
}
function setGameAreaBounds() {
//Setting the size of GameBoard/Window
}
function moveDot() {
//randomly move the button(id: dot) within the GameBoard/window
}
function start() {
alert("sometext");
moveDot();
}
The code runs fine if I put moveDot();
function inside setGameAreaBounds();
However, it seems like the button(id: startButton) never connects to function start();
What did I do wrong?
Upvotes: 0
Views: 447
Reputation: 7736
Try moving your functions inside your onLoad function and link them back up to the global scope:
var score = 0;
var aWidth;
var aHeight;
var timer;
var that = this;
function setGameAreaBounds() {
//Setting the size of GameBoard/Window
that.moveDot = function () {
//randomly move the button(id: dot) within the GameBoard/window
}
that.detectHit = function() {
//Increase the var score
}
that.start = _start; // link desired name to reference to existing function
}
function() _start {
alert("sometext");
moveDot();
}
Basically, your html functions are accessing functions defined in the global scope after the dom elements were created. So no reference to the function exists when the dom is created. The setGameAreaBounds function gets called after the dom is ready - onLoad. JavaScript functions each have their own scope so you need to pass this from the parent using an unique reference. Then you can assign the names you want to the functions.
A better approach would be to define all scripts after Many programs use an onReady function that waits until the dom is loaded before defining any javascript functions. This is a good approach.
Upvotes: 1