Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to hide multiple elements on click outside?

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?

like image 581
pilau Avatar asked Nov 28 '25 02:11

pilau


1 Answers

Assume:

  1. Those elements are show/hide by javascript.

  2. 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) {
    ...
}
like image 113
benbai123 Avatar answered Nov 30 '25 17:11

benbai123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!