Testing for “Not a Number” (NaN) in Javascript

When validating some text, to check if it’s a real number or not, I tried to compare it against “NaN”. I thought that was correct since that’s what Firebug tells me is returned by parseInt ("sfdsfs", 10). However, Firebug is just covering up Number.NaN, which is what you should be comparing against.

To check if a string is numeric, use the isNaN function:

if (isNaN (parseInt (somestring, 10)) {
	// is numeric
}

Quirks With Javascript Scope and Hoisting

Whilst drowning myself in JavaScript today, I learnt a couple of things.

First was that there’s such a technique as “hoisting“. I’ve taken for granted that defining a function anywhere in my code (whilst in scope) will be available for use. Even if I’m calling a function before it’s actually been declared (converse to what you’d consider to be procedural).

workOutSum (2, 3); // returns 5

function workOutSum (n, m) {
	return (n + m);
}

That’s thanks to hoisting. Declarations of functions get bumped up to the top of the scope. The same goes to variables declared with the var construct.

Continue reading

Money Format in Javascript

I have (amongst others) two functions in most of my websites’ common.js file, which is included on each page. The .round(precision) method just rounds the number to a certain precision, but it won’t be padded up to that precision, so it’s not helpful when you’re trying to output currency.

The second function though is .moneyFormat, which will handle that situation.

i = 11.2333;

i.moneyFormat (); // returns 11.23

i = 120;
i.moneyFormat (); // 120.00

i = 56.4;
i.moneyFormat (); // 56.40

It converts the number to a string, since a float won’t store the trailing zeros.

Continue reading

There is nothing wrong with using frameworks

After lurking in #javascript for a while I noticed that a lot of the developers there look down on people using jQuery and Prototype. Their view is that you’re just getting one step away from the actual language, and you’re leaving key programming skills behind.

I acknowledge that that’s true, but I don’t see why it matters. All languages are essentially frameworks of a lower level language. PHP is basically a framework for a load of C libraries. C is just a framework for assembly code. Assembly is just a framework for binary programming. Yes, by using PHP you lose a lot of functionality of C, but that’s just because PHP is filling a market with no need for hardware manipulation and the like.

Same with jQuery. If you use $.get() you lose the ability to do the request synchronously (I’m aware that you could just use $.ajax(), but I’m making a point), which isn’t really a big loss to most people when compared to the benefits.

Javascript isn’t exactly the most uniform language around, which IE not supporting half the stuff Opera does, and Safari doing things differently to Firefox it’s a really hard language to code for. You spend more of your time finding work-arounds for each browser than actual logic. The frameworks available all do that for you, making sure that there’re no compatibility issues between browsers, and that $(‘#element’).slideUp() does exactly the same on every browser.

I’d go as far as to say don’t even bother learning about document.getElementById means. It’s so clumsy and awkward when compared to $().

Due to those functionality additions though it’s obviously a little bit slower. I’ve not noticed any speed decrease, but in an “every microsecond counts” environment there would be a noticable difference. But Javascript engines are getting faster and faster so does it really matter? The average person doesn’t even notice a difference.

It’s just programming evolution. It happens to every language. I wouldn’t be surprised if a few forward thinking browsers decided to just store a copy of the latest framework versions locally, so they’re instantly available to every website without having to download the same file hundreds of times from different servers.

GBCanvas: A canvas experiment

I’m pretty sure my body doesn’t work on a 24 hour day cycle. I went to bed around 2300 two nights ago, and got up around seven. Though I’d been lying in bed awake, trying to sleep for much longer. I say I got about five or six hours sleep that night. I went to bed at ten tonight, and was awake by two. I feel I could stay awake until tonight now. I’m not tired or anything. Maybe so little sleep has just become a habit.

My sleep schedule isn’t why I’m here.

I’m doing some tests with the canvas element, and decided to make a class for it. You can see it over at the GBCanvas github I set up for it. (I’ve never used github. Just heard a lot about it.) The code is kinda broken at the moment though.

The class is based on the idea of pseudo-pixels, where you have a 300×300 canvas, and can set it to have ten rows and twelve columns. Then you can manipulate each of those segments, which I’ve decided to call pixels. The “GB” comes from Gameboy, because I figured it’d be cool to remake Zelda with canvas.

I want to add an edit mode so the user could do something like

$(document).ready (function () {
  var canvas = new gbCanvas ('canvasid1');
  canvas.editModeOn (true);
});

Which would allow clicking of a pixel and it fills it with a chosen colour. I  mostly want this feature so I can create pixel art, and then get the raw data:image/png data, which I can import into the project whenever. I’m aware I could just create sprites in Paint or something and import the file, but I don’t want to. I’m fond of imposing restrictions stubbornly unto myself.

After a few rethinks, I figured it would be fair simple to just bind a click event to the canvas

//  Turns on edit mode so onclicks are registered and bubbled
this.editModeOn = function (mode) {
  if (mode) {
    //  .click is a jquery thing
    this.canvasDiv.click (this.editModeClick);
  }
}

And then working out which pixel was clicked, and filling it with colour

  this.editModeClick = function (event) {
  //  getSelectPoint just returns an array with the X and Y coord of the click
  //  relative to the top left of the image (to avoid problems with scrolling)
  clickPoints = getSelectionPoint (event, this.canvasID);
  console.log (clickPoints);
  //  Work out which "pixel" they just clicked
  var coordWidth = parseInt (clickPoints[0] / pixelWidth);
  var coordLength = parseInt (clickPoints[1] / pixelHeight);
  console.log (coordWidth + ', ' + coordLength);
  this.colourPixel (coordWidth, corrdLength);
}

This doesn’t seem to work because the event is rarely passed. It is sometimes, but hardly ever. The function is bound correctly. It’s entirely a problem with the event being passed – something I’ve always had trouble with if I’m honest…

Update: Ladies and gents, do yourself a favour and check all your variables before you go bitching on your blog about your code not working. The event was being passed fine. The problem with my code is that since it’s a function that’s being bound to an event, it effectively loses it’s place in the instance of the class, so it no longer has access to the this variable.

My problem was that this.cavasID was undefined.

So, I fix that by simply passing it “this”. Changing the bound event function to something like this:

this.editModeClick = function (event, _this) {
  console.log (event);
  console.log (_this);
  clickPoints = getSelectionPoint (event, _this.canvasID);
  console.log (clickPoints);
  //  Work out which "pixel" they just clicked
  var coordWidth = parseInt (clickPoints[0] / _this.pixelWidth);
  var coordLength = parseInt (clickPoints[1] / _this.pixelHeight);
  console.log (coordWidth + ', ' + coordLength);
  _this.colourPixel (coordWidth, corrdLength);
}

That’s all well and good, but now I’m confused as to how to bind it…

this.canvasDiv.click (this.editModeClick (event, this));

The event needs to be the first argument, but I’ve no idea how to pass the event here… That obviously doesn’t work (event is undeclared).

Edit: Of course it was something ridiculously simple.

var self = this;
this.canvasDiv.click (function (event) { self.editModeClick (event, self) } );

Encoding problems

On localhost this script for really simple currency conversion works fine. When it’s live on the over hand the £ symbol is making it all iffy. It’s obviously being uploaded as the correct symbol, but I guess it’s not the correct charactor encoding, since that’s the only thing I can think that would be breaking the Javascript. You can check out the script brokenly working at my business site.

I don’t think anyone knows…

I’m still looking at how to get to the event data. At first, it was with another parameter, but now it’s at all. I can’t find any tutorials…

There’s this “events and event handlers” page. It gets to the ‘The Event object’ section which is brilliant! But then doesn’t say how you access it. I was using this “event accessing” page first, but it turns out that’s all wrong. It doesn’t work on my Firefox (3RC1).

So, I’m still lost.

Oh, and LiveJournal was no help. One person just told me to cheat and use a prewritten Javascript object and someone wanted me to write hundreds of lines

Taking a break

I had my law unit two exam today, and I think I did fine.

I’m not even thinking about my next exams (next, next Friday), so I’m having a break from worrying this week. Meanwhile, I’m gonna learn how to do drag and dropping HTML/Javascript. There don’t seem to be much helpful sites around.