javascriptsweetalert2

SweetAlert2 Disappearing when Triggered from Pressing Return


I am using a document.onkeydown to fire when Return is pressed when an element has been tabbed to:

Update:

function detectspecialkeys(e) {
  var evtobj=window.event? event : e; //distinguish between explicit event object (window.event) & implicit
  console.log('Event: ' , evtobj);
  console.log('Code: ' + evtobj.code);
  console.log('Repeat: ' + evtobj.repeat);
  if (evtobj.repeat) {return}
  if ((code==='Space') || (code==='Enter')) { // Space or Return (code:Enter)
    console.log('EObj-Sp/Return: ' , evtobj.target);
    if (evtobj.target.nodeName == 'BUTTON') {
      console.log('Inside Button'); // only see once
      var selid = '#' + evtobj.target.id;
    }
    $(#selid).trigger('singletap');
  }
}
document.onkeydown=detectspecialkeys;

I'm using jQuery Touch Events to handle interactions.

I'm using this version of Sweet Alert2: https://rahulbhut21.github.io/SweetAlert2/

I can see my handler firing and see the console.log ok:

$('#selid').on('singletap', function(e) {
  console.log('Inside Singletap'); // only see once
  e.preventDefault();
  swal('Test').catch(swal.noop);
  return false;  
});

When I click on #selid, the SweetAlert 2 alert shows fine, but when using the keyboard Return, it flashes and then disappears. I've tried to implement suggestions mentioned elsewhere, but the alert is still disappearing.


Solution

  • The detectspecialkeys function just needed:

    evtobj.preventDefault();
    evtobj.stopPropagation();
    

    I believe this was needed as the click event was probably clicking outside of the SweetAlert modal on a parent, due to propagation and thus immediately closing it.