<jupyter_start><jupyter_text>---title: Toggling code cells in Jupyter HTML Outputssummary: "Or, How I Wasted an Afternoon."date: 2020-01-11source: jupyter--- When writing a blog post in Twitter, I found there was no easy way toreproduce the rather lovely **code folding** effect you get in ([Rmarkdown documents](https://bookdown.org/yihui/rmarkdown/html-document.htmlcode-folding)),so I went and made one myself, illustrated here.Actually, I've written a few of them, as the code changes slightly depending on where you want to achieve code folding.First, here's some toggleable code.<jupyter_code>for i in range(9, -1, -1):
    if i > 0:
        print('.' * (i) + ('%i' % i) + '.' * (9-i))
    else:
        print('>Lift Off!')
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
plt.hist(np.random.normal(0, 1, 100));<jupyter_output><empty_output><jupyter_text>Jupyter MagicTo activate toggling directly in a live Notebook usingthe [%%JavaScript magic](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/JavaScript%20Notebook%20Extensions.html), just nclude the cell below in your notebookIf the notebook is [truster](https://jupyter-notebook.readthedocs.io/en/stable/security.html),it will automatically run when you load the page.<jupyter_code>%%javascript
function toggler(){
    if(window.already_toggling){
        // Don't add multiple buttons.
        return 0
    }
    let btn = $('.input').append('<button>Toggle Code</button>')
        .children('button');
    btn.on('click', function(e){
        let tgt = e.currentTarget;
        $(tgt).parent().children('.inner_cell').toggle()
    })
    window.already_toggling = true;
}
// Since javascript cells are executed as soon as we load
// the notebook (if it's trusted), and this cell might be at the
// top of the notebook (so is executed first), we need to
// allow time for all of the other code cells to load before
// running. Let's give it 5 seconds.

setTimeout(toggler, 5000);<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12226640159045726, 'fraction_numerical': 0.013916500994035786, 'mean_word_length': 4.096202531645569, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 13, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '38795', 'license': 'MIT', 'n_tokens_mistral': 655, 'n_tokens_neox': 616, 'n_words': 209, 'path': 'content/post/jupyter-toggle/index.ipynb', 'repo_name': 'EoinTravers/hugo.eointravers.com', 'size': '2012'}