Wednesday, 17 September 2014 at 1:20 pm

In my previous entry, I showed how to add a toggle code cell button to your IPython notebook. Someone in the comments had a great solution where a code snippet is added to the custom.js file. His code is located here:

However, it seems like a lot of people wanted a feature where the published notebook (NBViewer) has the ability to hide the code cell. 

It turns out, it is possible to run javascript in the notebook if you import the HTML method from IPython:

from IPython.display import HTML

In a code cell, add this:

function code_toggle() {
if (code_show){
} else {
code_show = !code_show
$( document ).ready(code_toggle);
The raw code for this IPython notebook is by default hidden for easier reading.
To toggle on/off the raw code, click <a href="javascript:code_toggle()">here</a>.''')

When you run this code cell, by default, all the code cells will now be hidden. But you can toggle it on and off by clicking on the link. This toggle link will also be present in the published (NBViewer) version.

Here is an example of an IPython notebook with this toggle link:

*Note that the above link doesn't actually contain the raw toggle script. I put all my IPython specific python scripts in a python library. I then import the script.