I have 2 divs which can receive pasted text. They are not editable. How can I visually indicate which one will receive the paste event?
I tried using :focus
, but it does nothing by default for div
s. I added tabindex
to the div, and then :focus
worked, but if I click outside the div, it losses the focus attribute but still receives the pasted text
document.querySelectorAll("div").forEach(element => {
element.addEventListener("paste", event => {
event.preventDefault();
const text = (event.clipboardData || window.clipboardData).getData("text");
const words = text.split(' ').join('n');
event.currentTarget.innerText = words;
}
)
});
<div>aaa</div>
<div>bbb</div>
3
Answers
You could simply add a border to the div to make it obvious. If you have a dedicated CSS file:
You can play around with the color/thickness of the border but you probably want something a little more subtle.
Inline:
You will need to set the style dynamically when the element is selected.
You can’t get focused on DIV elements out of "onpaste" event listener. You have to create a null or hidden div "lastHiddenDIV" and add it to "onpaste" event listener but prevent it from updating it’s innerHTML using IF statement.
and put them in a DIV as parent with CSS=overflow:hidden;
HTML:
JavaScript:
Take a look at this and see if it might help you.
You can only paste text if a div is focused.
If no div is selected, the text will not be pasted.
The div that is focused on will be highlighted with a distinct border.