Colorful JavaScript Console Output

See how to easily style your console outputs in JavaScript just by adding a few extra arguments. Please note that this currently only works in Google Chrome and Firefox.

 

Basic usage

This is not a feature that you’d use with every console.log call, but can come in handy for printing some initial messages, e.g. copyright notes, homepage links or any other important stuff you need to highlight. The styling is done using basic CSS attributes like background, color, font, font-style etc. The CSS string is passed as another argument to the console.log method. Also, when using styles, you will need to put ‘%c‘ at the beginning of the text that you want to be styled.

 

log-single
result of the above code

Multiple styles

You can also use multiple styles. To do this, you just pass more CSS strings to the method and insert corresponding ‘%c‘ marks in your message.

 

log-multi
result of the above code

Compatibility

As I noted before, this only works in Google Chrome and Firefox. But what happens if you run such a script in a browser like IE? Well the good news is that the code won’t generate any errors; The bad news is that the ‘%c‘ marks will remain visible and the styles will be connected with spaces to your message too.

So you will probably need some fallback for such browsers. For situations like these I like to use Bowser, a browser detection script by Ded (GitHub: https://github.com/ded/bowser). If you decide to use this script as well, the code will look like this:

 

Get crazy

Some people just like to take things a bit further… (Code by bartburkhardt from this answer on StackOverflow)

 

log-rainbow
I wouldn’t use this for my copyright tho.
Share on FacebookTweet about this on TwitterShare on Google+Share on Tumblr

Comments (0)