4

Suppose I have two textarea html elements and what I type in one shows in the other.

Is there a javascript event that will fire when the correct word is selected on the screenshot below?

image1

suchislife
  • 4,251
  • 10
  • 47
  • 78
  • 1
    Correct word selected in the right-click menu? – 0stone0 Mar 07 '21 at 17:00
  • On click of the correct word, trigger event. – suchislife Mar 07 '21 at 17:01
  • 3
    You can't really do that, but what you can do is listen to the change event on the textbox, and if some word has changed from the previous value, you can kinda detect it like that... – dev-cyprium Mar 07 '21 at 17:02
  • On `contextmenu`, you can save the actual textarea value and set a flag like `contextmenuOpen = true`... Then on `change` if `contextmenuOpen` is true and the prev value is different than the actual value... Something like this would do. ;) – Louys Patrice Bessette Mar 07 '21 at 17:11

2 Answers2

3

There's no way to get this from the event. You can write your own 'logic' to detect any words changes by checking the change event.

Small example using the split() and filter() functions to check the changed word:

function inputChange(event, oldvalue) {

    // Old words
    const old = oldvalue.split(' ');
    
    // Current words
    const curr = event.target.value.split(' ');
    
    // Changed words
    const diff = old.filter(x => !curr.includes(x));
    
    // For each changed word
    for (let changeId in diff) {
    
      // Diff
      console.log('Word changed: ', diff[changeId]);
      
      // Optionally, you can get the same index, so you'll know the new value
      const ind = old.indexOf(diff[changeId]);
      console.log('New value: ', curr[ind]);
    } 
}
input { width: 300px; }
<input type='textarea' value='Test txt. Correct this: hoube -> house' onfocus="this.oldvalue = this.value;" onchange="inputChange(event, oldvalue)" />

0stone0
  • 34,288
  • 4
  • 39
  • 64
1

Try using the contextmenu and the change events toguether like this:

let testElement = document.querySelector("#test");
let contextmenuOpened = false;
let prevValue = "";

testElement.addEventListener("contextmenu", function(){
  contextmenuOpened = true;
  prevValue = this.value;
})

testElement.addEventListener("change", function(){

  if(contextmenuOpened && prevValue !== this.value){
    console.log("Correction made from the contextmenu")
  }
  
  contextmenuOpened = false;
  prevValue = "";
})
<textarea id="test">Helllo Worrld!</textarea>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64