For introduction I would like to explain what I try to achieve:
Inside the div#content I would like to detect ‘keydown’ events AND get the element for which the keydown element is detected. For example TAB inside the paragraph “Coding is…” should return the… element and key pressed.
<!-- HTML -->
<div id="content"> <!-- div container keeps HTML element wich are toggled from editable to non-editable-->
<p id="paragraph">Coding is fun.</p>
<!-- ...bunch of further html element-->
</div>
<button id="buttonEditable">toggleEditable</button>
//javascript
const buttonEditable = document.getElementById("buttonEditable");
const contentDiv = document.getElementById("content");
const paragraph = document.getElementById('paragraph');
paragraph.addEventListener('keydown',keydown);
function keydown(){
console.log(event.key); // should return TAB
console.log(event.target); //should return paragraph element
}
buttonEditable.addEventListener('click',toggleEditable);
function toggleEditable(){
if(contentDiv.contentEditable === 'false'){
contentDiv.contentEditable = true;
} else {
contentDiv.contentEditable = false;
};
}
I made the following investigation. ‘keydown’ events are only detectable for elements whicht have the attribute contentEditable = true . By the way ‘click’ events are detectable for no-matter the contentEditable attribute is set to.
When add contenteditable = true to the html code. It works… TAB keydown inside paragraph is detected
<div id="content">
<p id="paragraph" contenteditable="true">Coding is fun.</p> <!-- <<<<<<<<<<-------contenteditable added -->
</div>
<button id="buttonEditable">toggleEditable</button>
Does somebody know a way how the TAB keydown AND element can be detected by the paragraph which inherits contenteditable = “true”?
Of course with a queryselector I could assign assign contenteditable attribute to any element inside div#content but this seems not very elegant to me