hide or not to hide?

browsereventdefault action ⟩ example ⟩ hide or not to hide?

function
const {log} = console;

// ⭐️ import
import {$} from './js/Node+ext.js';
// -------------------------------------------

// elements
const rabbit = $('#rabbit');
const button = $('button');

// scenario A
// -------------------------------------------------------------
// 1. click the button
//
// 2. confirm dialog                          ("rabbit.onhide")
//    (confirm dialog shows BEFORE the log message, why❓)
//
// 3. click "OK"
//
// 4. dispatching "hide" event on rabbit ...  ("button.onclick")
//    (this message shows AFTER the confirm dialog, why❓)
//
// 5. default action prevented ...            ("rabbit.onhide")
// 6. "hide" event on rabbit dispatched ...   ("button.onclick")
// 7. "hiding rabbit" cancelled ...           ("button.onclick")
//
// scenario A
// -------------------------------------------------------------
// 1. click the button
// 2. confirm dialog                          ("rabbit.onhide")
// 3. click "Cancel"
// 4. dispatching "hide" event on rabbit ...  ("button.onclick")
// 5. "hide" event on rabbit dispatched ...   ("button.onclick")

// button.onclick
button.onclick = () => {
    
    // ⭐️ cancelable custom "hide" event
    let hideEvent = new CustomEvent("hide", {
      cancelable: true  // ⭐️ preventDefault doesn't work without this
    });

    // start to dispatch hide event
    log(`dispatching "hide" event on rabbit ...`);

    // ⭐️ dispatch 'hide' on rabbit and see if the event handler
    // decides to do the default actions or not.
    let doDefaults = rabbit.dispatchEvent(hideEvent);
    
    log(`"hide" event on rabbit dispatched ...`);

    if (!doDefaults) {
      log('"hiding rabbit" cancelled ...');
      return;
    }
      
    // hide the rabbit
    rabbit.hidden = true;
};

// rabbit.onhide
rabbit.addEventListener('hide', (event) => {
    if (confirm("Cancel hidding?")) {

      // By calling event.preventDefault(), an event handler 
      // may send a signal to cancel default actions.

      // ⭐️ In this case, elem.dispatchEvent(event) returns false❗️
      //    "Don't do default actions."
      event.preventDefault();

      log('default action prevented ...');
    }
});

Last updated