Better JavaScript Using Modern Techniques

I’m going to highlight some of my favorite modern JavaScript features in this post. Most of these are new to ES6, but a few of them are not. I call these features modern because they allow JavaScript to be written in a way that supports conciseness for better readability. This isn’t intended to summarize all of ES6. It’s mostly just tips for more readable and interactive code. Continue reading “Better JavaScript Using Modern Techniques”

HTML5 Canvas Object Rotation

There is no simple function that you can use to rotate objects within the HTML5 Canvas. To implement rotation you need to rotate the entire canvas context and draw your object on the rotated context and then rotate the entire thing that back to it’s normal state. While you’re doing that, you also need to update the coordinate space of the canvas context. Continue reading “HTML5 Canvas Object Rotation”

Even Row Heights for Columns With Bootstrap and AngularJS

When using AngularJS to iterate over and display a collection with Bootstrap columns you might notice that the columns don’t stack nicely unless they all have the same content height. If the content heights differ, then you’ll have some of them nested in strange places. Continue reading “Even Row Heights for Columns With Bootstrap and AngularJS”

Stop Using for…in Loops to Iterate JavaScript Arrays

The best way to iterate a JavaScript array is using the trusty old for loop. Anything else is inefficient and prone to bugs. Some might recommend the for...in loop. Read on for the specific reasoning behind this.

Why is the for…in loop error prone?

What do you expect the value of sum to be? If you guessed 60 you’d be wrong. This script has a bug. for...in iterates over the arrays keys and not the values. So inside of each iteration the value of num is the key and not the value. To make matters worse, JavaScript uses strings for the indexes even with arrays! This means that sum will not be a number and instead a concatenated string with the value of 102030.

Just use a regular for loop when iterating over JavaScript arrays.

This example would be much less prone to errors with the use of the simple for loop.

You can also make a small micro-optimization here by caching the call to numbers.length by adding something like this:

With this method you no longer have the potential to incorrectly use the index as a value and you have the index as an integer, which is more versatile.

Handling Unicode Code Points in JavaScript

JavaScript strings are implemented in Unicode. Unfortunately, soon after JavaScript was created the Unicode developers realized that they implemented their vision incorrectly and revised their standard. By that time, Unicode was already so engrained in JavaScript that they feared changing anything would cause more harm than good. This means that in some situations the built in string functions of JavaScript will return erroneous data when dealing with some Unicode characters. This is because JavaScript strings are made up of 16-bit code units, while Unicode is based on code points. More on this coming up.

JavaScript/Unicode code units? Code points?

The original Unicode team miscalculated how many code points they would be able to fit into 2^16. They believed that they would be able to fit everything they wanted into this number. They were hoping that there would be a 1:1 mapping between the code unit that represented the element of their encoding and the code point, which is the unique integer that Unicode assigns every single unit of text. This means that every single unit of text from every single Unicode supported language is given a unique integer that represents it.

As is pertains to JavaScript, this meant that at the time each character in a JavaScript string could be mapped to a single Unicode code point because each character was a 16-bit value that fit inside of 2^16. Unfortunately, their miscalculation caused a lot of issues. While 2^16 is a massive number they soon discovered that they were outgrowing the original system. The Unicode standard was eventually expanded to support 2^20 code points, which is where it remains to this day. With this update, the current system was obsolete and they needed to introduce a system for representing numbers 2^16 or greater.

In come surrogate pairs.

To represent these new numbers, surrogate pairs were introduced. Two code units in the 2^16 range were now being mapped to a single code point greater than 2^16. This can cause a serious issue with strings in JavaScript. Multiple characters in a string (the code units) are now mapped to a single Unicode code point. This means that you can no longer believe that your JavaScript UTF-16 encoded strings length will match up with the number of characters in the string. The string may have a length of 10 based on string.length, but it may only have 9 actual Unicode code points in it because two of the code units in the string are being combined to represent a single Unicode code point.

Too late

JavaScript was already too entangled with the original Unicode 2^16 size to bother switching to the new method of handling strings that Unicode developed, thus the main string methods that we use everyday were never updated to handle the encodings outside of the 2^16 range. Some of these methods include length, charCodeAt and charAt.

Here we have a single code unit that maps directly to a single code point. This code point maps to: ☯. The length of this string is 1 as we might expect.

This is where it gets a little bit more complicated. Here we have multiple code units that map to a single code point. The length of this string is 2, even though we are only representing a single Unicode code point. This code point maps to: ?. The issues outlined here for length are also present for other string methods and even regular expressions. There are some standard libraries that are aware of code points directly, such as the URI libraries, which include encodeURI and decodeURI.

Remember this

To summarize, you should know that JavaScript operates on code units, while the Unicode standard operates on code points. Some code points need to be represented by multiple code units. JavaScript string methods do not understand this. When two code units are used to represent a single code point they are called surrogate pairs.

Triggering DataTables to search only on enter key press

By default DataTables will search whenever the user types something. If you’re using Ajax to search this might trigger a bunch of unnecessary calls to your server. Use this to only trigger the search when the enter key is pressed. You can also customize it to search every few letters or once a specific length is reached in the search box.

Notice the initComplete key. We wait until DataTables is initialized and then we remove the default handler, which is set to search on each keyup and we bind our own handler that searches only when the enter key is pressed.

An Easy Way to Obfuscate Your Email on a Website

I was looking for a quick way to hide my email from spam bots on my website. I was looking for best practices so I loaded up Google and looked for some solutions. I wasn’t 100% happy with what I found so I ended up rolling one myself.

Some research on this site shows that a quick way to do this is to use CSS. It’s a pretty awesome solution, with one big flaw. You provide the reverse of the email address and CSS will reverse it. Sounds like a really easy and clever solution. The problem is that if the user tries to copy the text they will get the reversed and incorrect email address in their clipboard. I only tested it in Google Chrome, so maybe it works on other browsers.

My solution is similar, but I use JavaScript to reverse the string instead of CSS. Bots might become keen to this and you might have to use more advanced techniques like building the email from a string concatenated in different places, but for me this should work well. I use GMail so hopefully Google can filter out the spammers that get passed this.

This script will find all elements marked for our hidden email and get the reversed email from the tag and reverse it to the correct email. It will also add the email to the href attribute and to the element value. Your HTML email might look like this:

The email you want to reach in this example is test@test.com. The reverse of that can be seen in the anchor element value.

Even Better Multiline Text Boundary Fitting For Fabric.js Text Objects

This is a revision of my previous post detailing how to get Fabric.js text objects with multiline strings to fit within a preset viewport or boundary. The original post can be found here. This version has been revised and will now automatically scale the font size to copyfit the text when the height of the text object is larger of the preset dimensions. In the previous version it would stop displaying the new lines.

This object will need to be customized to your specific needs. I may consider turning it into a library once it has been further tested. Here is an example of how to use it:

Provide the formatter object with the width and height of the viewport boundary. The formatter will then make sure that your text fits within that viewports boundary.