Search code examples
javascriptprototypejs

hide two elements on click on anywhere on the page


I am trying to hide two elements with classes notify-me and write-review, on click on anywhere on the page but not on those two elements.

How to do this using prototype?

Right now if I click on even the overlays, they are being closed.

PS: I am attaching the click event to body.


Solution

  • Try this :

    $(document).on('click', function (e) {
        var re = /(^|\s)(notify-me|write-preview)(\s|$)/;
        if (re.test($(e.target).classNames())) return false;
        $$('.notify-me', '.write-preview').invoke('hide');
    });
    

    Here is an improved version which bubbles up through the target element's ancestors :

    $(document).on('click', function (e) {
        var re, els, iterator;
        re = /(^|\s)(notify-me|write-preview)(\s|$)/;
        els = [$(e.target)].concat($(e.target).ancestors());
        iterator = function (el) { return re.test(el.classNames()); };
        if (els.find(iterator)) return false;
        $$('.notify-me', '.write-preview').invoke('hide');
    });
    

    Here is a demo : http://jsfiddle.net/wared/U7E2a/.