window.getSelection() in JavaScript - The torment of text selection

I talk about how I am implementing a functionality for text selection in JavaScript and being able to perform text highlighting and a note.

I'm going to explain something to you that I think you'll find very interesting: when the user selects a text, you can set options such as highlighting the text and adding a note; for this, there is a function in JS:

window.getSelection();

To test the above method, open a browser window, the developer console, select some text on the web page and then run the above line of code and you will see a greeting like the following:

Selection {anchorNode: text, anchorOffset: 9, focusNode: text, focusOffset: 47, isCollapsed: false, …}
anchorNode
: 
text
anchorOffset
: 
9
baseNode
: 
text
baseOffset
: 
9
extentNode
: 
text
extentOffset
: 
47
focusNode
: 
text
focusOffset
: 
47
isCollapsed
: 
false
rangeCount
: 
1
type
: 
"Range"

In my case, I use it to draw a bubble with the option to create a comment:

const rect = rango.getBoundingClientRect();

posX = rect.left + window.scrollX;
posY = rect.top + window.scrollY - 40;

Problems with window.getSelection();

The main problem with using window.getSelection(); is that if we don't have a clean paragraph like the following:

<p id="p_1739646025565_337622">Laravel, al igua<span title="Test" id="_p_1739646025565_337622" class="bg-purple-700 rounded-sm no-set-note text-white">l que otros frame</span>works, puede&nbsp;ejecutarse en diversos entornos tanto en ambiente de producción como de desarrollo:</p>

If not something like:

<p id="p_1739646025565_337622">Laravel, al igua<span title="Test" id="_p_1739646025565_337622" class="bg-purple-700 rounded-sm no-set-note text-white">l que otros frame</span>works, <span id="span_1739646025565_102820">puede&nbsp;ejecutarse en diversos entornos tanto en ambiente de producción como de desarrollo:</span></p>

And if for example, we want to select the text from “various environments both in ambien”, that is, the text right next to the SPAN, the defined range will be from the SPAN and not from the entire paragraph, therefore, any operation we want to do, the position will be linked to the SPAN and not to the paragraph, which is a big problem since it is not possible, at least in a simple way, to be able to create the ranges from the paragraph.

Regain the rank

The range must be recorded if we wish to be able to create the same order, to do so:

this.$axios
.post(this.$root.urls.bsnCreate + this.section.id, {
  title: this.form.title,
  content: this.form.content,
  json: {
    text: this.bubbleSelectecOptions.selectionText.substring(0, 10),
    id: this.bubbleSelectecOptions.selectionId, // Guarda el ID del elemento padre
    start: this.bubbleSelectecOptions.selectionRangeStart,
    end: this.bubbleSelectecOptions.selectionRangeEnd
  }

And to build or rebuild it:

async addHighlights(id, start, end, noteTitle, noteContent) {
  // const node = document.querySelector("#" + id).firstChild.nodeValue
  if (id.trim() == "")
    return this.$toast.warning(this.$t('large.noteBookRangeNoValid'))

  const node = document.querySelector("#" + id).firstChild
  const rango = document.createRange();

  try {
    rango.setStart(node, start);
    rango.setEnd(node, end);

    const span = document.createElement("span");
    span.title = noteTitle;
    span.id = "_" + id;

    span.onclick = function () {
      this.bubbleSelectecOptions.titleNote = noteTitle
      this.bubbleSelectecOptions.contentNote = noteContent
      this.bubbleSelectecOptions.showModalNoteUser = true
      this.bubbleSelectecOptions.modalKey3 = Date()
    }.bind(this);

    span.className = "bg-purple-700 rounded-sm no-set-note text-white";

    rango.surroundContents(span);
  } catch (error) {
    console.error(error)
  }

},

- Andrés Cruz

En español

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.

!Courses from!

10$

On Udemy

There are 1d 13:59!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

View books
¡Become an affiliate on Gumroad!