6

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).

Zoli
  • 831
  • 1
  • 11
  • 27
  • Flag the keydown if it's ENTER (unflag on keyup), and check the flag in click handler. Some [special keys can be detected](http://stackoverflow.com/a/18317134/1169519) also in a click handler directly. – Teemu May 25 '15 at 19:03
  • Do you mean that you want to react on a click **while** the enter key is pressed? – Bolesław Chrobry May 25 '15 at 19:07

4 Answers4

12

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; 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;
}
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
2

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

Mike
  • 23,542
  • 14
  • 76
  • 87
0

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);
Bartosz Gościński
  • 1,468
  • 1
  • 16
  • 28
  • Note, this solutions requires the use of the [underscore.js](http://underscorejs.org/) library. – Mike May 25 '15 at 19:09
  • Correct me if I'm wrong, but they look like two different libraries. – Mike May 25 '15 at 19:17
  • Lodash and underscore have similar functinality, but there are _slight_ [differences](http://stackoverflow.com/questions/13789618/differences-between-lodash-and-underscore#answer-13898916) – Bartosz Gościński May 25 '15 at 19:21
0

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);
}
Juan
  • 4,910
  • 3
  • 37
  • 46