Running cells when Thebelab starts

Sometimes it is helpful to automatically run some cells when Thebelab starts. For example, if you’d like to pre-define some variables or import a function that you’ll use later on. This lets you focus the code that users read on the ideas that you want to convey.

Thebelab can be controlled via Javascript after it has been initialized. Below are two ways that you can configure your Javascript to run code under-the-hood.

Running cells when Thebelab is initialized

A straightforward way to run code is to simply simulate a click on the buttons that are created when you launch Thebelab. By selecting the Thebelab button and calling the click() method, the code in that cell will be run (and outputs will show) once the Thebelab kernel is ready.

Here’s a code sample that selects all cells with a tag called thebelab-init and simulates a click on the button."request-kernel")(() => {
    // Find any cells with an initialization tag and ask ThebeLab to run them when ready
    var thebeInitCells = document.querySelectorAll('.thebelab-init');
    thebeInitCells.forEach((cell) => {
        console.log("Initializing ThebeLab with cell: " +;
        const initButton = cell.querySelector('.thebelab-run-button');;

Running custom code with Thebelab

In addition, you can run your own custom code from the Thebelab object with Javascript using the requestExecute method. Below is a code snippet that uses the same event trigger, but in this case runs some custom code against the kernel once it is ready."request-kernel")((kernel) => {
    // Find any cells with an initialization tag and ask ThebeLab to run them when ready
    kernel.requestExecute({code: "import numpy"})

In both of the cases above, you’ll likely need to customize the Javascript calls depending on how your code is structured and what behavior you’d like when users land on a page.