Fortytwo
Fortytwo

Reputation: 127

Disable/enable a EventListener

I want to disable the event listener when an element is focused on and renable the event listener when it is focused out. How can I do this?

*//event listener execute function on paste*
document.addEventListener('paste', function (evt) {
  pasteClipboardURL(evt); 
});

*//on focus disable event listener paste event and function*
$('#input-url').on('focus', function (url) {
  *//disable document.addEventListener('paste', function (evt)*
});

$('#input-url').on('focusout', function (url) {
  *//enable document.addEventListener('paste', function (evt)*
});

Upvotes: 2

Views: 885

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

Rather than dynamically adding/removing listeners, I'd prefer to set a flag which gets toggled on focus or focusout, and check that flag in the main listener:

let focused = false;
$(document).on('paste', (e) => {
  if (!focused) pasteClipboardURL(e);
});
$('#input-url')
  .on('focus', () => focused = true)
  .on('focusout', () => focused = false);

const pasteClipboardURL = () => console.log('pasteClipboardURL');
let focused = false;
$(document).on('paste', (e) => {
  if (!focused) pasteClipboardURL(e);
});
$('#input-url')
  .on('focus', () => focused = true)
  .on('focusout', () => focused = false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="some other input">
<input id="input-url" placeholder="input-url">
<input placeholder="some other input">

You can also listen for a paste event on the input and use stopPropagation on the event, so that the document listener doesn't see it:

const pasteClipboardURL = () => console.log('pasteClipboardURL');
$(document).on('paste', pasteClipboardURL);
$('#input-url').on('paste', e => e.stopPropagation());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="some other input">
<input id="input-url" placeholder="input-url">
<input placeholder="some other input">

Upvotes: 2

Related Questions