i want to make an Jupyter notebook-like input, where i have spans as inputs, and when the user clicks Enter a new input is added to the page and so on. the problem is the listener for click event works only on the first input. how can i make it functional on all the blocks.
$inputSpan.on('click', function() {
$inputSpan.attr('contenteditable', 'true').focus();
});
$inputSpan.on('blur', function() {
$inputSpan.removeAttr('contenteditable');
});
$inputSpan.on('keydown', function(event) {
if (event.key === 'Enter') {
if (event.shiftKey) {
// ... action for enter click
} else {
// ... end editing
$inputSpan.blur();
event.preventDefault();
add_block(); // this function append a new block to the page
}
}
});
above is the code i used.
2
Answers
Here’s how you can modify your code to use event delegation:
Assuming your input blocks are within a container element with the ID inputContainer, you can modify your code as follows:
I’ve created a runnable snippet that demonstrates the behavior you desire. Note that I have used INPUTs instead of SPANs, but this doesn’t effect how to do it / how to make it work