There is a nice solution provided here that works well for notebooks exported to HTML. The website even links back here to this SO post, but I don't see Chris's solution here! (Chris, where are you at?)
This is basically the same solution as the accepted answer from harshil, but it has the advantage of hiding the toggle code itself in the exported HTML. I also like that this approach avoids the need for the IPython HTML function.
To implement this solution, add the following code to a 'Raw NBConvert' cell at the top of your notebook:
<script>
function code_toggle() {
if (code_shown){
$('div.input').hide('500');
$('#toggleButton').val('Show Code')
} else {
$('div.input').show('500');
$('#toggleButton').val('Hide Code')
}
code_shown = !code_shown
}
$( document ).ready(function(){
code_shown=false;
$('div.input').hide()
});
</script>
<form action="javascript:code_toggle()">
<input type="submit" id="toggleButton" value="Show Code">
</form>
Then simply export the notebook to HTML. There will be a toggle button at the top of the notebook to show or hide the code.
Chris also provides an example here.
I can verify that this works in Jupyter 5.0.0
Update:
It is also convenient to show/hide the div.prompt
elements along with the div.input
elements. This removes the In [##]:
and Out: [##]
text and reduces the margins on the left.