6

Is it possible to have keyboard event listener canvas.addEventListener('onkeydown', ev_keydown, false); like we have Mouse event Listeners

canvas.removeEventListener('mousedown', ev_mousedown, false);
canvas.addEventListener('mousedown', ev_mousedown, false); 

in JavaScript. If not then what would be the alternate?

2 Answers 2

2

Check if this works for you. Your sample line had the a prefix of on which is only used for IEs method attachEvent.

function listener(elem, evnt, func)
{
    if (elem.addEventListener)
        elem.addEventListener(evnt,func,false);
    else if (elem.attachEvent) // For IE
        return elem.attachEvent("on" + evnt, func);
}

listener(document.getElementById('myCanvas'), 'keydown', ev_keydown);
Sign up to request clarification or add additional context in comments.

Comments

1

jQuery offers a simple way to bind eventlisteners to DOMElements

and there are also eventlisteners for keyboard events here are some links

http://api.jquery.com/keydown/

http://api.jquery.com/keypress/

http://api.jquery.com/keyup/

you can bind them to window and this should do what you want

you can also use your own method to bind events in a cross-browser compatible way

function bindEvent(e, typ, handler) {
   if(e.addEventListener) {
      e.addEventListener(typ, handler, false);
   }else{
      e.attachEvent('on'+typ, handler);
   }
}

this should also allow you to bind the mentioned types of events

6 Comments

can we do it without using Jquery? i can use only Javascript in this context.
jQuery is not mentioned in the question, why force an implementation-specific solution?
I also added the method i use to bind events without jQuery - hope it works for you
@Eliran Malka i have mentioned JavaScript.
why downvote? sure jQuery has not been mentioned but jQuery is Javascript - so whats the problem?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.