Brajmohan Rajput
Brajmohan Rajput

Reputation: 7

hide menu when click anywhere in page

I have a left menu and when I click it appears and there is a cross button with id close-button when I clicked on it, menu disappears, I need to close also when click anywhere except menu.
site link

(function() {
    var bodyEl = document.body,
    content = document.querySelector( '.content-wrap' ),
    openbtn = document.getElementById( 'open-button' ),
    closebtn = document.getElementById( 'close-button' ),

    isOpen = false;


function init() {
    initEvents();
}

function initEvents() {
    openbtn.addEventListener( 'click', toggleMenu );

    //bodyEl.addEventListener( 'click', toggleMenu ); //

    if( closebtn ) {
        closebtn.addEventListener( 'click', toggleMenu );
    }
    // close the menu element if the target it´s not the menu element or one of its descendants..
    /**content.addEventListener( 'click', function(ev) {
        var target = ev.target;
        if( isOpen && target !== openbtn ) {
            toggleMenu();
        }
    } ); */
}

function toggleMenu() {
    if( isOpen ) {
        classie.remove( bodyEl, 'show-menu' );
    }
    else {
        classie.add( bodyEl, 'show-menu' );
    }
    isOpen = !isOpen;
}

init();

})();

Upvotes: 1

Views: 4552

Answers (4)

Tom
Tom

Reputation: 93

Simply bind a click event to the body to close the menu. Then use event.stopPropagation(); on click of the menu.

Upvotes: 0

Dharmesh Kumar Laxkar
Dharmesh Kumar Laxkar

Reputation: 411

code look like this

$('body').on('click', function (e) {
            // hide any open popovers when the anywhere else in the body is clicked
            if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.menu-element').has(e.target).length === 0 && $(this).is(":visible")) {
                var target=$("#popupDiv_id").hide();
            }


    });

Upvotes: 0

Frederik
Frederik

Reputation: 57

If I understand the problem correct you can use the onblur="toggleMenu();" to run the javascript function when the element looses focus. It is the opposite of the onfocus()event.

<div class="menu-element" onblur="toggleMenu();"/>

Can also add the eventlistner in the javascript:

    var x = document.getElementById("menu-wrap");
    x.addEventListener("blur", toggleMenu, true);

There is some examples of it here: https://www.w3schools.com/jsref/event_onblur.asp

Upvotes: 0

shubham agrawal
shubham agrawal

Reputation: 3541

You'd better go with something like this. Just give an id to the div which you want to hide and make a function like this.Call this function by adding onclick event on document.

document.onClick=myFunction(event) { 

if(event.target.id!="popupDiv_id" || event.target.id=="closeButton_Id")
{ 
    document.getElementById("popupDiv_id").style.display="none";
  }
}

Upvotes: 2

Related Questions