0

Let me start this off with I'm working with someone else's code and am still relatively new to jquery/javascript. I am also using classie.js from another file. If any of this code can be improved please let me know - I am still learning.

I would post html but it's rather long. If it's an issue let me know and I will try and get a live version of my site up.

I'm trying to toggle a mobile menu with two different open buttons: sticky-open-button and open-button.

It works fine right up until I go to close the menu element if the target is not the menu element or one of its descendants. Then it will ONLY let openbtn open the menu.

Problem Code:

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

    } );
}

All code:

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

function init() {
    initEvents();
}

function initEvents() {

        openbtn.addEventListener( 'click', toggleMenu );
        stickyopenbtn.addEventListener( 'click', toggleMenu );
        if( closebtn ) {
            closebtn.addEventListener( 'click', toggleMenu );
        }

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

    } );
}

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



init(); //make onclick talk to menu



})();
1
  • The html would be helpful, perhaps you can use jsfiddle.net to get an example running. Commented Sep 10, 2015 at 3:05

1 Answer 1

3

Your OR condition is wrong as openbtn || stickyopenbtn will always return openbtn instance so the click of stickyopenbtn won't be evaluated.

content.addEventListener('click', function (ev) {
    var target = ev.target;
    if (isOpen && (target !== openbtn && target !== stickyopenbtn)) {
        toggleMenu();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.