Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

Using Javascript to Detect the Key Pressed

Often it is useful to intercept the key pressed within an element of an HTML form, like a textbox and so on. For this purpose you can use Javascript to extract the code of the key that was pressed. Here is a snippet of code you can use–of course adapting it to your needs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function keyPressed(e){
  var code;
  if(window.event){ //IE
   code = e.keyCode;
  }
  else{ //other browsers
    code = e.which;
  }
  //check, for example, if the Enter key was pressed (code 13)
  if(code == 13){
    //Enter key pressed
  }
  else{
    //Another key pressed
  }
}

Note: keyCode is used by Internet Explorer while which is used by the other browsers.

Then, from within a form, you can call this function. For example

1
<input onkeypress="javascript:keyPressed(event);" type="text" />

The Name-separator Character In Java

Java was born as a platform-independent programming language. Some features that grant the platform independence are achieved using the APIs of the language itself. For example, to construct a filename path, you can use the public static field separator of the java.io.File class.

Example:

1
String path = java.io.File.separator + "foldername" + java.io.File.separator + "filename";

This produces the string /foldername/filename under Unix-like systems and \foldername\filename under Windows systems.

Hello World!

Welcome to my blog. This is my first post. About myself: My name is Alessandro Lacava and I am a software engineer. I love designing and developing software. So, as you may have guessed, my blog is going to mainly contain articles, techniques, tips & tricks and much more about computer programming. Stay tuned.