I'm making a tic-tac-toe game in javascript and i'm currently trying to get my x's and o's appear when I click on the spaces (divs). I have my system so that my ticTacToe() object "game" can update through it's object prototype.
The problem is since I use a for loop to attach click event handlers to all the divs with the "space" class, I can't access the properties of the "game" object at that scope. If I use "this" i'd be referring to the div itself. I've tried making a prototype function and a constructor function to update the "currentPlayer", "board" and "turn" properties of the game object but I can't manage to get the browser to recognize that the properties are in the game object.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="js/script2.js"></script>
</head>
<body>
<div id="gameBoard">
<h1 id="msg">Welcome to Tic-Tac-Toe</h1>
<div id="tl" class="space"></div>
<div id="tm" class="space"></div>
<div id="tr" class="space"></div>
<div id="ml" class="space"></div>
<div id="mm" class="space"></div>
<div id="mr" class="space"></div>
<div id="bl" class="space"></div>
<div id="bm" class="space"></div>
<div id="br" class="space"></div>
</div>
</body>
</html>
JS
function ticTacToe() {
this.board = [[0,0,0]
[0,0,0]
[0,0,0]];
this.turn = 0;
this.currentPlayer = 1;
}
ticTacToe.prototype = {
status: function(){
console.log("The number of turns played is " + this.turn +
" and it is player " + this.currentPlayer + "'s turn.");
},
attachClicks: function(){
var spaces = document.getElementsByClassName("space"),
player = this.currentPlayer;
for(var i = 0; i<spaces.length; i++){
spaces[i].addEventListener('click',function(){
if(player == 1){
this.style.backgroundImage = "url('x.png')";
//Update ticTacToe's turn, player, and board
}
else {
this.style.backgroundImage = "url('o.png')";
//Update ticTacToe's turn, player, and board
}
})
}
}
}
var game = new ticTacToe();
window.onload = function(){
game.attachClicks();
}
Bind another variable to this:
attachClicks: function(){
var game = this;
var spaces = document.getElementsByClassName("space")
for(var i = 0; i<spaces.length; i++){
spaces[i].addEventListener('click',function(){
if(player == 1){
this.style.backgroundImage = "url('x.png')";
//Update ticTacToe's turn, player, and board
}
else {
this.style.backgroundImage = "url('o.png')";
//Update ticTacToe's turn, player, and board
}
})
}
Then you can refer to game.board and game.currentPlayer in the event listener function to access the current tictactoe object.
Related
I'm working on javascript a bit and have had some problems I do not understand how to solve. In my HTML code, I only have a id="felt" but as soon as I open the page in my browser, it creates two pieces of id="felt" (please see attached image for more understanding: https://imgur.com/7ACU7vt) It seems Do not be wrong with the writing of the html code, there is something that makes id="felt" created twice in the browser and I can't understand why. The second id="felt" is working but the first one is not working.
codepen: https://codepen.io/tommattias/pen/yjYoEQ
Thanks for your help!!
HTML
<html>
<head>
<title>JavaScript Card Game | The Art of Web</title>
<link rel="stylesheet" type="text/css" href="css-animation.css">
</head>
<body>
<div id="stage">
<div id="felt">
<div id="card_0"><img onclick="cardClick(0);" src="back.png"></div>
<div id="card_1"><img onclick="cardClick(1);" src="back.png"></div>
<div id="card_2"><img onclick="cardClick(2);" src="back.png"></div>
<div id="card_3"><img onclick="cardClick(3);" src="back.png"></div>
<div id="card_4"><img onclick="cardClick(4);" src="back.png"></div>
<div id="card_5"><img onclick="cardClick(5);" src="back.png"></div>
<div id="card_6"><img onclick="cardClick(6);" src="back.png"></div>
<div id="card_7"><img onclick="cardClick(7);" src="back.png"></div>
<div id="card_8"><img onclick="cardClick(8);" src="back.png"></div>
<div id="card_9"><img onclick="cardClick(9);" src="back.png"></div>
<div id="card_10"><img onclick="cardClick(10);" src="back.png"></div>
<div id="card_11"><img onclick="cardClick(11);" src="back.png"></div>
<div id="card_12"><img onclick="cardClick(12);" src="back.png"></div>
<div id="card_13"><img onclick="cardClick(13);" src="back.png"></div>
<div id="card_14"><img onclick="cardClick(14);" src="back.png"></div>
<div id="card_15"><img onclick="cardClick(15);" src="back.png"></div>
</div>
</div>
<script type="text/javascript" src="css-animation2.js"></script>
<script type="text/javascript">
var game = new CardGame("stage");
</script>
</body>
</html>
Javascript:
var CardGame = function(targetId)
{
var cards = []
var card_value =
["1C","2C","3C","4C","5C","6C","7C","8C","1H","2H","3H","4H","5H","6H","7H","8H"];
var started = false;
var matches_found = 0;
var card1 = false, card2 = false;
var moveToPlace = function(id) // deal card
{
cards[id].matched = false;
with(cards[id].style) {
zIndex = "1000";
top = cards[id].fromtop + "px";
left = cards[id].fromleft + "px";
WebkitTransform = MozTransform = OTransform = msTransform =
"rotate(60deg)";
zIndex = "0";
}
};
var cardClick = function(id)
{
if(started)
{
showCard(id);
}
else {
// shuffle and deal cards
card_value.sort(function() { return Math.round(Math.random()) - 0.5;
});
for(i=0; i < 16; i++)
{
(function(idx)
{
setTimeout(
function()
{
moveToPlace(idx);
}, idx * 100);
})(i);
}
started = true;
}
};
// initialise
var stage = document.getElementById(targetId);
var felt = document.createElement("div");
felt.id = "felt";
stage.appendChild(felt);
// template for card
var card = document.createElement("div");
card.innerHTML = "<img src=\'back.png\'>";
for(var i=0; i < 16; i++) {
var newCard = card.cloneNode(true);
newCard.fromtop = 15 + 120 * Math.floor(i/4);
newCard.fromleft = 70 + 100 * (i%4);
(function(idx) {
newCard.addEventListener("click", function() { cardClick(idx); },
false);
})(i);
felt.appendChild(newCard);
cards.push(newCard);
}
}
EDIT: When i open my browser, i get like this picture shows
https://imgur.com/7ACU7vt the one who has the text "Not working" should not show up. When i open programmer tool i can se that under id="stage", id="felt" creates two times and thats why I have one working and other one not working. My question is why does i get two id="felt" when my code only say one?
It is already existing in your html, and then within the script you create it again. You cannot have 2 different elements with the same id. Remove it from the html and see my comment
So I have the following Code:
class Process {
constructor(){
this.failedattempts = 0
}
generateNumber(){
this.randomNumber = Math.floor(Math.random() * 20)
document.getElementById("randomdisplay").innerHTML = this.randomNumber
//this.guessNumber(this.randomNumber)
}
getNumber(test){
var temp
for (var i=0; i < test.elements.length; i++){
temp = test.elements[i]
//alert("getnumberloop iteration number " + i)
if(temp.name){
this.submittedContent = temp.value
}
}
//alert(this.submittedContent)
}
guessNumber(){
//alert(randomInput)
//alert("submittedContent in guessNumber() is " + this.submittedContent)
//alert("randomNumber in guessNumber() is " + this.randomNumber)
if(this.submittedContent == this.randomNumber){
document.getElementById("victorymessage").innerHTML = "You won!"
document.getElementById("victorymessage").style.color = "red"
}else{
this.failedattempts++
alert("failedattempts in guessnumber() is " + this.failedattempts)
}
}
}
class chartData {
constructor () {
this.processClone = new Process
}
displayfailedattempts(){
alert("entered displayfailedattempts")
alert(this.processClone.failedattempts)
}
}
var processInstance = new Process
var chartDataInstance = new chartData
//document.getElementById("randomdisplay").innerHTML = processinstance.guessNumber();
<!DOCTYPE html>
<html>
<head>
<title>game with graphs!</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<link rel="stylesheet.css" type="text/css" href="gamestyle.css">
</head>
<body onload="processInstance.generateNumber()">
<div id="div1">
<p>input number between 0 and 19 here</p>
<p>random number is</p>
<p id="randomdisplay"></p>
<form>
<input type="text" name="place">
<input type="button" value="senden" onclick='processInstance.getNumber(this.form)'/>
</form>
<input type = "button" value = "evaluate" onclick="processInstance.guessNumber()"></input>
<p id="victorymessage">did you win?</p>
<input type = "button" value = "showattempts" onclick="chartDataInstance.displayfailedattempts()">
</div>
<script src="gamejs.js"></script>
</body>
</html>
The purpose of this whole thing was/is to practice processing userinput on the webpage via javascript. I chose this approach because I wanted to practice mainly with javascript and not bother with php and a server.
Later on I want to display for example the number of failed attempts in graphs created with chart.js. Thats why I called the second class where the output happens "chartData". Since determining the number of failed attempts is inherently connected to evaluating the users "tip", I've put it into the guessNumber() method.
Now, the main issue is that when I use a property thats derived from "Process" class, then the "displayfailedattempts()" method always displays "0". It seems the property inside ChartData class , although derived from process Class, is not visible there.
I've tried numerous different attempts where I created a property inside process Class derived from ChartData class, but this didn't result in any success.
I wonder what other options I have?
For the sake of practice I'm trying to keep up the current approach with two classes as long as possible. I also try to avoid coding outside the classes, because I want to try out how far I can go in connecting the classes between each other.
This is a basic OOP design.
I do not know if your design is correct, but specific in the way you went, The processInstance should be receive the reference of the instance that already exists, rather than create a new one.
You can pass it to her as a constructor parameter:
class Process {
constructor(){
this.failedattempts = 0
}
generateNumber(){
this.randomNumber = Math.floor(Math.random() * 20)
document.getElementById("randomdisplay").innerHTML = this.randomNumber
//this.guessNumber(this.randomNumber)
}
getNumber(test){
var temp
for (var i=0; i < test.elements.length; i++){
temp = test.elements[i]
//alert("getnumberloop iteration number " + i)
if(temp.name){
this.submittedContent = temp.value
}
}
//alert(this.submittedContent)
}
guessNumber(){
//alert(randomInput)
//alert("submittedContent in guessNumber() is " + this.submittedContent)
//alert("randomNumber in guessNumber() is " + this.randomNumber)
if(this.submittedContent == this.randomNumber){
document.getElementById("victorymessage").innerHTML = "You won!"
document.getElementById("victorymessage").style.color = "red"
}else{
this.failedattempts++
alert("failedattempts in guessnumber() is " + this.failedattempts)
}
}
}
class chartData {
constructor (prc) {
this.processClone = prc
}
displayfailedattempts(){
alert("entered displayfailedattempts")
alert(this.processClone.failedattempts)
}
}
var processInstance = new Process
var chartDataInstance = new chartData(processInstance )
//document.getElementById("randomdisplay").innerHTML = processinstance.guessNumber();
<!DOCTYPE html>
<html>
<head>
<title>game with graphs!</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<link rel="stylesheet.css" type="text/css" href="gamestyle.css">
</head>
<body onload="processInstance.generateNumber()">
<div id="div1">
<p>input number between 0 and 19 here</p>
<p>random number is</p>
<p id="randomdisplay"></p>
<form>
<input type="text" name="place">
<input type="button" value="senden" onclick='processInstance.getNumber(this.form)'/>
</form>
<input type = "button" value = "evaluate" onclick="processInstance.guessNumber()"></input>
<p id="victorymessage">did you win?</p>
<input type = "button" value = "showattempts" onclick="chartDataInstance.displayfailedattempts()">
</div>
<script src="gamejs.js"></script>
</body>
</html>
You can use extends from class Process and call super() to run constructor of parent class
class chartData extends Process {
constructor () {
super();
// this.processClone = new Process
}
displayfailedattempts(){
alert("entered displayfailedattempts")
alert(this.failedattempts)
}
}
// var processInstance = new Process
var chartDataInstance = new chartData();
chartDataInstance.displayfailedattempts();
See the codepen
My toggle button logic (the last code block in under the <script> tag) only seems to work in one direction. Specifically, the temperature, temp, variable arrives at this section of code in Celsius. On button click, everything successfully converts to Fahrenheit, but then the button stops working. Note, I tried an alternate design using closures, embedding everything in the updateTemp function, changing the button's id with every click, and axing the top two variables under $(document).ready. It was a mess and still didn't provide the toggle functionality I was looking for. Thoughts?
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Bootstrap -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- CSS -->
<!-- JS/JQ -->
<script>
$(document).ready(function () {
var tempType = 0;
var temp = 0;
var coords = {
lat: 0,
lon: 0
};
// retrieve and set user's latitude and longitude coordinates
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
coords.lon = position.coords.longitude;
coords.lat = position.coords.latitude;
// AJAX called here b/c getCurrentPosition is asynchronous
sendAJAX(coords);
});
} else {
alert("Sorry, I couldn't locate you. Here's the weather elsewhere.");
coords.lon = 48.8566;
coords.lat = 2.3522;
sendAJAX(coords);
}
// AJAX request and settings wrapped in fxn for ease of calling within if/else
function sendAJAX (coords) {
// enumerate AJAX request settings & pass in coordinate settings
var ajaxOptions = {
crossDomain:true,
dataType:"json",
url:"https://fcc-weather-api.glitch.me/api/current?",
data: {
lon:coords.lon,
lat:coords.lat
},
method:"GET"
};
// attached .done() fxn calls used here, as they rely on the JSON file returned by the AJAX request
$.ajax(ajaxOptions).done(updateCity).done(updateIcon).done(updateDesc).done(updateTemp).done(updateHumid).done(updateWind);
}
// update weather icon on page
function updateCity (json) {
var cityHTML = "";
cityHTML += json.name + ", " + json.sys.country;
$("#city").html(cityHTML);
}
// update weather icon on page
function updateIcon (json) {
var iconHTML = "";
iconHTML += "<img src='" + json.weather[0].icon + "'";
iconHTML += "alt='weather icon'>";
$("#icon").html(iconHTML);
}
// update description of weather on page
function updateDesc (json) {
var descHTML = "";
var desc = json.weather[0].main;
descHTML += desc;
$("#descript").html(descHTML);
changeImage(desc);
}
// update temperature
function updateTemp (json) {
var tempHTML = "";
// the 0x in front of the character code matters, no truncation allowed despite what some docs might seem to suggest
temp = Math.round(json.main.temp);
var degree = String.fromCharCode(0x2103);
tempHTML += temp + degree;
$("#temp").html(tempHTML);
}
// update humidity
function updateHumid (json) {
var humidHTML = "";
var percent = String.fromCharCode(0x0025);
humidHTML += json.main.humidity + percent;
$("#humidity").html(humidHTML);
}
// update wind speed
function updateWind (json) {
var windHTML = "";
windHTML += json.wind.speed + " knots";
$("#wind").html(windHTML);
}
// change background image
function changeImage (desc) {
if (desc.match(/Clear/)) {
$("body").css("background-image", "url(img/clear.jpg)");
} else if (desc.match(/Rain/)) {
$("body").css("background-image", "url(img/rain.jpg)");
} else if (desc.match(/Haze/)) {
$("body").css("background-image", "url(img/haze.jpg)");
} else if (desc.match(/Clouds/)) {
$("body").css("background-image", "url(img/cloudy.jpg)");
} else if (desc.match(/Snow/)) {
$("body").css("background-image", "url(img/snow.jpg)");
} else {
$("body").css("background-image", "url(img/default.jpg)");
}
}
// toggle button logic
if (tempType == "0") {
$("#convert").on("click", function () {
var fahrenheit = Math.round((9/5)*(temp) + 32);
var tempFarHTML = "";
var degree = String.fromCharCode(0x2109);
tempFarHTML += fahrenheit + degree;
$("#temp").html(tempFarHTML);
$("#convert").html("Convert to Celsius");
tempType == "1";
});
} else {
$("#convert").on("click", function () {
var celsius = temp;
var tempCelsiusHTML = "";
var degree = String.fromCharCode(0x2103);
tempCelsiusHTML += celsius + degree;
$("#temp").html(tempCelsiusHTML);
$("#convert").html("Convert to Celsius");
tempType == "0";
});
}
});
</script>
<title>Local Weather</title>
</head>
<body>
<div class="container">
<div class="row text-center">
<div id="page-title" class="col-md-12">
The Local Weather
</div>
</div>
<div class="row text-center">
<div id="city" class="col-md-12">
City
</div>
</div>
<div class="row text-center">
<h2>Current Conditions</h2>
<div id="icon" class="col-md-12 img-responsive">
Icon
</div>
<div id="descript" class="col-md-12">
Desc
</div>
</div>
<div class="row text-center">
<div class="col-md-4">
<h2>Temperature</h2>
</div>
<div class="col-md-4">
<h2>Humidity</h2>
</div>
<div class="col-md-4">
<h2>Wind</h2>
</div>
</div>
<div class="row text-center">
<div id="temp" class="col-md-4">
Temp
</div>
<div id="humidity" class="col-md-4">
Humid
</div>
<div id="wind" class="col-md-4">
Wind
</div>
</div>
<div class="row text-center">
<div id="temp" class="col-md-4">
<button id="convert" class="btn btn-default">Convert to Fahrenheit</button>
</div>
</div>
</div>
</body>
</html>
The condition should be checked inside of the function as follows:
// toggle button logic
$("#convert").on("click", function () {
if (tempType == "0") {
var fahrenheit = Math.round((9/5)*(temp) + 32);
var tempFarHTML = "";
var degree = String.fromCharCode(0x2109);
tempFarHTML += fahrenheit + degree;
$("#temp").html(tempFarHTML);
$("#convert").html("Convert to Celsius");
tempType == "1";
temp = fahrenheit;
} else {
var celsius = temp;
var tempCelsiusHTML = "";
var degree = String.fromCharCode(0x2103);
tempCelsiusHTML += celsius + degree;
$("#temp").html(tempCelsiusHTML);
$("#convert").html("Convert to Celsius");
tempType == "0";
temp = celsius
});
});
Also, as mentioned by #gavgrif in a comment on the question, there is a duplicate id "temp", which should be corrected.
Instead of
tempType == "1";
I think you're looking for one equal sign
tempType = "1";
When your page is loaded, your tempType is 0 and on click event is registered on your convert div to change the value to farenheit.
When the onClick event is triggered and your conversion works for the first time, however your onClick event doesn't change as your page isn't loaded again and your onClick event stays the same even though your tempType is set to 1. You need to change the way you try to solve your problem, you must reload the whole page or make a function that changes your onClick event, and assign it to your button, however that is not a good practice and would be considered to be an anti-pattern. The best approach would be to move the if-else condition inside the onClick event.
i am pretty new to javascript (a little over 2 months into my studies) and am starting my first project. the end goal is to have a set of baseball team logo images (right now 6 images but eventually i would like to expand this to more) randomized every time a button is clicked. i had researched on how to do this and came across the fisher yates algorithm used in a while loop, and various uses of random number generation. decided to use the fisher yates.
at the moment, my code seems to work. i followed 1 image and i couldn't see a specific pattern. my other concerns are if i can achieve the same functionality using 1 loop and also cleaning up my code so its not so repetitive.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>sports</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="container">
<h1>Sports Random</h1>
<br>
<div class="row">
<div class="col-sm-2"> <img id="team1"src="images\sports\team1.jpg" alt=""></div>
<div class="col-sm-2"> <img id="team2"src="images\sports\team2.jpg" alt=""></div>
<div class="col-sm-2"> <img id="team3"src="images\sports\team3.jpg" alt=""></div>
<div class="col-sm-2"> <img id="team4"src="images\sports\team4.jpg" alt=""></div>
<div class="col-sm-2"> <img id="team5"src="images\sports\team5.jpg" alt=""></div>
<div class="col-sm-2"> <img id="team6"src="images\sports\team6.jpg" alt=""></div>
</div>
<br>
<button id="button">Random</button>
<button id="reset">Reset</button>
</div>
</div>
<script src="js/main.js"></script>
</body>
</html>
var button = document.getElementById("button");
var reset = document.getElementById("reset");
var team1 = document.getElementById("team1");
var team2 = document.getElementById("team2");
var team3 = document.getElementById("team3");
var team4 = document.getElementById("team4");
var team5 = document.getElementById("team5");
var team6 = document.getElementById("team6");
var pics = ["team1.jpg", "team2.jpg", "team3.jpg", "team4.jpg", "team5.jpg", "team6.jpg"];
var teams = [team1, team2, team3, team4, team5, team6];
button.addEventListener("click", function random() {
var i = pics.length,
rNum, temp;
// shuffle pictures using fisher yates
while (--i > 0) {
rNum = Math.floor(Math.random() * (i + 1));
temp = pics[rNum];
pics[rNum] = pics[i];
pics[i] = temp;
}
// display images
for (var i = 0; i < teams.length; i++) {
teams[i].src = "images\\sports\\" + pics[i];
}
});
reset.addEventListener("click", function reset() {
team1.src = "images\\sports\\team1.jpg";
team2.src = "images\\sports\\team2.jpg";
team3.src = "images\\sports\\team3.jpg";
team4.src = "images\\sports\\team4.jpg";
team5.src = "images\\sports\\team5.jpg";
team6.src = "images\\sports\\team6.jpg";
});
Just add an id to the div class="row" id="parent">
and replace the code like this.
var button = document.getElementById("button");
var reset = document.getElementById("reset");
var originalChildren =
Array.from(document.getElementById("parent").children);
button.addEventListener("click", function random() {
var list = document.getElementById("parent");
for (var i = list.children.length; i >= 0; i--) {
list.appendChild(list.children[Math.random() * i | 0]);
}
});
reset.addEventListener("click", function reset() {
document.getElementById("parent").innerHTML = "";
for (var i =0 ; i< originalChildren.length; i++) {
document.getElementById("parent").appendChild(originalChildren[i]);
}
});
Additionally, I would also suggest creating the children dynamically then appending them to parent instead of putting them in HTML. But, this is entirely up to you. Modified the code so you don't have to keep the elements in JS side.
Here is a Fiddle that might help you:
https://jsfiddle.net/yha6r5sy/1/
You can use list.children to add it to main div
I've browsed through a couple of questions but I couldn't find any help.
By the way this is the first time I'm asking a question here so I might not do it the right way. Anyway, the following line is causing me the problem
/* cursorPps defined above */
document.getElementById("cursorPps").innerHTML = cursorPps;
The cursorPps variable is already defined. Can someone point out what other possible stuff could have caused this error?
Edit: By the way the problem is that it is not updating the value on HTML, although the value of the variable changes.
HTML:
<html>
<head>
<title>Potato Clicker</title>
<link rel="stylesheet" type="text/css" href="interface.css">
</head>
<body>
<div id="left">
<img id="potato-img" onClick="potatoClick(clickPower)" src="stockvault-potatoes107220.jpg" width="300" height="300">
<br>
<div id="mainDisplay">
<span id="potatoes">0</span> <br> potatoes
<br>
<br>
Producing <span id="pps">0</span> potatoes per second
<br>
</div>
Cursors: <span id="cursors">0</span>
</div>
<div id="middle">
<div id="buildings" onClick="buyCursor()"> Buy Cursor </div>
</div>
<script src="main.js"></script>
</body>
</html>
Javascript:
//variables
var potatoes = 0; //potatoes
var clickPower = 1; //potatoes gained per click
var pps = 0; //potatoes per second
var cursors = 0; //cursors
var cursorCost; //cost of cursor
var cursorPps = 0; //total cursor potatoes per second
var cursorBuy; //cursor buy button
//functions
function potatoClick(number) {
potatoes = potatoes + number;
document.getElementById("potatoes").innerHTML = potatoes;
}
function buyCursor() {
var cursorCost = Math.floor(10 * Math.pow(1.2,cursors));
if (potatoes >= cursorCost) {
pps = pps - cursorPps;
cursors = cursors + 1;
potatoes = potatoes - cursorCost;
cursorPps = cursorPps + 1;
pps = pps + cursorPps;
document.getElementById("potatoes").innerHTML = potatoes;
document.getElementById("cursors").innerHTML = cursors;
document.getElementById("cursorPps").innerHTML = cursorPps;
document.getElementById("pps").innerHTML = pps;
}
else {
alert("Not enough potatoes!")
}
var nextCost = Math.floor(100 * Math.pow(1.2,cursors));
document.getElementById('cursorCost').innerHTML = nextCost;
}
window.setInterval(function () {
if (pps > 0) {
potatoClick(pps);
}
}, 1000);
Make sure that
You have an element has that ID
The element IS on the page before that Javascript is run
You bind the execution of your JS to an event (follow-up from previous) that happens after the element is on the page
The cursorPps variable has been populated
Here's a simple codepen that demonstrates a way to do it http://codepen.io/leopic/pen/wDtIB
<div id="myDiv"></div>
You have an element with that ID
var length = document.querySelectorAll('#myDiv').length;
if(length > 0) {
// This element exists in the DOM tree
}
You bind the execution of your JS to an event (follow-up from previous) that happens after the element is on the page
<body>
<div id="myDiv"></div>
<script>
var length = document.querySelectorAll('#myDiv').length;
console.log(length);
</script>
</body>
The cursorPps variable has been populated
if(cursorPps != undefined)