Okay so we all know this way of hiding an element (and multiple elements) when clicking outside of it (i.e. element loses focus):
$('document').on('click', function () { $(element).hide(); });
$(element).on('click', function (e) { e.stopPropagation(); /* ka-chow! */ });
Meaning any click event that reaches the document will hide the element, while any click inside the element will not propagate to the document and will not fire the click event.
That's all nice and well and definitely not news.
However, I have a complex and rich UI. This interface has many elements that require this sort of behavior. Let's assume only one element needs to get hidden on each event for that matter. Would I need to traverse the whole lot every time, to find the one element I want to hide?
If so what is the most efficient way to do it? Give them all a unique class name? Or store each element's classname/ID/DOM instance in an array and loop through that every time? Each solution sounds more inefficient than the other to me.
What would you do?
Assume:
Those elements are show/hide by javascript.
The rule is the later it is showed up, the earlier it is hidden.
Then I'll maintain an array to handle it, for example:
var displayedElements = [];
...
// called when you want to display an element
function showUp (ele) {
// push element into array
displayedElements.push(ele);
...
}
// called when you want to close the last displayed element
function closeOneIfAvailable () {
var len = displayedElements.length;
if (len > 0) {
var idx = len - 1;
hideIt (displayedElements[idx]);
displayedElements.splice(idx, 1);
}
}
// called when you want to hide an element
function hideIt (ele) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With