Jquery:One

.One event listener in jquery detaches itself from DOM after it has been executed. This lovely piece of event listener is not so popular and has limited use cases. During my development I found one of the scenario where it can be of good use.

Custom popups and drop downs are very popular in web sites. Since they are custom components they actually don’t behave like regular alert boxes and select list, and some of the UI calls need to be handled manually. One of them is to close them when users clicks outside their ROI (Region Of Interest).

mouseout can be a possible solution, but sometimes we want to be really sure and we demand a click from user to deactivate the popups. But with a view that, clicking on the custom container and its child items should not deactivate it.

So here we go.

See the Pen huJer by Sanket Mehta (@sanketmehta7) on CodePen.

Here we have assigned click events to all iActivate buttons. Which opens their respective popups. Apart from that it also creates ONE event listener for body, which listens to click event, in case click happens on any part of your body it tries to find its parent. If at all parent of the target element is having class .iAmParent, it restricts the current opened popup from closing otherwise it just closes the popup.

Don’t forget to miss event.stopPropagation
Since your click event to open the popup bubbles up and .one event gets fired and gets expired.

Hope you find this use case interesting, if you have any more such scenarios where .one event is useful, do write down in comment or mail me. Till then good bye.

You may also like

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *