jqueryevents

Turn click event on and off


I feel lke there must be a more streamlined way to do this than re-executing the whole click event code each time.

In 'big' mode, I don't need the overlay, so I shut it off. But I want it to work when I switch back to 'default' or 'smol' mode.

My sizer buttons:

<a href="javascript:false" class="smol" onclick="sizer('smol')">Small</a>
<a href="javascript:false" class="default" onclick="sizer('default')">Default</a>
<a href="javascript:false" class="big" onclick="sizer('big')">Big</a>

// my generated content
<article>My content 1</article>
<article>My content 2</article>
// etc.
<div id="overlay" onclick="hideOverlay()"></div>

My sizer function:

function sizer(sz) {
    // a bunch of CSS to resize my content

    if (sz=="big") { 
        enableOverlay(false);
    }
    else {
        enableOverlay(true);
    }
}

Turning the overlay click functionality on and off (ctually, destroying it and recreating it each time)

function enableOverlay(state){
    if (state) { // sizer is 'default' or 'smol'
        // set article to show overlay when clicked
        $( "article" ).on("click", function(){
            // build the contents of the overlay on-the-fly for this article
            var aside = $(this).find("aside");
            var o = $("#overlay");
            o.contents().remove(); //destroy old content
            o.append(aside[0].innerHTML); // add new content
            o.css("display","block");
        });
    }
    else { // sizer is 'big'
        // disable article click event
        $( "article" ).off();
    }
}

function hideOverlay(){
    // hide when clicked
    $("#overlay").hide()
}

And of course, I start off in default mode:

$( document ).ready(function() {
    enableOverlay(true);
});

Isn't there a way of keeping the click event bound but disabling it temporarily?


Solution

  • Maybe I will try to add a temporary variable.

    let overlayEnabled = true;
    
    function sizer(sz) {
        // a bunch of CSS to resize my content
    
        overlayEnabled = sz !== 'big';
    }
    
    $( "article" ).on("click", function(){
        if (!overlayEnabled) {
            return;
        }
        // build the contents of the overlay on-the-fly for this article
        var aside = $(this).find("aside");
        var o = $("#overlay");
        o.contents().remove(); //destroy old content
        o.append(aside[0].innerHTML); // add new content
        o.css("display","block");
    });
    
    

    or if you don't want a flag variable, you can set data attribute on the overlay.

    function sizer(sz) {
        // a bunch of CSS to resize my content
    
        $("#overlay").attr('data-enabled', sz !== 'big')
    }
    
    $( "article" ).on("click", function(){
        const enabled = $("#overlay").attr('data-enabled');
    
        // notice: the type of enabled is string
        if (enabled === 'false') {
            return;
        }
        // rest of code
    })