I have a table and I listen for double click on a table cell. If user double click on a cell that cell becomes editable. I am looking for how to revert the "edit" state once the user clicks outside the cell (anywhere else on the page). The code I have so far is working for entering the "edit" mode:
$('table tbody tr td').dblclick(function(){
var cell=$(this)
var value=cell.text();
var rowIndex = cell.parent().index('table tbody tr');
var tdIndex = cell.index('table tbody tr:eq('+rowIndex+') td');
//my logic on editing
//the event handling if I click outside of that `cell`
});
The code I miss should be triggered only if there is a cell being edited, shouldn't interfere with other click events on the page. How can I accomplish this?
You can attach a click event listener to the document that checks whether one of the table cells contains the event target. If not, you know the click event was not directed towards the table cell, and you can perform the logic to disable editing:
const tableCells = $('table tbody tr td')
tableCells.dblclick(function() {
$(this).attr('contenteditable', 'true').focus();
});
$(document).click(function(e) {
if (!tableCells.toArray().some(f => f.contains(e.target))) {
tableCells.removeAttr('contenteditable');
}
})
td {
margin: 10px;
padding: 10px;
border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Hello</td>
<td>World!</td>
</tr>
</table>