Total results: 24

Sorting a German date format in Tablesorter.js

The German date format is 01.05.2015 as opposed to the UK date format 01/05/2015 which Tablesorter.js comes prebuilt to parse.

To sort by a German date, you have to add a custom parser. Here is one that will work for a date with the German dot notation.

$.tablesorter.addParser({
  id: 'dotDate',
  is: function (content) {
    return /\d{1,2}\.\d{1,2}\.\d{1,4}/.test(content);
  },
  format: function (content) {
    content = content.replace(/\-/|:|\.|\//g,' ').split(' ');
    return $.tablesorter.formatFloat(new Date(content[2], content[1]-1, content[0]).getTime());
  },
  type: 'numeric'
});

Simply add this parser and then tell your tablesorter initializer function which column the German date is in.

$('table').tablesorter({
  headers: {
    0: { sorter: 'dotDate' }
  }
});

If your date only has 2 numbers for the year instead of 4, you can adjust the is method to use the regex /\d{1,2}\.\d{1,2}\.\d{1,2}/.

Detect Internet Explorer 10 without conditional comments

Commonly to target specific versions of Internet Explorer we will use conditional HTML comments to apply a specific class name to the <html> tag. With this approach it is then trivial to target a specific browser via CSS for special styling. For example:

<!--[if IE 8]> <html class="ie8"> <![endif]-->

Since Internet Explorer conditional comments have been disabled since IE10, we can no longer use the following syntax.

<!--[if IE 10]> <html class="ie10"> <![endif]-->

JavaScript to the rescue

In order not to break from the pattern of HTML specific class names for IE versioning, a JavaScript can be used to manually add a class targeting IE10.

if (navigator.userAgent.match('MSIE 10.0;')) {
  $('html').addClass('ie10');
}

Or in pure JavaScript, if you do not have jQuery available.

if (navigator.userAgent.match('MSIE 10.0;')) {
  document.querySelector('html').className += " ie10"
}

This is not the ideal approach. In general feature detection is a better method to tell if a feature is available but when looking to target Internet Explorer purely for CSS styling purposes this may be the most pragmatic approach.

A simple jQuery add/remove class name pattern

Often when using jQuery and you aim to add or remove a class based on a state variable, you will see a function such as.

function updateInterface () {
    var shouldShowLogout = user.isLoggedIn;

    if (shouldShowLogout)
        $('.logout-button').addClass('active');
    } else {
        $('.logout-button').removeClass('active');
    }
 } 

This function is hard to read and basically repeats itself in the if and else clauses. The function implementation can be refactored down to 2 lines using a ternary if operator.

function updateInterface () {
    var shouldShowLogout = user.isLoggedIn;
    $('.logout-button')[ shouldShowLogout ? 'addClass' : 'removeClass' ]('active');
}

Since you can access functions of a an object in JavaScript like values, you can use the [] accessor to return the correct function based on the ternary if statement and them immediately call it using (), or in this case passing our class name value ('active').

You could even take this down to a single line.

function updateInterface () {
    $('.logout-button')[ user.isLoggedIn ? 'addClass' : 'removeClass' ]('active');
}

Although this final single line approach may be confusing to the next developer who is not already familiar with the pattern.

Ember Server "Bus Error 10" Fix

If you are using the ember-cli package to access the ember command line tool and experience a "Bus Error 10" that crashes the ember server every time you save a file then it is probably due to an incompatible Node.js version.

To fix this issue simply head to the Node.js downloads page and get the latest version of Node for your operating system.

For a functional ember server you should be using Node.js version 0.10.21 or higher, personally I upgraded from 0.10.20 to 0.10.29 and now the server runs perfectly, including the live reload functionality.

JavaScript Beacon API Explained

Beacons are a new API that is being experimentally introduced by browser vendors that will allow an XHR call to be made to a server when a webpage unloads without blocking the thread in order to create a better user experience. Quoting the W3C Beacon Specification.

"analytics and diagnostics code will typically make a synchronous XMLHttpRequest in an unload or beforeunload handler to submit the data. The synchronous XMLHttpRequest forces the User Agent to delay unloading the document, and makes the next navigation appear to be slower. There is nothing the next page can do to avoid this perception of poor page load performance."

This specification will prevent developers from having to use tricks and hacks to bend the rules of the browser, creating a better experience for everyone.

Fix "0.1 + 0.2 = 0.300000004" in JavaScript

Because JavaScript uses the IEEE 754 standard for Math, it makes use of 64-bit floating numbers. This causes precision errors when doing floating point (decimal) calculations, in short, due to computers working in Base 2 while decimal is Base 10.

0.1 + 0.2; // 0.300000004

A simple solution to this problem is:

+(0.1 + 0.2).toFixed(1); // 0.3

Here the numbers are added together, returning the erroneous floating number, it is then set using toFixed as a string "0.3". Finally the + symbol casts the string back to a valid Number so that it can be worked with again.

var x = 0.1,
  y = 0.2;

var z = +(x + y).toFixed(1);
z += 0.1; // z is now 0.4

Fastest alternative to Math.floor in JavaScript

Normally to floor a number in JavaScript we would use the built in Math.floor function. There are however other ways to round a number down in JavaScript, by using the bitwise operators to perform the rounding operation on a binary level.

The various methods are:

  • |
  • ~~
  • <<
  • >>
  • >>>

Which can be used, for example, like so:

var float = 367.9987;

~~float //367
float | 0 //367
float << 0 //367
float >> 0 //367
float >>> 0 //367

I have set up a test on the great JS Perf website to sample which of these methods is fastest in the various browsers, check out the result and run the tests for yourself here:

http://jsperf.com/math-floor-alternatives

So far, my result graph looks like so (for an interactive version please visit the link above):

Math.floor results in JavaScript (from Browserscope)

These results are very interesting. As you can see currently Chrome will handle all of these operations at almost the same speed. However, Internet Explorer handles Math.floor around 76% slower than a bitwise shift/or.

Surprisingly Safari 7 handles all versions in a slow manner, with the triple bitwise shift (>>>) being the fastest.

In FireFox Math.floor has actually been optimised to the fastest but the other methods are still very close behind.

Taking all of this into account, I would suggest using a regular bitwise shift >> as this is fast in all browsers, including Internet Explorer.

However, that being said the syntax for a bitwise not is more intuitive and looks more natural in the flow of code, for example:

var x = 345.768,
  y = 0;

// Confusing
y = (5 * x) << 0;

// Nicer
y = ~~(5 * x);

// Least confusing, but slower
y = Math.floor( 5 * x );

So ultimately you must make the choice of which operation to use based on your application, the audience you have and the actual routine you are implementing. Meaning, it's best not to confuse the next programmer who comes along so Math.floor is best in non performance critical code but (5 * x) << 0; might be a good idea in a performance bottleneck situation such as on an animated <canvas> which runs code in a loop many times per second.

Thanks for the programming challenge, Deutsche Telekom!

A guide on how to fix the Speedport W 723V "web 'n' walk" configuration error that occurs when trying to run the setup.

Recently the W 723V Speedport router that I rent from Deutsche Telekom automatically pulled an update for new software. This update put my router into an unresponsive mode, meaning I had to reset the device and re-enter my login / configuration data through the internal configuration utility (A.K.A https://speedport.ip/).

The Speedport provides a configuration page where I would normally enter my Deutsche Telekom details and the setup would run. After this update however, the setup tells me that my "Web 'n' Walk Stick" has not been properly configured.

I do not own a Web 'n' Walk stick, so I saw this as an obvious bug in the configuration web page. The page was submitting the wrong configuration form details, as both forms are in the same page, just shown/hidden via JavaScript.

After calling Deutsche Telekom, they were clueless, had no help to give and promised to call back when an engineer was available. This is where I took the task upon myself to inspect the router software and see if I could fix this problem myself. The game was afoot, a programming challenge lay ahead. After around an hour absorbed in convoluted code, ignoring the temptation to let the Deutsche Telekom get away with this, I focused in on the problem, the following is the description of the solution.

© Blake Simpson, 2012 – 2017