The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Automatically Select-All When Clicking On A Content Editable Element

TODO: Pull subtitle into page object

Overview

I'm working on a tool to make ascii art. One feature I'm after is the ability to auto select a character when I click on it. This is the code I'm using for that.

Example HTML

Here's the example along with the HTML that makes it

Draw the chart
Fasten two pins

The Script

And this is the function that makes things happen:

Notes

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Automatically Select-All When Clicking On A Content Editable Element

-- h2

Overview

I'm working on a tool to make ascii art. One feature I'm 
after is the ability to auto select a character when I click
on it. This is the code I'm using for that. 

-- h2

Example HTML

Here's the example along with the HTML that
makes it

-- html

<div id="tango">Draw the chart</div>
<div id="sierra">Fasten two pins</div>

-- h2

The Script

And this is the function that makes things 
happen:

-- script

const focusOnClick = (event) => {

  event.srcElement.contentEditable = true

  const selection = window.getSelection();

  selection.removeAllRanges();

  const range = document.createRange()

  range.selectNodeContents(event.srcElement)

  selection.addRange(range)

}


const init = () => {

  tango.addEventListener("click", focusOnClick)

  sierra.addEventListener("click", focusOnClick)

}

document.addEventListener("DOMContentLoaded", init)


-- notes

- If you click on the _Draw the chart__ or
_Fasten two pins__ lines in the Example
section you'll see the behavior

- I tested this on a mac in safari, firefox, and
chrome

- The main thing is the _focusOnClick__ handler. I'm 
attaching them through the _init__ function. Other
methods would work just as well


-- ref
-- title: Range: selectNodeContents() method
-- subtitle: sets the Range to contain the contents of a Node
-- url: https://developer.mozilla.org/en-US/docs/Web/API/Range/selectNodeContents


-- ref
-- title: contenteditable
-- subtitle: an enumerated attribute indicating if the element should be editable by the user (MDN)
-- url: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable


-- categories
-- JavaScript 
-- WebDev

-- metadata
-- date: 2023-08-05 12:22:21
-- id: 2tzzpnob
-- site: aws
-- type: post
-- status: draft