NewKidOnTheBlock
NewKidOnTheBlock

Reputation: 1511

Clicking outside active div to deactivate function

I have a jquery function which freezes the HTML scroll when the toggle button has been clicked. Click here

I want to add an extra touch to this function when the user clicks outside the container - wrapper it unfreezes the scroll function of the HTML

//Freeze page content scrolling
function freeze() {
    if ($("html").css("position") != "fixed") {
        var top = $("html").scrollTop() ? $("html").scrollTop() :
            $("body").scrollTop();
        if (window.innerWidth > $("html").width()) {
            $("html").css("overflow-y", "scroll");
        }
        $("html").css({
            "width": "100%",
            "height": "100%",
            "position": "fixed",
            "top": -top
        });
    }
}

//Unfreeze page content scrolling
function unfreeze() {
    if ($("html").css("position") == "fixed") {
        $("html").css("position", "static");
        $("html, body").scrollTop(-parseInt($("html").css("top")));
        $("html").css({
            "position": "",
            "width": "",
            "height": "",
            "top": "",
            "overflow-y": ""
        });
    }
}

var frozen = false;

$("#addFixed").click(function() {
    if (frozen) {
        unfreeze();
        frozen = false;
    } else {
        freeze();
        frozen = true;
    }
});

Upvotes: 1

Views: 142

Answers (1)

Tocila Ionut
Tocila Ionut

Reputation: 69

One solution can be:

$("body").click(function(e) {
    if ($(e.target).closest("#addFixed").length) {
        console.log("Clicked inside #addFixed");
        freeze();
    } else { 
        console.log("Clicked outside #addFixed");
        unfreeze();
    }
});

Using one handler without any stopPropagation call will allow others to be notified and allows you to handle freeze/unfreeze logic

Upvotes: 4

Related Questions