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:

http://pastebin.com/H77xP2vN

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:

HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
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:

http://nbviewer.ipython.org/github/damiankao/smed-neoblast-analysis/blob/master/001_cap3-comparison.ipynb

*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.








Search

Categories


Archive