0

What I'm trying to do. I have web page that has a log area

.log {
  padding: 5px;
  background: #CCF;
  max-height: 50px;
  overflow: auto;
}
.log pre {
  margin: 0;
}
<p>
some text
<p>
<div class="log">
  <pre>some</pre>
  <pre>logged</pre>
  <pre>text</pre>
  <pre>that</pre>
  <pre>is</pre>
  <pre>hundreds</pre>
  <pre>of</pre>
  <pre>lines</pre>
  <pre>long</pre>
</div>

I don't want prevent the user from selecting text outside the log (eg "some text" above) but I do want to check if they pick "select all" either via the keyboard, app menus, or context menu, and if the focus is on the log area then I want to select all for only the log area. Copying the log area would be way more common than copying all the content even outside of the log. Note: the behavior I'm trying to replicate is no different than a textarea. If the textarea has the focus and you choose select all only the content of the textarea is selected but you can still select the entire document including the area outside the textarea if you want.

I can't make my log a textarea since I'm formatting it with multiple elements.

Forcing the user to scroll to one end of the log and drag select or shift select to the bottom is not a good UX.

One possibility is to mark that area as contenteditable though I don't really want to confuse the user by making the log itself editable.

I can't just check for Ctrl-A AFAIK as that won't cover using the menus.

I'm surprised I didn't find an answer to this question already but maybe my search-fu is weak.

gman
  • 100,619
  • 31
  • 269
  • 393
  • I just double click the first word, scroll down and shift click the last, THEN hit ctrl-c – mplungjan Sep 14 '20 at 09:37
  • The dupe works great - you do not have to set it content-editable from the start, just while accessing the div – mplungjan Sep 14 '20 at 09:40
  • It's about Selection API (https://developer.mozilla.org/en-US/docs/Web/API/Selection). See this SO answer: https://stackoverflow.com/questions/62566550/is-there-a-way-to-detect-users-select-all-content – Samuli Hakoniemi Sep 14 '20 at 09:40
  • I found [more dupes](https://www.google.com/search?q=ctrl-a+div+site:stackoverflow.com) – mplungjan Sep 14 '20 at 09:40
  • @Salumi, that is not dupe. I saw that answer. It only works with a textarea. Even the MDN docs you linked to explicitly state that select events only work in textarea and input type=text – gman Sep 14 '20 at 09:44
  • 1
    @mplungjan, thanks. I didn't think to search for Ctrl-A since I'm not trying to handle only Ctrl+A but the first linked solution works. Yay! – gman Sep 14 '20 at 09:46

0 Answers0