Making IE play nice…still

I came across an issue with IE9 yesterday, while using Twitter Bootstrap. I almost couldn’t believe it, having copied the template from the Bootstrap website, I thought it would be issue free. To add to my exasperation, the bug was in IE9 – the modern browser

At first I simply couldn’t understand what was wrong. Everything seemed to be correct, and then I looked at the IE developer tools. IE was rendering the page in quirks mode! Having used the HTML5 doc type, having not played with the styles in bootstrap, even having removed a few HTML comments I’d added, it was still happening!

Luckily, a guy that I was working with had seen the issue before, and before long he’d found a tag which sorted everything out. Rather than working fine with valid and correct HTML, IE9 needs this <meta> tag:

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

Once this had been put into the <head> of the document, everything rendered with the IE9 engine and all was well again. But it is still quite ridiculous to see some hack-like technique being required in any modern browser.

What’s worse is that we won’t be rid of IE9 any time soon. With the release preview of IE10 for Windows 7 only having been made available last month, it’s unlikely there will be a huge rush to upgrade. Especially as IE10 sports Windows 8 like gesture controls for a lot of operations, which will surely alienate most users of the previous browsers.

It seems that this is yet another IE-only hack that we’ll just have to endure for a little while more!

EDIT (09/01/2013): Looks like I may’ve over-looked part of the bootstrap documentation, it seems that this meta tag is indeed mentioned in the “Responsive design” section! Oops!

Useful Links

 Microsoft explaining their different rendering modes

 A stackoverflow question which was answered with this <meta> tag

Advertisements

Javascript: Selecting a range of checkboxes

A quick post about a small snippet of code that I’ve quickly written up, just to see how easily it could be done. It’s a feature that I feel should be on every web app (there are exceptions though). It’s the ability, when dealing with a list of checkboxes (in an email client for example), to be able to select one checkbox and then, while holding shift, select another and for this to then select all those checkboxes in between. To effectively select a range of checkboxes all at once.

This reduces the number of clicks required, in some cases, drastically and is one of those nice little touches which really makes you feel as though the user interaction with a web app has been considered. To make things even better, it’s a very simple feature to implement! I’ve attempted to do it sparingly, but I’m sure it can be condensed even more. And my comments can of course be removed to save space.

Hopefully this will help someone  to add a nice little extra to their web app, just as a final bit of polish. I’ve put it on to Codepen, which means if I’ve made a massive error, someone can fork me and correct it!

You can find my code at http://codepen.io/andrewbridge/pen/qtgcE and it includes a demo of the code working, do try it out! It may be something that’s helpful to you!

Auto-Scrobbling bookmarklet

I’ve recently got back into the habit of using Last.Fm (again!) and scrobbling whatever I’m listening to, to it. This has been fine for the most part, I use either Spotify or iTunes to listen to my music and both of these having scrobbling features, I also occasionally listen to Last.FM radio, which of course has scrobbling as part of it.

The last thing that I couldn’t work out, was scrobbling the music played on the radio. I’m a big fan of BBC 6Music, it’s a brilliant station, great for when you’re at work and you really shouldn’t be mucking about with choosing music too much and there’s rarely a track that I’m embarrassed to say I’ve listened to.

However, there is very little provision for scrobbling radio stations, it’s generally very platform specific. One website has the answer however, Universal Scrobbler will fetch the track listings from several locations, a few of which, are BBC radio stations. Meaning I can fetch the latest tracks played on 6Music and scrobble the ones I’ve listened to.

There’s one last problem however, I still have to regularly go back to the website to fetch in the new tracks being played and scrobble those. This can be a pain, and when you’re at work, you probably shouldn’t be mucking about with this if you don’t have the time to muck around with your own music! So in a few minutes, I got to grips with the website and created a bookmarklet for the site.

Continue reading Auto-Scrobbling bookmarklet

Javascript: addEventListener and element.event

A quick post on the differences between addEventListener and element.event.

addEventListener and element.event, on first appearances, do the same thing. They allow a custom function or action to be linked to a javascript event, which are usually triggered by user-input.

But in more detail they do in fact have differences and for this reason, they should be used and treated differently. Each case where either is required should be assessed to make sure that it’s the best option of the two.

Using both methods

To use an addEventListener for the mousedown event, for example, we would do this.

var mouseInput = function(e) {
//filter the mouse inputs you're looking for
//do something based on the mouse input
}

document.addEventListener('mousedown', mouseInput, true);

The alternative element.event method would look like this.

var mouseInput = function(e) {
//filter the mouse inputs you're looking for
//do something based on the mouse input
}

document.onmousedown = mouseInput;

That’s it, and in most cases, both those will do the same thing…

The Exception to Explain the Difference

However, the methods are actually doing different things behind the things.

addEventListener

addEventListener assigns an additional function or action to carry out when the event happens. The clue is in the name really, addEventListener suggests that it won’t overwrite or override any other actions. This is generally a good thing, scripts, extensions and the browser itself will have assigned things to certain events and it may make the User Experience (UX) poorer if those normal functions and actions don’t happen when those specific events happen.

However, it also means that if you are purposely trying to change default actions to in fact improve the UX, this method won’t work “out-of-the-box”. An example of this is if you’re writing a web app and you want to force your own right click context menu*. You won’t surpress the context menu by default.

*A note on this idea: This is something you should carefully think about, it can certainly be useful, but many core browser operations can be found in the default right-click menu, and many extensions place a menu item to enable them to work effectively. It’s best to only use it on certain parts of the web page/app if you really are going to do this. It is very inadvisable to use this technique to stop people copying your content, there are other ways to take your content and it will often detriment genuine, non-malicious users.

element.event

element.event is an absolute assignment, it scraps and effectively destroys anything that was meant to happen when that event occurred and instead replaces it with yours. When put like that, it’s a pretty selfish way of coding as, again, it is likely to detriment the overal UX. Posts about making element.event assignments less problematic were commonly seen around a decade ago. But as addEventListener has become more supported over the years (it has been in the w3 spec for years and had support in Netscape 6(!), but only gained full support across the browsers when IE9 came in), and full featured libraries such as jQuery it has been less of an issue.

However, element.event has it’s place. It has much wider support. It’s likely that you’ll be able to support browser versions you’ve not even considered because this method of registering event listeners has been around since the beginning of Javascript (it’s fully supported in Netscape 2 as part of DOM 0…). So if compatibility is a real issue further than it is for most projects, and you can’t use a library (which will more than likely have this support built in), then this is your method to go for.

It also is quicker, and in some respects, a little easier to read, so if you’re writing a proof of concept or a quick script, where you know you won’t be interfering with anything unintentionally. Then this is also the method to choose.

The Best of Both

It is now accepted that using addEventListener over element.event is generally a better way to do things. You won’t be mucking about with the pre-assigned functions and actions for that event, which means that you’ll provide a better, more consistent UX overall.

However, if you actually are looking to surpress default actions using addEventListener, it is possible. This final example demonstrates how.

var mouseInput = function(e) {
e.preventDefault();
//filter the mouse inputs you're looking for
//do something based on the mouse input
}

document.addEventListener('mousedown', mouseInput, true);

It should be noted that this example is actually a very bad idea if implemented, as it will stop any pre-assigned click functions. If you were trying to prevent the default context menu from appearing on right click, you should replace mousedown with contextmenu to do this correctly. See my (*) about this above.

Further Reading

 StackOverflow thread that brought these differences to my attention
 Further information on element.event registration
 Article from 2004 on making a cross-browser addEventListener (for the onload event) function for full browser support
 Article from 2001 about how difficult it was to code cross-browser event handlers (not much has changed sadly…)
 Mozilla Developer Network page on both event registration methods
 QuirksMode article on DOM Level 0 (the first version of DOM, used in the first iterations of Javascript)

Javascript: Using Prototype

It seems that I have missed a major part of Javascript, and even more importantly, I’ve missed one of the fundamental attributes and styles of Javascript! From what I’m seeing round the Internet, I’m definitely not the only one, in fact it seems as if even some seasoned professionals, who’ve worked with Javascript with years, still don’t use or quite understand the concept of prototyping.

I myself am completely new to the concept. I’ve seen code with prototyping in before, but I’ve not known anything about it, and I’ve found other ways around it. If you’ve come across it before, maybe in an older implementation of Javascript, and need your Prototype education rewiring, you should maybe look at the article by Angus Croll (which I’ve also linked in the Further Reading section at the bottom). Otherwise, I’ll see if I can explain it.

You can go without using prototypes directly for as long as you use Javascript, but chances are that you’ll be using prototypes in everything you do and if you’re using a library like jQuery then there’s no question that you’ll be using prototypes. Many core Javascript objects use prototypes already, if you’ve ever use split() or replace() on a string – you’ll have used a prototype. But prototyping is not essential to programming in Javascript, which is why many go without using or knowing about it, however, it is the key to huge performance gains. Something which is very important if you’re making larger, more interactive pages with a lot of Javascript code.

An Example

Finding an example of this which could affect almost all Javascript developers was actually quite hard, as it doesn’t affect many in a massive way until you get into the aforementioned more interactive, larger pages. But I think I’ve found a scenario, sadly I’ve still had to explain a different style of coding, which really could go in another blog, but it’s nevertheless useful to explain objects and their place in programming.

Using simple functions

Say you wanted a set of functions which would change some text in a paragraph tag (<p>), to keep things simple, I only want to change what the actual text says and the colour of the text. Most people would instantly go for the following approach.

function changeText(pTagName, toWhat) {
document.getElementById(pTagName).innerHTML = toWhat;
  return true;
}

function changeColour(pTag, toWhat) {
  //do functions for colour change
  alert("colour changed to "+toWhat);
  return true;
}

And to the value of two p tags, you’d do the following.

changeText("pTag1","This is the new text.");
changeText("pTag2","This is the new text.");

But what if you had 10 things you wanted to be able to do to the paragraph tag? Or 100, what if you wanted to expand it to changing other elements? Really you’d want to have one function that did it all, right?

Using Objects

You can do this by using Objects. With an object you can write methods, which (in this case) will change anything you want about the paragraph tag. In this example, that’ll look like this.

function TextChanger(pTag) {
  this.textObj = document.getElementById(pTag);

  this.changeColour = function(toWhat) {
    //do functions for colour change
    alert("colour changed to "+toWhat);
    return true;
  };

  this.changeWords = function(toWhat) {
    this.textObj.innerHTML = toWhat;
    return true;
  };
}

We can then create an object which will change just the attributes of one paragraph tag each, making it much quicker and easier to manipulate it later on in your script. Now, we’d change the text like this.

//Assign a TextChanger object to both paragraph tags.
var text1 = new TextChanger("pTag1");
var text2 = new TextChanger("pTag2");
text1.changeWords("This was an object method changing me, the first one!");
text2.changeWords("This was an object method changing me, the second one!");

//Aside: If we wanted to change the colour now, we can do it like this.
text1.changeColour("blue");
text2.changeColour("pink");

You could stop there, that will still be faster than the first approach, and now everything will be contained, so things will still be easier to work with. But you can still get faster performance just from this simple example!

Using Prototypes with your Object

The problem is that every time you create a new TextChanger() object, it has to also create an instance of the changeWords() and the changeColour() method. And that can build up a surprising amount, especially if you’re using objects to do something a lot more complex or resource intensive.

So now we’re finally at the point where Prototypes come in. With a prototype, you can declare a function which will be available to every single instance of that TextChanger() object, or whatever object you want. Just about anything that is a function or a value in Javascript can have a prototype. Integers, Strings (more on this later), pre-existing Javascript objects, your own objects, whatever you want.

In our example here, if you use prototypes, it means that Javascript only needs to create one instance of changeWords() and one instance of changeColour() for any instance of TextChanger, whether you have one instance or a million instances. And as before, that really does start affecting performance once you start doing more complex operations!

To use prototypes in our code, we can do the following.

function TextChanger(pTag) {
  this.textObj = document.getElementById(pTag);
}

TextChanger.prototype.changeColour = function(toWhat) {
  //do functions for colour change
  alert("colour changed to "+toWhat);
  return true;
};
TextChanger.prototype.changeWords = function(toWhat) {
  this.textObj.innerHTML = toWhat;
  return true;
};

It’s pretty similar to what we saw in the above example with just declaring an Object. The only difference is that you declare your Object function and then outside of that function, you can declare your methods with “TextChanger.prototype.changeWords =” and your function.

To use it, it’s the same as using an object method (as shown above).

var text1 = new TextChanger("pTag1");
var text2 = new TextChanger("pTag2");
text1.changeWords("This was an object method changing me, the first one!");
text2.changeWords("This was an object method changing me, the second one!");

And to see the results of going through all that change? I’ve set up a benchmark test on jsPerf (a javascript benchmarking site that I would highly recommend!) and you can find that at http://jsperf.com/change-text-test. It differs slightly to the examples shown here, though only marginally. We’re still doing the same operations to get the same result.

In the case of the simple function test, the element has be retrieved each time and then it’s operated on. In the case of the Objects using nested methods, it’s actually slower, in this test, than the simple function! This is because it’s having to retrieve the element the same number of times as the simple function test and it’s having to create several instances of both methods. If you used this approach and did more using it, you’d find that actually, it would come out on top of the simple function test.

But it’s the Object with prototyped test which really shows the improvement on both these methods, it still has to retrieve the element for each paragraph tag, but only one instance of each method is created, and the actual operation takes less time because the element is already stored as an object property.

A time saver using prototypes

Because everything can have a prototype in Javascript, it means you can add some very interesting functionality into core features of Javascript. For instance, lets make a method to add the html entity for a bullet point to any string, using prototypes.

String.prototype.bullet = function() {
 return "&bull; "+this;
}

"Item 1".bullet(); //Returns "&bull; Item 1" or "• Item 1" in HTML

That’s pretty useful, but there are so many more useful things that can be done with prototypes. Explore what there is out there!

Any notes?

It should be noted that if you’re using a Javascript library (like jQuery), then you may come in to some problems with prototyping. Just Googling “prototype and jQuery” will show just a sample of these problems. So just be cautious if you do decide to use both of these together.

Just a quick aside!

Completely unrelated, I’d just like to once again recommend you try Adobe Photoshop CS6 while it’s still running in public beta, I made the banner for this blog post using just CS6 and it just keeps offering more and more. I really am impressed!

Further Reading

 jsPerf Benchmark test using the examples seen here
 General information about optimising your code from Nettuts
 Understanding Javascript Prototypes from the Javascript, Javascript blog
 Dmitry A. Soshnikov’s article on prototypes

Use Version Control Software for More Manageable Project Development

The bigger the project that I undertake, the more of a risk and sometimes a pitfall, that I fall in to. Often when developing code alone, you fly about, trying different bits of code and usually making snap decisions on which method to go for. At the time you think that it’ll be fine to work like that and it won’t cause any problems.

This is fine if you find there are problems early on, but if it’s not until days or weeks down the line, and you realise that you should’ve made the opposite decision, then you’ll have to try and figure out just what went wrong, and where and what you did differently to make things work.

Upon doing this for yet another project recently, I decided it’d be the last time it happened, and promptly looked into version control software, which I’d previously never thought about, assuming it was software only useful for team development.

Continue reading Use Version Control Software for More Manageable Project Development

HTML5: requestAnimationFrame made easy

I’ve been searching for a recent, clear article on how to start using requestAnimationFrame and it just doesn’t seem to exist.

requestAnimationFrame is an API for animating styling changes, canvas or WebGL. It removes the need to use a setInterval or setTimeout to continuously call an animation function and, along with it, optimises the animation both in visual and resource performance.

This sounds great, but the API is still experimental and so is liable to change, which it has done over the past year. This means a lot of the demos of the API online are outdated. Those that aren’t, make the API seem much harder to use than it actually is. This is what I’m hoping to remedy.

Continue reading HTML5: requestAnimationFrame made easy