Most efficient way to hide multiple elements when clicked outside?

Ok, so we all know this way of hiding an element (and multiple elements) when clicked outside of it (i.e. the element loses focus):

$('document').on('click', function () { $(element).hide(); });

$(element).on('click', function (e) { e.stopPropagation(); /* ka-chow! */ });

      

The value of 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.

This is all good and good, and definitely not news.

However, I have a complex and rich interface. This interface has many elements that require this kind of behavior. Suppose only one element needs to be hidden at each event. Do I have to iterate over the entire batch each time to find the one element I want to hide?

If this is the most efficient way to do it? Give them all a unique class name? Or store every classname / ID / DOM instance in an array and every loop? Each solution sounds more ineffective than the other to me.

What would you do?

+3


source to share


1 answer


Let's assume:

  • These elements are displayed / hidden by javascript.

  • The rule is that it appeared later than it was hidden before.



Then I will 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) {
    ...
}

      

+1


source







All Articles