Alex Man
Alex Man

Reputation: 4886

boolean flag in javascript is not checking properly

i've created a sample application which checks when i press a key or mouse, but the problem is when mouse or when key is pressed it prints the console "Enter is pressed" and "Enter is not pressed some Mouse event is clicked", that boolean checking is not working properly i think so,

can anyone please tell me some solution

$('#adminPanel').bind("searchMaster", function(event, data)
{
    var press = true;
    $(this).keypress(function(e) {
       var  code = e.keyCode ? e.keyCode : e.which;
       if (code == 13) 
       {
         console.log("Enter is pressed");
         press = false;
       }
    });

    if(press)
    {
        console.log("Enter is not pressed, some Mouse event is clicked");   
        // some other action to be triggered if key is not pressed
    }
});

Upvotes: 0

Views: 277

Answers (1)

Syjin
Syjin

Reputation: 2810

The problem is, (a) that you register the keypress event inside the click callback and (b) that you set press to false, if is pressed and (c) that you never reset the value of press every time you click with the mouse.

I suggest you split the two callbacks up and move press outside of the callbacks. In the example press => enterPressed. The enterPressed and the callbacks are wrapped in an IIFE to not poluted the global namespace.

 (function () {
    // by default, "enter" is not pressed
    var enterPressed = false;

    // Suppose this event is triggered by mouse clicks
    $("#adminPanel").bind("searchMaster", function (event, data) {
        if (!enterPressed) {
            // Handle Mouse Click (no "enter" pressed here)
        }
    });

    // This callback will be triggered if you press a key
    // and if you release a key
    $("#adminPanel").on("keydown keyup", function (e) {
        var code = e.keyCode ? e.keyCode : e.which;

        // check if the pressed/released key was "enter"
        if (code === 13) {
            enterPressed = !enterPressed;
        }
    });
})();

Upvotes: 1

Related Questions