I am trying to allow the user to click on a span element and change the text according to what they type along with the original textcontent.
container.addEventListener('click', (event) => {
if (event.target.classList.contains('targetSpan')){
targetSpanText = event.target.textContent;
document.addEventListener("keydown", (event) => {
targetSpanText.textContent = `${event.key}`;
});
}
});
The textcontent does not seem to update, although the the keydown event listener is working.
CodePudding user response:
Using the contenteditable
attribute seems fitting in this case:
/* Just some styles for this snippet */ .targetSpan { background-color: hsla(0, 0%, 50%, 0.15); font-family: sans-serif; font-size: 1.5rem; padding: 0.25rem; }
<span contenteditable="plaintext-only">You can type here</span>
Here's a second example (prompted by this comment) with a checkbox control for toggling a simulation of plaintext mode:
const span = document.getElementById('text');
const input = document.querySelector('#toggle');
const setPlaintext = () => {
span.textContent = span.textContent;
};
const update = () => {
if (input.checked) setPlaintext();
};
input.addEventListener('change', update);
span.addEventListener('input', update);
/* Just some styles for this snippet */ body { font-family: sans-serif; } #text { background-color: hsla(0, 0%, 50%, 0.15); font-size: 1.5rem; padding: 0.25rem; }
<label><input id="toggle" type="checkbox" /> plaintext</label> <span id="text" contenteditable="true">You can type here</span>
CodePudding user response:
I think the recommendation is to use the getElementById() method of document in order to manipulate the contents of a span tag. It seems your code is not using it. Why you may not be getting the results you expect.
There's a few examples for changing the text in a span element in this post How do I change the text of a span element using JavaScript?