allenfrostline

Hide Codes/Prompts in Jupyter Notebook


2020-02-27

I’m recently asked this question many times: how do I hide the codes in a Jupyter notebook? In fact, I myself encountered this need one or two years ago and had found an almost perfect solution. Check out the steps below.

Magic Scripts

Add on top of the notebook a new cell with scripts:

from IPython.display import HTML
HTML('''
<script>
code_show=false;
function code_toggle(){
    if(code_show){$('.prompt, .input, .output_stderr, .output_error').hide();}
    else{$('.input, .prompt, .output_stderr, .output_error').show();}
    code_show=!code_show;
}
function initialize(){
    document.body.style.fontFamily='Palatino';
    var output=$('.output_subarea.output_text.output_stream.output_stdout');
    $.merge(output,$('.output_subarea.output_text.output_result'));
    for(var i=0;i<output.length;i++)for(var j=0;j<output[i].children.length;j++)
        output[i].children[j].style.fontFamily='Palatino';
    code_toggle();
}
$(document).ready(initialize);
</script>
Click <a href="javascript:code_toggle()">here</a> to show/hide codes in this notebook.
''')

and at the bottom, an ending cell with scripts as follows:

HTML('''<script>initialize();</script>Click <a href="javascript:code_toggle()">here</a> to show/hide codes in this notebook.''')

A sample notebook with these two cells added would look like this:

Re-run the Notebook

KernelRestart & Run All and the notebook should be just as expected:

Notice here the two links we added empowers you to toggle on/off the codes and the prompts (the In [ ] tags on the left). You can customize them however you like, but I highly recommend you not to simply hide them - trust me, you’ll need them more when they’re hidden by yourself.

Export as HTML

You may now FileHTML (.html) and the toggling feature should still work if nothing broken.