killajoule
killajoule

Reputation: 3832

Attach an event listener with event delegation to Jupyter notebook?

I am trying to attach an event to Jupyter notebook variables (for some experiments):

$( "#notebook-container" ).on( "dblclick", ".cm-variable", function( event ) { alert("hi"); });

As Jupyter notebook variables are constantly refreshed/etc, I thought the best way to attach an event handler to all variables would be via jquery event delegation: https://learn.jquery.com/events/event-delegation/

"Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future."

So I felt that was the right fit, however, if I paste the line of code I shared above, into the js console, I am not getting the desired effect.

I am wondering what is the correct way to do this, you can access a live jupyter notebook here: https://try.jupyter.org/

Upvotes: 0

Views: 824

Answers (1)

Louise Davies
Louise Davies

Reputation: 15971

Based on this answer, here's how you can simulate a double click using mousedown/mouseup (mouseup is probably better, since click is fired after the user lifts their mouse and not when they first press it)

var clicks = 0, delay = 400;
$("#notebook-container").on("mouseup", ".cm-variable", function(event) {
    event.preventDefault();
    clicks++;

    setTimeout(function() {
        clicks = 0;
    }, delay);

    if (clicks === 2) {
        clicks = 0;
        alert("hi");
        return;
    }
});

Upvotes: 1

Related Questions