Xah Lee Xah Lee - 4 months ago 5
Javascript Question

odd event handler error: num.toString is not a function

an odd problem. Hard to describe in few words, but i'll try. (am JavaScript beginner).

when mouse hovers over a .u tag, i want it to do something. So i have:

var dotUElements = document.getElementsByClassName("u");

for (var ii = 0; ii < dotUElements.length; ii++) {
dotUElements[ii].onmouseover = createHandler1( dotUElements[ii] );
dotUElements[ii].onmouseout = createHandler2( dotUElements[ii] );
}


then adding handlers:

function createHandler1( myobj ) {
return (function() {ff1(myobj);});
}

function createHandler2( myobj ) {
return (function() {ff2(myobj);});
}


my functions ff1 for mouseover and ff2 for mouse out are:

function ff1 (myobj) {
myobj.style.color="red";
var uChar = myobj.firstChild.nodeValue;
var uNum = uChar.charCodeAt(0);
uName = unicodeTable(uNum);
var uHex = (uNum).toSring(16);
}

function ff2 (myobj) {
myobj.style.color="black";
}


the problem is the last line

var uHex = (uNum).toSring(16);


it creates error:

Error: TypeError: uNum.toSring is not a function


if i replace that line by simply

(30).toSring(16);


same error. Any hints on what's wrong? i have the code at
http://xahlee.info/js/ex/xx_test.html

Answer

Here is a working demo for your example

function unicodeTable(num) {
  var unicodedata = {
    0x2190: "LEFTWARDS ARROW",
    0x2191: "UPWARDS ARROW",
    0x2192: "RIGHTWARDS ARROW",
    0x2193: "DOWNWARDS ARROW",
  };
  return unicodedata[num];
}

function createHandler1(myobj) {
  return (function() {
    ff1(myobj);
  });
}

function createHandler2(myobj) {
  return (function() {
    ff2(myobj);
  });
}

function ff1(myobj) {
  myobj.style.color = "red"; // test code. so we know it's activated
  var uChar = myobj.firstChild.nodeValue;
  var uNum = uChar.charCodeAt(0);
  uName = unicodeTable(uNum);
  var uHex = (uNum).toString(16);
  alert(uHex);
}

function ff2(myobj) {
  myobj.style.color = "black"; // test code. so we know it's activated
}

var dotUElements = document.getElementsByClassName("u");

for (var ii = 0; ii < dotUElements.length; ii++) {
  dotUElements[ii].onmouseover = createHandler1(dotUElements[ii]);
  dotUElements[ii].onmouseout = createHandler2(dotUElements[ii]);
}
<body>

  <h1>unicode test 3</h1>

  <p>
    <b class="u">←</b>
    <b class="u">→</b>
    <b class="u">↑</b>
    <b class="u">↓</b>
  </p>

  <p>when mouse hover on b.u element, show the unicode name.</p>
</body>

I have added an alert(uHex); to show the value.

Let me know if it didn't work.