Callysto.ca Banner

Open in Callysto

Hiding code

When presenting a Jupyter notebook, it is sometimes useful to hide the code. This makes the presentation less cluttered and less confusing to the viewer.

Callysto developed came up with an easy solution. The following piece of code, once run, creates a “Show code / Hide code” button in the notebook, that will display or hide code as per your selection.

You can copy this code into your own notebooks, to add this functionality whenever you want it.

Run the following block, and click the button to see how it works.

%%html

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

Example 1

Here is a short piece of code that prints out some words. Observe how the code gets hidden when the “Hide Code” button above is clicked.

print('Here is a list of colours: \n')
for colour in {'red', 'orange', 'yellow', 
               'green', 'blue', 'violet', 'black'}:
    print(colour)
Here is a list of colours: 

violet
green
red
yellow
black
blue
orange

Example 2

We can also hide HTML elements, such as we get when we insert a YouTunde video, or include some music.

Here is a video:

%%html
<iframe width="300"  src="https://www.youtube.com/embed/ZmhlRsYjs7Y?start=30" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Example 3

Here is a clip of music.

%%html
<audio controls>
  <source src="KolnShort.wav" type="audio/wav">
Your browser does not support the audio element.
</audio>

End

And that’s about it. Enjoy!

Callysto.ca License