Fun with console logging

Ok, so “fun” is probably a relative term here, but it’s certainly possible to do a lot more with console logging than a lot of developers realise, including myself up until a couple of weeks ago, and I’ve just had the opportunity to use it in my latest projectCompare the Project™.

So if you got to Compare the Project™ and open the developer tools (F12 in most browers) and go to the Console tab, you should see this…

As you can see, that’s not just text, but there’s an image in there, and styled (bold) text as well.  So how did I do this?

Well here’s the javascript…

console.log("%c  %ccompare%cthe%cproject%c™%c - Rik Lewis © 2020", "background-image: url(''); background-repeat: no-repeat; background-size: 32px 32px; font-size: 32px","font-weight: bold","font-weight: normal","font-weight: bold","font-size: 80%","font-weight: normal");

Let me break that down a bit…

  1. “%c %ccompare%cthe%cproject%c™%c – Rik Lewis © 2020” – the first parameter is a string which includes 6 instances of “%c”, which is the key
  2. “background-image: url(‘×32.png’); background-repeat: no-repeat; background-size: 32px 32px; font-size: 32px” – this is styling which outputs the site’s favicon at a fixed size (first “%c”)
  3. “font-weight: bold” – styling to make “compare” bold (second “%c”)
  4. “font-weight: normal” – styling to make “the” normal (third “%c”)
  5. “font-weight: bold” – styling to make “project” bold (fourth “%c”)
  6. “font-size: 80%” – styling to make “™” smaller (fifth “%c”)
  7. “font-weight: normal” – styling to make “Rik Lewis © 2020” normal (last “%c”)

As you can see, “%c” is used to inject styling into the text that you are logging out, and for each one you can add another parameter with the styling.

If you want another example, check out Porsche Digital.