Question

Thanks for any assistance. This site has been a great resource.

My problem: When a menu is opened on a site I'm working on, I also prepend (to the body) a div overlay and give it a class that should allow it to be clickable to close the menu and remove itself. This is so that the user can click anywhere outside the menu to close it instead of requiring them to click on the "close" button. This sounds simple enough, but I can't quite get it working.

I know that there are "binding" issues since I'm adding content to the DOM, so I used .on() instead of .click(), thinking this would allow my trigger event to be bound to the newly created div. I also tried .bind(), but honestly, I'm just code-guessing at this point, since I don't understand the difference between those. I don't want to use a plugin for something that seems so simple, so I'm hoping there's some easy error that I've made that will be immediately obvious to those of you with more experience, ie all of you. ;) Here is my jQuery function. Everything works like I want except that clicking on "#the-overlay" doesn't do anything.

    $('.the-toggle').on("click", function(){
    $(".the-menu").slideToggle();
    $(".icon-chevron-sign-down").toggleClass("icon-rotate-180");

    if ($('#the-overlay').length) {
        $('#the-overlay').remove();
    }
    else {
        var content = '<div id="the-overlay" class="the-toggle"></div>';
        $('body').prepend(content);

        var docHeight = $(document).height();
        $("#the-overlay").height(docHeight);    
    }
});

Please excuse me if my question breaks the rules somehow. I did look for an answer to avoid repeats, but all the ones I could find indicated that my problem would be solved with .on() or the deprecated .live().

Thank you.

Was it helpful?

Solution

Use delegation syntax:

$(document.body).on("click",'.the-toggle', function(){...});

OTHER TIPS

Please replace your code with below code. It will work.

$(document).ready(function(e) {
    theToggle();
});
function theToggle(){
    $('.the-toggle').on("click", function(){
        $(".the-menu").slideToggle();
        $(".icon-chevron-sign-down").toggleClass("icon-rotate-180");

        if ($('#the-overlay').length) {
            $('#the-overlay').remove();
        }
        else {
            var content = '<div id="the-overlay" class="the-toggle"></div>';
            theToggle();
            $('body').prepend(content);             
            var docHeight = $(document).height();
            $("#the-overlay").height(docHeight);    
        }
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top