Category: JavaScript

The Function class in JavaScript

Most programmers know how to define and use a function in JavaScript. For example the following function displays an alert containing the string passed in as a parameter:

 
function displayAlert(sText) {
  alert(sText);
}
// Then you call it this way
displayAlert("Hello World!");

How many developers, however, know that JavaScript functions are actually objects? Indeed, you can define the previous function using the Function class:

 
var displayAlert = new Function("sText", "alert(sText);");
//...and you call it the same way
displayAlert("Hello World!");

For those who didn’t figure it out, the syntax of the Function class is the following:

Read more...

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.

   
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.

Read more...