SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Thread: Key Codes

  1. #1
    SitePoint Enthusiast
    Join Date
    Dec 2006
    Posts
    50
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Key Codes

    Hi,

    Can anyone show me how to show an alert box any time ctrl -n is pressed.

    Thanks in Advance

    Sinky

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Ctrl+N opens a new window in many/most browsers, so if you try to apply some other function to it you run the risk of:
    - it not working
    - it working, but a new window popping up
    - annoying someone who wants to open a new window but finds an annoying alert box popping up instead

    It would be much more sensible to use something else, like just the letter N:
    Code:
        document.onkeydown = function(e) {
          if (!e) {keycode = event.keyCode;}
          else {keycode = e.which;}
          if (keycode == 78) {
            alert('You pressed N');
          }
        }

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    document.onkeydown = function(e) {
    	e= window.event || e;
    	if (e.ctrlKey && e.keyCode == 78){
    		alert('You pressed Control + N');
    	}
    }
    This will work, but ctrl + N opens a new window in most browsers, and your alert, being fired on the old window, will not be visible until either you blur the new window or refocus the old one. One side effect of the alert- it will pause any running scipts on the original window until you return and close it.

  4. #4
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    e= window.event || e;
    I suggest this order:
    Code:
    e = e || window.event;
    because listeners added with attachEvent do receive event object arguments. And because it is more 'forward compatible'.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •