How to remove eventlistener after popup is closed?

I have a form in a popup and I want to submit it when I click Enter on the keyboard, and this works when the popup is opened. If I just click Enter as soon as the page loads, the event is not running, since I don´t add the eventlistner until the popup is opened. So this is good.

  1. BUT, if I click Enter when the popup is closed then I still get the console.log("enter is clicked") in the below code. It is not running document.getElementById("tabsok-link").click();so why is it showing the enter is clicked in the console?

  2. If I open the popup for the second time and click Enter then it is bubbling/looping so it shows the console.log("enter is clicked") 2 times, and if I open it a third time it show console.log("enter is clicked") 3 times and so on. So Im trying to remove the eventlistner when the popup is closed but it still runs the "keydown" event if I click Enter when the popup is closed. How can I prevent the Enter event to work if the popup is closed?

     var tabsPopup = app.popup.create({
       closeByBackdropClick: true,
       swipeToClose: true,
       backdrop : false,
       closeOnEscape : true,
       swipeHandler: '.min-swipe-to-close-handler',
       content: '<div class="popup">'+			
     				datan +	 
                 '</div>',
       // Events
       on: {
         open: function (popup) {
          	
     		if(tabsPopup.opened){
     			console.log("popup is opened")
     			
     		
     		document.addEventListener("keydown", function(event) {
     		  // Number 13 is the "Enter" key on the keyboard
     		  if (event.keyCode === 13) {
    
     			// Trigger the button element with a click
     			document.getElementById("tabsok-link").click();
     			console.log("enter is clicked")
     			event.preventDefault();
     			event.stopPropagation();
          		 return false;
     			
     		  }
     		});
     		
     		}
         },
         opened: function (popup) {
          //console.log('Popup opened');
         },
     	closed: function (popup) {
     	animate: false;
           console.log('Popup is closing');
     	
         },
     	closed: function (popup) {
     	document.removeEventListener("keydown", function(tabsPopup) {
     		console.log('keydown event removed')
     	});
          console.log('Popup is closed');
     	 tabsPopup.destroy()
         },
       }
     });
    

So how to prevent the keydown event to work if the popup is closed? Thanks.

If you want to remove event you should store function callbacks of events in a variable , ex:

let myFunc = function(event) {
if (event.keyCode === 13) {

		// Trigger the button element with a click
		document.getElementById("tabsok-link").click();
		console.log("enter is clicked")
		event.preventDefault();
		event.stopPropagation();
  		 return false;
		
	  }

then:
document.addEventListener("keydown", myFunc)
or
document.removeEventListener("keydown", myFunc)

Thanks a lot Ars_Rza, it works great!