Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - adding style to the text of console log [duplicate]

Recently I logged into my FB account on Chrome Browser. When I opened the developer tools, I saw something like this:

enter image description here

Now I know that it is possible to add anything to console using the javascript console.log function. But my question is -- how did they add style to the text? E.g. "Stop!" is written in red tahoma font with black border and larger size. How did they do it?

like image 545
Ruchir Gupta Avatar asked Jul 18 '14 15:07

Ruchir Gupta


People also ask

What does .log do in JavaScript?

The console. log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user. Syntax: console.

How do I copy the output console in JavaScript?

Right click on the object in console and click Store as a global variable. the output will be something like temp1. type in console copy(temp1) paste to your favorite text editor.

Is console log same as print?

The only notable difference between the two is that, when printing an object, console. log gives special treatment to HTML elements, while console. dir displays everything as plain objects.


1 Answers

Addy Osmani has a good explanation:

https://plus.google.com/+AddyOsmani/posts/TanDFKEN9Kn (archive.org)

Styled console logging in the Chrome DevTools (Canary)

Thanks to Mr. +Mike West, you can now add style to your console log via %c, just like you can in Firebug. e.g

console.log("%cBlue!", "color: blue;");  

Blocks such as console.log('%cBlue! %cRed!', 'color: blue;', 'color: red;'); are also now supported :)

Whilst most people will probably use this for practical purposes, it's also possible to have a little fun with it :) (see below)

Not to be outdone, here's what +Mike West came up with a few days ago

;)

Relevant change: http://trac.webkit.org/changeset/130941


Basically, you can use the %c paramater to pass in CSS styling. For an example, try the following in your chrome console:

console.log("%cBlue! %cGreen", "color: blue; font-size:15px;", "color: green; font-size:12px;");
like image 160
khalid13 Avatar answered Sep 25 '22 14:09

khalid13