Skip jQuery document.one event for certain elements
October 4th 2013
3173

document.one jquery event

So, the situation here is very straigth forward: you want to use $(document).one handler on something like pop-up settings box, which should be closed if user clicks anywhere outside of it. But what if the settings box in question has some elements inside it that need a separate handling and should keep the box open?

Preferably, you would like to skip the document.one call for that particular element (or group of elements). 

Here’s a little visual preview: 

Once bell icon is pressed you would attach the document.one event handler as follows:

The result would be an open box (as in the image) which would close if user clicks anywhere on the window, including the text inside the box, which can work as links too. Note that clicking a link will close the box and execute the link too, that is the natural behaviour.

Now note those little crosses on the right hand side of the image. What if we want those crosses to be the links that would remove the alert from the list without closing the box? Let’s say each of these grey X’s got a class ’alert_remove’ attached to them. We just need to attach the event listener to the class in this way:

And the problem disappears! Now once the ’X’ is clicked the whole alert line will be removed with the box still open. Note that document.one event is still in waiting and will be activated the next time you click anywhere but those grey X’s.

So that would be it for this time. As always, happy coding and feel free to use the comment section below if you have any questions.

SD

Back To Blog