views:

59

answers:

3

In jQuery, how do you make it so when I click a div, I can press the delete key and make something happen?

For example, I click on a div, then after that I press the button delete and it alerts a message. If I dont click on the div and press delete, nothing happens. Thanks!!

+1  A: 

Didn't test this code, but i imagine you should use something like this...

  var divSelected = null;
  $(document).ready(function(){
    $("div").click(
      function(){
        divSelected = caller.id;
        alert(test.val());
    }
  );
  $('#DIV').keypress(function(e){
      if(e.which == 46 && divSelected){ // 46 is the keycode for the delete key...
          // do what you want...
      }
   });
});
Garis Suero
A: 

You can use the keydown() and keyup() events to detect keystrokes.

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

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

Check out the demos and examples for each and you'll get a good idea for how to do it. You'll need the keycode for the delete button. Which delete button are you talking about... the "Backspace", the "Delete", or the "Del" on the number pad? Backspace should be '8' and delete should be '46'. I'm not 100% sure so double check that... I got my values from here: http://www.webonweboff.com/tips/js/event_key_codes.aspx

Refer to this post about how to find out what they keycode is when a key is being pressed if you can't find the keycode.

Hope that helps.

Hristo
A: 

Garis Suero is close, but I think it should be:

  $(function(){
  var divSelected = null;
    $('div').click(
      function(){
        divSelected = this;
    });
  $('div').keypress(function(e){
      if(e.which == 46 && this == divSelected){ 
        alert('Delete me!');
      }
   });
});

Also totally untested though ;)