Reputation: 16251
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?
Upvotes: 7
Views: 5214
Reputation: 2840
If you are writing a jupyter lab widget, you can get the cell index by iterating the widget
array. This is what jupyter lab internally does (source).
const cellIndex = ArrayExt.findFirstIndex(
notebook.content.widgets,
widget => widget.node === this.originalCell.node
);
Then you can assign the new active cell by changing the activeCellIndex
property of the notebook widget:
notebook.content.activeCellIndex = cellIndex;
Upvotes: 1
Reputation: 31
In the case of executing javascript with display(HTML("javascript code"))
, this
will return the Window object.
So you should use display(Javascript("javascript code"))
to get the current cells' output_area.
Upvotes: 2
Reputation: 38608
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);
Upvotes: 7