简体   繁体   中英

How to hide a section when click outside the section in my HTML page?

Please check it. Here is the Fiddle: http://jsfiddle.net/4467yz37/

When I do click in the Link it works good ( Show and Hide ). The only problem existing it's when I want to hide the Items section doing click outside the Link and the Items (that is in the Body except in the Items section).

Here is the JavaScript code:

(function(document) {    
    var alterNav = function() {
        var item = document.querySelector('.items');
        var link = document.querySelector('.clickme');
        var theClass = 'display';
        var itemIsOpened = false;

        if (link) {
            link.addEventListener('click', function (event) {
                event.preventDefault();

                if (!itemIsOpened) {
                    itemIsOpened = true;
                    addClass(item, theClass);
                } else {
                    itemIsOpened = false;
                    removeClass(item, theClass);
                }
            });
        }
    };    

    var addClass = function (element, className) {
        if (!element) {
            return;
        }
        element.className = element.className.replace(/\s+$/gi, '') + ' ' + className;
    };

    var removeClass = function(element, className) {
        if (!element) {
            return;
        }
        element.className = element.className.replace(className, '');
    };    

    alterNav();
})(document);

I try to solve it creating another variable with the tag Html or Body and alter the JS code, but it still don't working good: http://jsfiddle.net/g1d321rv/2/

var link = document.querySelector('body');

I manipulated your code a bit. Do you use jquery? I assumend that you are not using jquery.Here jsfiddle :

  • http://jsfiddle.net/9fpf07mt/

     window.onclick = function (e) { console.log(e); if (!itemIsOpened) { if (e.target == link) { itemIsOpened = true; addClass(item, theClass); } } else { if (!isChild(e.target, item)) { itemIsOpened = false; removeClass(item, theClass); } } }; 

edit for last request:

link.addEventListener('click', function (event) {
                event.preventDefault();
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM