Toggle button works in one direction only - javascript

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.

Related

Why is my save function not executing in its entirety?

I am trying to create a to-do list in HTML, CSS and pure JS.
const dSubmit = document.getElementById('submit');
const storeData = [];
let typer = document.getElementById('type');
let input = document.getElementById('text');
const list = document.getElementById('listHolder');
dSubmit.addEventListener("click", (e) => {
e.preventDefault();
if (input.value == "") {
typer.innerHTML = "Please enter a task";
} else {
typer.innerHTML = "";
store();
}
});
function store() {
const tData = document.getElementById('text').value;
storeData.push(tData);
updater();
input.value = "";
}
function deleter (index) {
storeData.splice(index, 1);
updater();
}
function updater() {
let htmlCode = "";
storeData.forEach(function(item, index){
htmlCode += "<div class='test'><div id = "+ index +">" + item + "</div><div class='sideBtn'><button type='button' class='edit' onClick= 'editF("+ index +")'>Edit</button><button class='delBtn' onClick= 'deleter("+ index +")'>Delete</button> </div> </div>"
})
list.innerHTML = htmlCode;
}
function editF (index) {
let tempOne = document.getElementById(index);
let tempTwo = "<input id='inputText"+String(index)+"' type='text' name='task' value ='" + String(storeData[index]) + "'><button id='saveText"+String(index)+"' onClick= 'save("+index+")' >Save</button>"
tempOne.innerHTML = tempTwo;
}
function save (index) {
console.log('test1')
let tempOne= document.getElementById('saveText'+String(index));
let tempTwo = document.getElementById('inputText'+String(index));
console.log('test2')
tempOne.addEventListener("click", function foo (){
console.log('test3')
storeData.splice(index,1,tempTwo.value)
updater()
}
)
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<title>To Do List</title>
</head>
<body>
<h1>To-do-list</h1>
<form>
<label for="task">Please enter item:</label>
<input type="text" name="task" id="text">
<button id="submit">Submit</button>
</form>
<div id='type'></div>
<div>List:</div>
<div id="listHolder" class="test"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
I am facing problems with the save function. If I edit an item in the to-do list and click the save button, the function executes up to the point of console.log('test2'). If I click save again the function executes in its entirety.
I would like to ask why the first click results in execution of the save function up to 'test2'?
Additionally would anyone be kind enough to critique my JS? are there things in dire need of improvement? or is there a more practical/efficient method of writing my JS code?
Thank you for your help in advance.
After the 'test2' log, you are adding an event listener, and the rest of the code is inside of the listener block. The code in the listener block is only executed once that listener receives a 'click' event, which is why it works the second time.

JavaScript not working for all HTML pages

I am working on the tablet's display of a Pepper robot; I have a functional HTML index page comprising a list of questions—each question redirects to its respective HTML when clicked on—, 2 volume buttons and 2 other buttons—one that pops up an instruction image and the other one that closes the index page and gets back to the splash screen, which when clicked upon, reveals the index page. So far everything is working. The issue is that when I click a question—I get redirected to its HTML page, but then I get stuck there, as neither the 2 volume buttons nor the 2 other buttons work;
I made sure to include the following in each HTML page:
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
I also reused the same JavaScript functions that worked for the index page.
I commented out some line:
btnPrevious.addEventListener('click', goToPreviousPage);
because I noticed it prevented the splash screen from disappearing when clicked on—i.e., the visibility attribute stays on visible instead of switching to hidden thus revealing the index page, but still, the 3 remaining buttons don't work anyway.
Here is my faq.js code:
/* global QiSession */
var serviceName = 'ADFAQ';
var volumeUpEvent = serviceName + '/VolumeUp';
var volumeDownEvent = serviceName + '/VolumeDown';
var volumeData = serviceName + '/Volume';
/* Clickable buttons */
var btnReturn = document.getElementById('return');
var btnHelp = document.getElementById('call_help');
var btnPrevious = document.getElementById('previous_page');
var btnVolUp = document.getElementById('volume-up');
var btnVolDown = document.getElementById('volume-down');
/* Help image and splash screen */
var helper = document.getElementById('helper');
var img = document.getElementById('click_on_me');
var memory;
var volume;
var audioDevice;
QiSession(connected, disconnected);
function connected (s) {
console.log('QiSession connected');
var questions = document.getElementById('questions');
/* Associating buttons to their respective functions */
btnHelp.addEventListener('click', showHelper);
btnReturn.addEventListener('click', closeQuestions);
//btnPrevious.addEventListener('click', goToPreviousPage);
btnVolUp.addEventListener('click', raiseVolume);
btnVolDown.addEventListener('click', lowerVolume);
img.addEventListener('click', loadQuestions);
questions.addEventListener('click', clickOnQuestion);
s.service('ALMemory').then(function (m) {
m.subscriber(serviceName + '/DialogEnded').then(function (subscriber) {
subscriber.signal.connect(hideQuestions);
});
m.subscriber(serviceName + '/Pepper').then(function (subscriber) {
subscriber.signal.connect(displayPepperHTML)
});
m.subscriber(serviceName + '/RaiseVolume').then(function (subscriber) {
subscriber.signal.connect(raiseVolume);
});
m.subscriber(serviceName + '/LowerVolume').then(function (subscriber) {
subscriber.signal.connect(lowerVolume);
});
memory = m;
});
s.service('ALAudioDevice').then(function (a) {
a.getOutputVolume().then(assignVolume);
audioDevice = a
});
}
function disconnected () {
console.log('QiSession disconnected');
}
function assignVolume(value){
volume = value;
}
function raiseVolume (event) {
var changed = 0;
if(volume < 100) {
volume = Math.min(volume + 5, 100);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeUpEvent, changed);
}
function lowerVolume (event) {
var changed = 0;
if(volume > 30) {
volume = Math.max(volume - 5, 0);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeDownEvent, changed);
}
function showHelper (event) {
if (btnHelp.innerHTML === '?') {
helper.style.opacity = '1';
helper.style.zIndex = '1';
btnHelp.innerHTML = '←';
} else {
helper.style.opacity = '0';
helper.style.zIndex = '-1';
btnHelp.innerHTML = '?';
}
btnHelp.blur();
}
function loadQuestions (event) {
memory.raiseEvent(serviceName + '/LoadQuestions', 1);
img.style.visibility = 'hidden';
}
function goToPreviousPage () {
window.location.href = "index.html";
}
function displayPepperHTML() {
window.location.href = "pepper.html";
}
function closeQuestions (event) {
if(location.href != "index.html")
{window.location.href = "index.html";}
memory.raiseEvent(serviceName + '/CloseQuestions', 1);
btnReturn.blur();
}
function hideQuestions (data) {
if (data !== 0) {
img.style.visibility = 'visible';
helper.style.opacity = '0';
btnHelp.innerHTML = '?';
}
}
function clickOnQuestion (event) {
memory.raiseEvent(serviceName + '/' + event.target.id, 1);
}
Here is my non-functioning pepper.html code:
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Pepper</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=1280, user-scalable=no" />
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/faq.css" />
</head>
<body>
<header>
<h1>Bla bla bla</h1>
<span class="buttons">
<button id="previous_page" class="button-help"> ← </button>
<button id="return" class="button-return">X</button>
</span>
<div id="helper" class="pop-up">
<img src="img/interactionscreen_frf.png" alt="Bla bla bla">
</div>
</header>
<ul id="questions">
<p>
Bla bla bla
</p>
<div class="volume-part">
<div id="volume-up" class="Click-me">+</div>
<img src="img/speaker.png" alt="Bla bla bla" style="vertical-align: middle;">
<div id="volume-down" class="Click-me">-</div>
</div>
</ul>
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
</body>
</html>
Thank you for your help.
I am expecting the pepper.html page to respond to both the volume and ← and X buttons, as the index.html should, since they use the exact same Javascript.
I was able to find some workaround: creating one JavaScript file for each HTML page, this is redundant and non-optimal I know, but at least it works.
This also made me realize that the commented-out line was blocking the program because the index.html page doesn't use the previous_page button, that's what led me to make a JS file for each HTML page.
If anybody has any other suggestions I am all ears.
Edit: I reduced the number of JS scripts to only 2. One for the index.html and the other for the identically-structured html pages of the other questions.

Why does the browser create two pieces of div in html but when the code just says one?

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

How to run JavaScript in WebStorm

I'm new at this so apologies in advance if I'm missing something obvious, but I'm not able to figure out how to run JavaScript in WebStorm. The WebStorm documentation says to simply open the HTML file in the browser, but that doesn't seem to work. For what it's worth, everything is working up on codepen.io.
Here's the HTML (for a simple weather app):
<body>
<head>
<script src="script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<div class="container-fluid">
<div class="col-sm-3">
</div>
<div class="col-sm-6">
<div class="white-box text-center">
<span>Weather where you are:</span>
<div class="loc"></div>
<div class="weather"></div>
<div class="temp"></div>
<br>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</body>
And here's the script (still in draft, as it needs to be expanded to, among other things, link to images covering all values for 'weather'):
$(document).ready(function() {
$( window ).on("load", function(){
$.getJSON("http://ip-api.com/json", function(json) {
var json;
json = JSON.stringify(json);
var obj = JSON.parse(json);
var latitude = obj.lat;
var longitude = obj.lon;
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+latitude+"&lon="+longitude+"&appid=74a6725c2ca6f1342464bb9005bf0b63", function(json) {
var json;
json = JSON.stringify(json);
var obj = JSON.parse(json);
var loc = obj.name;
var weather = obj.weather[0].description;
var tempInCelsius = obj.main.temp - 273.15;
var tempInCelsiusString = tempInCelsius.toFixed(1) + " &#8451";
var tempInFahrenheit = obj.main.temp * 9/5 - 459.67;
var tempInFahrenheitString = tempInFahrenheit.toFixed(1) + " &#8457";
var tempStringCombined = tempInCelsiusString + " | " + tempInFahrenheitString;
$(".loc").html(loc);
if(weather === "haze"){
weather = "<img src='https://cdn3.iconfinder.com/data/icons/chubby-weather/440/fog-512.png'>";
}
$(".weather").html(weather);
$(".temp").html(tempStringCombined);
});
});
});
});
Many thanks in advance for any help!
Select the tab of html file(say index.html), and click in the menu Run > Run... and select index.html.

Update javascript object properties inside of a for loop?

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.

Categories

Resources