List Scrobbling bookmarklet

A few weeks ago, I introduced a bookmarklet that I’d created for Auto-scrobbling BBC Radio using the brilliant web app, Universal Scrobbler. Since then, I’ve been using the bookmarklet myself pretty regularly! It’s been very useful at work and so far I’ve not seen a bug (UI improvements maybe, but not actual bug!).

But there is still a problem, sometimes I don’t listen to the radio live, as it broadcasts. The BBC iPlayer is a brilliant service and I often use it to listen to shows that I would otherwise have missed altogether. But because there’s no live broadcast, there’s also no live track update. This means that, should I want to, I can’t scrobble the music I’m listening to! Looking on the feature requests on the web app’s forum, it’s been wished for in some form or another, by a majority of the community of users posting.

My newest bookmarklet sets out to solve this problem in part. For my specific scenario, I have solved it as much as I can with just the frontend to play with. It is now possible to go to the tracklisting of any BBC radio show, and get two batches of JSON code, one with all the artist names, the other with all the track names. This is very specific to the BBC website and the current layout they’re using, but that’s the instability that comes with bookmarklets which are relying on consistencies within the DOM.

The thing that may interest more people is the second half of the process, which happens on the Universal Scrobbler site itself. When the bookmarklet detects that it’s being run on the site, a box will appear with two text boxes to enter two batches of JSON code, this (if parsed correctly) will then allow for a batch scrobble operation to begin, using pre-existing features of the site.

It’s certainly not a perfect solution, but it’s pretty close. And it means that any JSON code can be entered into the two boxes, meaning playlist scrobbling is more of a possibility! Further to this, the bookmarklet is extendable, with the possibility of other sites being support to allow scrobbling from them as well!

As with the auto-scrobbling bookmark, I haven’t tested this. I know it won’t work on IE7 or below, there’s a few properties used for positioning of the UI that may not be supported in certain other browsers, but I’m not sure. Try it in a modern browser, and you should find it works! To get it, just click the link below and follow the simple instructions.

Universal Scrobbler :: List Scrobbler

Once you’ve done that, the bookmarklet works differently depending on where you are. If you’re on a BBC page, for a radio programme (I’d assume it’d work for ones that are live and updating their track listing as they go too!), clicking the bookmarklet will grab all the tracks it can find, show a white box in the middle of the page and give you the artist and track details in JSON code. If you’re on the Universal Scrobbler site, a similar white box will appear in the middle of the page and you can put JSON code into the two boxes it contains. When you click “Scrobble All”, it will visibly begin scrobbling (if it doesn’t something’s wrong!), once it’s finished, the box will disappear and you’ll see a confirmation message.

Hopefully something here will be useful for someone else to enjoy too!

Useful Links

 Universal Scrobbler

 Universal Scrobbler Last.Fm group page

 Universal Scrobbler’s creator on Last.Fm, OnDistantShores

Stub: 2013 Week 1

A stub is a short article which rounds up little bits of information that I’ve found throughout the week. These may be web or computer related, or they may be more general things. It’s more a personal log than an actual article, reminding me of things that I may’ve forgotten, but some of it may be of help to someone else!

A belated Merry Christmas and a Happy New Year! This is the first of these articles which , after having great trouble writing any of the articles that I have planned to over the holidays, I’ve decided to start so that I can at least get something on the page! It’s also part of my New Year’s resolution to write more!

This week:

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

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