Hazel Meehan
Hazel Meehan

Reputation: 23

Special character breaking JavaScript code

I am making a JavaScript flash card game for a mechanics website. Because I want to put equations on the cards I need to use a delta(Δ) sign.

A card might have: "The equation for power" on one side and "P=W/Δt" on the other. If the card starts on side one it will flip when the space key is pressed or when the flip button is pushed. However, if it starts on side two, the one with the Δ sign, it will not flip when the 'flip' button or space key is pushed.

I have tried different ways of writing Δ:

Δ Δ Δ

none of these worked. My code is:

//Copyright Attribution-ShareAlike 4.0 International 2017 Hazel Meehan


//array containing all options
var options = [ //counts from 0
  "Joules(J)", "Measure of Work",
  "Watts(W)", "Measure of Power",
  "Ek", "Kinetic Energy",
  "Ep", "Potential Energy",
  "Newtons(N)", "Measure of Force",
  "Pascals(Pa)", "Pressure",
  "ms-1", "Metres per Second",
  "ms-2", "Metres per Second Gained",
  "10N", "Value of Gravity",
  "Weight is a", "Force beginning with W",
  "The capacity to do work", "Energy is",
  "d = ΔvΔt is the equation for", "The equation for distance",
  "W=FΔd is the equation for", "The equation for work",
  "P=W/Δt is the equation for", "The equation for power"
];

//initialize variables
var randomNum = 0;
var sideOne = " ";
var sideTwo = " ";

//choose new card using random number
var newCard = function() { //runs on 'next'
  var randomNum = Math.floor(Math.random() * options.length);
  sideOne = options[randomNum];
  if (randomNum % 2 == 0) { //is the number even
    sideTwo = options[randomNum + 1];
  } else {
    sideTwo = options[randomNum - 1];
  }
  document.getElementById("card").innerHTML = sideOne;
};

//show other side of card
var flip = function() { //runs on 'flip'
  if (document.getElementById("card").innerHTML == sideOne) {
    document.getElementById("card").innerHTML = sideTwo;
  } else {
    document.getElementById("card").innerHTML = sideOne;
  }
};

//change card on key down
document.onkeydown = function(e) {
  e = e || window.event;
  if (e.keyCode == '39') { //right arow key
    newCard();
  } else if (e.keyCode == '32') { //space bar
    flip();
  }
}
<article>
  <h2>Flashcards</h2>
  <center><button id="flashButton" onclick="newCard()">Next</button></center>
  <br>
  <center><button id="card"></button></center>
  <br>
  <center><button id="flashButton" onclick="flip()">Flip</button></center>
</article>

Upvotes: 0

Views: 831

Answers (1)

ASDFGerte
ASDFGerte

Reputation: 5195

When checking the element's innerHtml (if (document.getElementById("card").innerHTML == sideOne)), the string previously set has been interpreted as html and when retrieving it, the &Delta; will now be Δ. The comparison is then false:

"d = &Delta;v&Delta;t is the equation for" !== "d = ΔvΔt is the equation for"

Therefore it sets the innerHtml to the same side again.

Upvotes: 1

Related Questions