Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select current cell with JavaScript in Jupyter?

I have a notebook cell containing JavaScript code, and I would like the code to select this particular cell. Unfortunately, the behavior of get_selected_cell depends on whether I execute the cell in place, or execute and select the cell below.

Example:

%%javascript
var cell = Jupyter.notebook.get_selected_cell();
console.log(Jupyter.notebook.find_cell_index(cell));

When executing this cell, the console output will be different whether I execute with Ctrl+Enter or Shift+Enter. In one case it logs the index of the cell that contains the JavaScript code, in the other the index of the cell below.

Is there a way to select the cell I want?

like image 286
IanS Avatar asked Sep 21 '16 10:09

IanS


People also ask

How do you select specific cells in a Jupyter Notebook?

Select Multiple Cells: Shift + J or Shift + Down selects the next sell in a downwards direction. You can also select sells in an upwards direction by using Shift + K or Shift + Up . Once cells are selected, you can then delete / copy / cut / paste / run them as a batch.

Can you use JavaScript in Jupyter Notebook?

Jupyter Notebooks are documents that contain a mix of live code (Python, R, Julia, JavaScript, and more), visualizations, and narrative text (Markdown). They're useful for breaking down concepts in a story telling form, where you can give some context and show the code below along with interactive visualizations.

What does %% do in Jupyter Notebook?

Both ! and % allow you to run shell commands from a Jupyter notebook. % is provided by the IPython kernel and allows you to run "magic commands", many of which include well-known shell commands. ! , provided by Jupyter, allows shell commands to be run within cells.


1 Answers

Your Javascript will have a handle on the OutputArea applying the Javascript, but not one all the way to the cell (in general, output areas can be used without cells or notebooks). You can find the cell by identifying the parent .cell element, and then getting the cell corresponding to that element:

%%javascript
var output_area = this;
// find my cell element
var cell_element = output_area.element.parents('.cell');
// which cell is it?
var cell_idx = Jupyter.notebook.get_cell_elements().index(cell_element);
// get the cell object
var cell = Jupyter.notebook.get_cell(cell_idx);
like image 74
minrk Avatar answered Nov 09 '22 23:11

minrk