Delay execution after eventlistener is triggered

Viewed 1998

I'm new to javascript, and have a lot of confusions... I'm trying to write a script in Tampermonkey which would allow to put the cursor at the end of the input area once "copy" event listener is triggered. This is the site where I want to apply it: https://voicenotebook.com/#medtrdiv The original code is:

var input = document.querySelector('#docel');
var textarea = document.querySelector('#docel');
var reset = function (e) {
   var len = this.value.length;
    this.setSelectionRange(len, len);
};
input.addEventListener('copy', reset, false);
textarea.addEventListener('copy', reset, false);

The problem is that if I click copy, it doesn't copy the text, though it puts the cursor at the end. So I guess the problem is that the function executes too soon.

I wanted to add some delay to this function, but nothing seems to work. So I think the solution would be to delay the function by 100ms once an eventlistener is triggered. This is what I tried:

var input = document.querySelector('#docel');
 var textarea = document.querySelector('#docel');
     var reset = function (e) {
     var len = this.value.length;
     this.setSelectionRange(len, len);
  };
 textarea.addEventListener('copy', setTimeout(reset, 100), false);
 input.addEventListener('copy', setTimeout(reset, 100), false);

I know this probably doesn't make sense at all. I've tried different things also. I've researched many topics about this, but nothing works for me. Can you please help me to figure it out? Thank you in advance!

1 Answers

There are couple of issues in the code you have written.

  • id is supposed to be unique on the page.

  • You intent is to delay the setSelectionRange. This happens when the copy event is triggered. Move the setTimeout to inside the reset function.

  • Also you if you want to select the text from the start your first argument should be 0.

Your event gets triggered sometime in the future and wrapping reset function reference in the event handler really does nothing other than binding the event handler.

var input = document.querySelector('#docel1');
var textarea = document.querySelector('#docel2');

var reset = function(e) {
 var context = this;
  
  setTimeout(function() {
    var len = context.value.length;
    context.setSelectionRange(0, len);
  }, 100);
};

input.addEventListener('copy', reset, false);
textarea.addEventListener('copy', reset, false);
<input id="docel1" />
<textarea id="docel2" />

Related