简体   繁体   中英

Key pressed and click in the same time

how can I merge keypress and on click? I mean when a user press enter and click somewhere in the same time I need to invoke a function.

$(document).keypress(function(e) {
    var code = e.keyCode || e.which;
    if(code == 13) {
        alert('keypress');
    }
});
$(document).on( "click", function() {
    alert('click');
});

I have this code but I am not able to merge it (usually I don't work with jQuery/javascript).

Something like this may do the trick

var pressingEnter = false;
$(document).on({
    keydown: function(e) {
        if(e.which == 13) {
            // enter is being pressed, set true to flag variable
            pressingEnter = true;
        }
    },
    keyup: function(e) {
        if(e.which == 13) {
            // enter is no longer pressed, set false to flag variable
            pressingEnter = false;
        }
    },
    click: function() {
        if (pressingEnter) {
           console.log('click and enter pressed');
        }
    }
});

BTW: there is no need to do var code = e.keyCode || e.which; var code = e.keyCode || e.which; since jQuery resolves that for you. You can use e.which on any browser.

EDIT

This version should allow any order of key pressed / mouse click. I'm assuming only left click is captured. Logic to handle enter + mouse click is placed on keydown and mousedown (it could be moved to keyup and mouseup if makes more sense)

Changed alert by console.log since the first prevents mouseup event to be triggered. Nowdays we have hundred of better ways to show a message to user than built-in alert pop ups so I'll assume making it work for it is not a requirement.

var pressingEnter = false;
var clickingMouseButton = false;
$(document).on({
    keydown: function(e) {
        if(e.which == 13) {
            pressingEnter = true;
        }

        if (clickAndEnterPressing()) {
            console.log('click and enter pressed');
        }        
    },
    keyup: function(e) {
        if(e.which == 13) {
            pressingEnter = false;
        }
    },
    mousedown: function(e) {
        if (e.which == 1) {
            clickingMouseButton = true;
        }

        if (clickAndEnterPressing()) {
            console.log('click and enter pressed');
        }           
    },
    mouseup: function(e) {
        if (e.which == 1) {
            clickingMouseButton = false;
        }
    }
});

function clickAndEnterPressing() {
    return pressingEnter && clickingMouseButton;
}

Here's an example that will work if enter is pushed first or if the mouse is clicked first or if they are both pressed within a certain threshold of time apart (I set it to 100 ms, but this can be easily adjusted):

var enterDown = false;
var mouseDown = false;
var lastEnter = false;
var lastMouseUp = false;

var triggerOnNextUp = false;
$(document).on({
    keydown: function(e) {
        enterDown = true;
    },
    keyup: function(e) {
        if(e.which == 13) {
            lastEnter = (new Date()).getTime();
            enterDown = false;
            detectEnterAndClick();
            if (mouseDown) {
                triggerOnNextUp = true;
            }
        }
    },
    mousedown: function() {
        mouseDown = true;
    },
    mouseup: function() {
        lastMouseUp = (new Date()).getTime();
        mouseDown = false;
        detectEnterAndClick();
        if (enterDown) {
            triggerOnNextUp = true;
        }
    }
});

function detectEnterAndClick() {
    if (Math.abs(lastEnter - lastMouseUp) < 100 || triggerOnNextUp) {
        // Reset variables to prevent from firing twice
        triggerOnNextUp = false;
        enterDown = false;
        mouseDown = false;
        lastEnter = false;
        lastMouseUp = false;

        $("body").append("Clicked and pushed enter<br>");
    }
}

See it on JSFiddle

There is no way to 'merge' events. However you could for example debounce your handler. For example (using lodash ):

var handler = _.debounce(function(event) { alert(event.type); }, 100);
$(document)
  .on('click', handler)
  .on('keypress', handler);

you can use the event.type to determine what triggered the event

Demo

$(function(){
    $(document).on("click", ClickAndKeyPress);

  $(document).on("keypress", ClickAndKeyPress);
});


function ClickAndKeyPress(event){
  $("div").text(event.type);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM