Shubham
Shubham

Reputation: 1793

I want to capture multiple key event at once

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    </head>
    <body>
        <textarea id="txtarea"></textarea>
        <script>
            var map = [];
            $('#txtarea').onkeydown = $('#txtarea').onkeyup = function(e){
                e = e || event; // to deal with IE
                map[e.keyCode] = e.type == 'keydown';
                if(map[13] && map[16])
                    alert("Its Working!!");
                else
                    alert("Its not working !!");
            }
        </script>
    </body>
</html>

I want to capture multiple mouse event at once.Where is the error in this.If there is nay better way to do is then please let me know. Thanks in advance.

Upvotes: 0

Views: 122

Answers (4)

Phylogenesis
Phylogenesis

Reputation: 7880

As per our discussion above, you are trying to trigger an action when Shift-Enter is pressed. You can reduce your code above to the following:

$('#txtarea').on(
    'keydown',
    function (e) {
        if (e.shiftKey && e.keyCode === 13) {
            // Shift-Enter has been pressed!
        }
    }
);

Upvotes: 0

mpdunson
mpdunson

Reputation: 237

If you change

$('#txtarea').onkeydown = $('#txtarea').onkeyup = function(e){
            e = e || event; // to deal with IE
            map[e.keyCode] = e.type == 'keydown';
            if(map[13] && map[16])
                alert("Its Working!!");
            else
                alert("Its not working !!");
        }

to

$('#txtarea').bind("keyup keydown", function(e){
    if(e.keyCode === 13] || e.keyCode === 16) {
        alert("Its Working!!");
    } else {
        alert("Its not working !!");
    }
});

then it should work for either event.

Upvotes: 1

benjaminbenben
benjaminbenben

Reputation: 1228

If you use .on() you can bind to multiple events by separating them with a space.

$('#txtarea').on('keyup keydown', function (e){
  // (fires for both keyup and keydown events)
  // console.log(e) 
});

Upvotes: 0

Quentin
Quentin

Reputation: 943586

You can't capture multiple events at once, only one event will fire at any given moment and JavaScript doesn't do threading.

It looks like you are actually trying to define multiple event handlers at once, but you have your syntax wrong.

jQuery doesn't support onkeydown etc properties.

You need to use the on method.

The events argument is a string containing space separated list of events.

$('#txtarea').on("keydown keyup", yourFuntion);

e = e || event; // to deal with IE

Don't do that. jQuery normalises event handlers.

Upvotes: 1

Related Questions