Within a text box I want my cursor to be set where I click (‘mouseup’). However the cursor doesn’t change when clicking the mouse, I can only move it using the keyboard, am I somehow disabling the mouseclicks?
Here’s the snippet …
textarea.addEventListener('mouseup', function(e) {
e.stopPropagation();
const pos = textarea.selectionStart;
textarea.focus();
textarea.setSelectionRange(pos, pos);
});
If I’m not mistaken the above code should work, can anyone see where I am going wrong?
The full function code is below.
function makeEditable(element) {
const text = element.textContent;
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.classList.add('edit-textarea');
// Set initial height
textarea.style.height = 'auto';
textarea.style.height = element.offsetHeight + 'px';
// Replace the span with the textarea
element.parentNode.replaceChild(textarea, element);
// Focus and select all text
textarea.focus();
// Handle input for auto-resizing
textarea.addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + 'px';
});
// Handle blur event to save the text
textarea.addEventListener('blur', function() {
saveEdit(this, element);
});
// Handle keydown event to detect Enter key
textarea.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.blur();
}
});
// Prevent double-click event from being triggered again
textarea.addEventListener('dblclick', function(e) {
e.stopPropagation();
});
// Allow single clicks for cursor positioning
textarea.addEventListener('mousedown', function(e) {
e.stopPropagation();
});
// Set cursor position based on click location
textarea.addEventListener('mouseup', function(e) {
e.stopPropagation();
const pos = textarea.selectionStart;
textarea.focus();
textarea.setSelectionRange(pos, pos);
});
}
1