Search code examples
javascriptgetuikit

GetUIkIt 3 Notification Close event?


I need to know when a UIKit notification has been closed.

The UIkit notification plugin (https://getuikit.com/docs/notification) mentions that it has a close event. Is it possible to use this for instances triggered programatically?

e.g.

UIkit.notification({
    message: 'my-message!',
    status: 'primary',
    timeout: null
});
UIKit.o

I've tried putting the nofication on a variable, (as suggested https://getuikit.com/docs/javascript#programmatic-use, where it even states You'll receive the initialized component as return value - but you don't)

let foo = UIkit.notification('message'); // foo is undefined

I've tried chaining the on method

UIkit.notification.on('close', function() { ... }); // on is undefined

but the .on method is part of UIkit.util.on($el, event, fn) and there is no $el when calling notification programatically.

The only other way I can think of doing it is putting a mutation observer onto the body and watching to the notification element to change state, but this seems like overkill.


Solution

  • You can store a handle to the notification...

    warning_notification = UIkit.notification({message: 'Warning message...',
                                               status: 'warning', timeout: 1000});
    

    ... and check if this is the origin of the close event:

    UIkit.util.on(document, 'close', function(evt) {
      if (evt.detail[0] === warning_notification) {
        alert('Warning notification closed');
      }
    });
    

    Now, you will only see the alert when exactly this notification was closed.

    Check out this demo.