Primeros Pasos (Tutorial de Javascript)

¿Por qué JavaScript?

JavaScript es un lenguaje de programación poderoso, complicado y frecuentemente mal entendido. Permite el desarrollo fácil de aplicaciones en las que los usuarios pueden introducir datos y ver los resultados con facilidad.

La ventaja principal de JavaScript, también conocido como ECMAScript, gira entorno al Navegador Web, ya que tiene la habilidad de producir los mismos resultados en todas las plataformas soportadas por el navegador. Los ejemplos de esta página, justo igual que Google Maps, funcionan en Linux, Windows y Mac OS. Con el creciente número de librerías JavaScript ahora es más sencillo navegar por un documento, seleccionar elementos del DOM, crear animaciones, gestionar eventos y desarrollar aplicaciones Ajax. A diferencia de la moda alrededor de otras tecnologías promovidas por diferentes intereses propietarios, JavaScript es el único lenguaje de programación cliente multiplataforma que es libre y tiene una adopción universal.

Qué deberías saber

JavaScript es un lenguaje de programación con el que empezar a programar muy fácilemente. Todo lo que necesitas para empezar es un editor de texto y un Navegador Web.

Hay muchas otras tecnologías que pueden integrarse y desarrollarse conjuntamente con JavaScript que están más allá del alcance de este documento. ¡No esperes hacer una aplicación entera como Google Maps en tu primer día!

Primeros pasos

Comenzar en JavaScript es muy fácil. No necesitas instalar ningún software de desarrollo complejo. No necesitas saber el uso de la consola, ni el programa Make o usar un compilador. Javascript es un lenguaje interpretado por tu navegador web. Todo lo que debes hacer es guardar tu programa como archivo de texto y abrirlo en tu navegador web. Eso es todo.

 

JavaScript es un gran lenguaje de programación para iniciarse en el mundo de la programación. Permite una respuesta instantánea con los nuevos estudiantes y enseña sobre herramientas que son utilizadas en la vida real. Esto hace un gran contraste con C, C++ y Java los cuales son utilizados solamente por desarrolladores de software muy dedicados y especializados.

Problemas de compatibilidad entre navegadores

There are variations between what functionality is available in the different browsers. Mozilla, Microsoft IE, Apple Safari, and Opera fluctuate in behavior. We intend on documenting these variations. You can mitigate these issues by using the various cross-platform JavaScript APIs that are available. These APIs provide common functionality and hide these browser fluctuations from you.

Cómo probar los ejemplos

The examples below have some sample code. There are many ways to try these examples out. If you already have your own website, then you should be able to just save these examples as new Web pages on your website.

If you do not have your own website, you can save these examples as files on your computer and open them up with the Web browser you are using now. JavaScript is a very easy language to use for beginning programmers for this reason. You don't need a compiler or a development environment; you and your browser are all you need to get started!

Ejemplo: Interceptando un clic de ratón

The specifics of event handling (event types, handler registration, propagation, etc.) are too extensive to be fully covered in this simple example. However, this example cannot demonstrate catching a mouse click without delving a little into the JavaScript event system. Just keep in mind that this example will only graze the full details about JavaScript events and that if you wish to go beyond the basic capabilities described here, read more about the JavaScript event system.

'Mouse' events are a subset of the total events issued by a Web browser in response to user actions. The following is a list of the events emitted in response to a user's mouse action:

  • Click - issued when a user clicks the mouse
  • DblClick - issued when a user double-clicks the mouse
  • MouseDown - issued when a user depresses a mouse button (the first half of a click)
  • MouseUp - issued when a user releases a mouse button (the second half of a click)
  • MouseOut - issued when the mouse pointer leaves the graphical bounds of the object
  • MouseOver - issued when the mouse pointer enters the graphical bounds of the object
  • MouseMove - issued when the mouse pointer moves while within the graphical bounds of the object
  • ContextMenu - issued when the user clicks using the right mouse button

Note that in the latest versions of HTML, the inline event handlers, i.e. the ones added as tag attributes, are expected to be all lowercase and that event handlers in script are always all lowercase.

The simplest method for capturing these events, to register event handlers - using HTML - is to specify the individual events as attributes for your element. Example:

  <span onclick="alert('Hello World!');">Click Here</span>

The JavaScript code you wish to execute can be inlined as the attribute value or you can call a function which has been defined in a <script> block within the HTML page:

<script type="text/javascript">
  function clickHandler () {
     alert ("Hello, World!");
  }
</script>
<span onclick="clickHandler();">Click Here</span>

Additionally, the event object which is issued can be captured and referenced, providing the developer with access to specifics about the event such as which object received the event, the event's type, and which mouse button was clicked. Using the inline example again:

<script type="text/javascript">
  function clickHandler(event) {
    var eType = event.type;
    /* the following is for compatibility */
    /* Moz populates the target property of the event object */
    /* IE populates the srcElement property */
    var eTarget = event.target || event.srcElement;

    alert( "Captured Event (type=" + eType + ", target=" + eTarget );
  }
</script>
<span onclick="clickHandler(event);">Click Here</span>

In addition to registering to receive events in your HTML, you can likewise set the same attributes of any HTMLElement objects generated by your JavaScript. The example below instantiates a span object, appends it to the page body, and registers the span object to receive mouse-over, mouse-out, mouse-down, and mouse-up events.

<body></body>
<script type="text/javascript">
  function mouseeventHandler(event) {
    /* The following is for compatibility */
    /* IE does NOT by default pass the event object */
    /* obtain a ref to the event if one was not given */
    if (!event) event = window.event;

    /* obtain event type and target as earlier */
    var eType = event.type;
    var eTarget = event.target || event.srcElement;
    alert(eType +' event on element with id: '+ eTarget.id);
  }

 function onloadHandler () {
   /* obtain a ref to the 'body' element of the page */
   var body = document.body;
   /* create a span element to be clicked */
   var span = document.createElement('span');
   span.id = 'ExampleSpan';
   span.appendChild(document.createTextNode ('Click Here!'));

   /* register the span object to receive specific mouse events - 
      notice the lowercase of the events but the free choice in the names of the handlers you replace them with. 
   */
   span.onmousedown = mouseeventHandler;
   span.onmouseup = mouseeventHandler;
   span.onmouseover = mouseeventHandler;
   span.onmouseout = mouseeventHandler;

   /* display the span on the page */
   body.appendChild(span);   
}

window.onload = onloadHandler; // since we replace the handler, we do NOT have () after the function name
</script>

Ejemplo: Interceptando un evento de teclado

Similar to the "Catching a mouse event" example above, catching a keyboard event relies on exploring the JavaScript event system. Keyboard events are fired whenever any key is used on the keyboard.

The list of available keyboard events emitted in response to a keyboard action is considerably smaller than those available for mouse:

  • KeyPress - issued when a key is depressed and released
  • KeyDown - issued when a key is depressed but hasn't yet been released
  • KeyUp - issued when a key is released
  • TextInput (available in Webkit browsers only at time of writing) - issued when text is input either by pasting, speaking, or keyboard. This event will not be covered in this article.

In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, never both. If the key pressed generates a character (e.g., 'a'), charCode is set to the code of that character, respecting the letter case (i.e., charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored in keyCode.

The simplest method for capturing keyboard events is again to register event handlers within the HTML, specifying the individual events as attributes for your element. Example:

  <input type="text" onkeypress="alert ('Hello World!');" />

As with mouse events, the JavaScript code you wish to execute can be inlined as the attribute value or you can call a function which has been defined in a <script> block within the HTML page:

<script type="text/javascript">
  function keypressHandler() {
    alert ("Hello, World!");
  }
</script>

<input onkeypress="keypressHandler();" />

Capturing the event and referencing the target (i.e., the actual key that was pressed) is achieved in a similar way to mouse events:

<script type="text/javascript">
  function keypressHandler(evt) {
      var eType = evt.type; // Will return "keypress" as the event type
      /* here we again need to use a cross browser method
         mozilla based browsers return which and others keyCode.
         The Conditional operator or ternary is a good choice */
      var keyCode = evt.which?evt.which:evt.keyCode; 
      var eCode = 'keyCode is ' + keyCode;
      var eChar = 'charCode is ' + String.fromCharCode(keyCode); // or evt.charCode
      alert ("Captured Event (type=" + eType + ", key Unicode value=" + eCode + ", ASCII value=" + eChar + ")");
   }
</script>
<input onkeypress="keypressHandler(event);" />

Capturing any key event from the page can be done by registering the event at the document level and handling it in a function:

<script type="text/javascript">
  document.onkeypress = keypressHandler(event);
  document.onkeydown = keypressHandle(event);
  document.onkeyup =keypressHandle(event)
 
</script>

Here is a complete example that shows key event handling:

<!DOCTYPE html>
<html>
<head>
  <script>
    var metaChar = false;
    var exampleKey = 16;
    function keyEvent(event) {
      var key = event.keyCode || event.which; // alternative to ternary - if there is no keyCode, use which
      var keychar = String.fromCharCode(key);
      if (key==exampleKey) { metaChar = true; }
      if (key!=exampleKey) {
         if (metaChar) {
            alert("Combination of metaKey + " + keychar)
            metaChar = false;
         } else { alert("Key pressed " + key); }
      }
    }
    function metaKeyUp (event) {
      var key = event.keyCode || event.which;
      if (key==exampleKey) { metaChar = false; }
    }
  </script>
</head>
<body onkeydown="keyEvent(event)" onkeyup="metaKeyUp(event)">
    Try pressing any key!
</body>
</html>

Browser bugs and quirks

The two properties made available through the key events are keyCode and charCode. In simple terms, keyCode refers to the actual keyboard key that was pressed by the user, while charCode is intended to return that key's ASCII value. These two values may not necessarily be the same; for instance, a lower case 'a' and an upper case 'A' have the same keyCode, because the user presses the same key, but a different charCode because the resulting character is different.

The way in which browsers interpret the charCode is not a consistently-applied process. For example, Internet Explorer and Opera do not support charCode. However, they give the character information in keyCode, but only onkeypress. Onkeydown and onkeyup keyCode contain key information. Firefox uses a different word, "which", to distinguish the character.

Refer to the Mozilla Documentation on Keyboard Events for a further treatment of keyboard events.

Borrador
Esta página no está completa.

Ejemplo: Arrastrando imágenes

The following example allows moving the image of Firefox around the page:

<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
img { position: absolute; }
</style>

<script type='text/javascript'>
window.onload = function() {

  movMeId = document.getElementById("ImgMov");
  movMeId.style.top = "80px";
  movMeId.style.left = "80px";

  document.onmousedown = coordinates;
  document.onmouseup = mouseup;

  function coordinates(e) {
    if (e == null) { e = window.event;}
    
    // e.srcElement holds the target element in IE, whereas e.target holds the target element in Firefox
    // Both properties return the HTML element the event took place on.

    var sender = (typeof( window.event ) != "undefined" ) ? e.srcElement : e.target;

    if (sender.id=="ImgMov") {
      mouseover = true;
      pleft = parseInt(movMeId.style.left);
      ptop = parseInt(movMeId.style.top);
      xcoor = e.clientX;
      ycoor = e.clientY;
      document.onmousemove = moveImage;
      return false;
    } else { 
        return false;
    }
  }

  function moveImage(e) {
    if (e == null) { e = window.event; }
    movMeId.style.left = pleft+e.clientX-xcoor+"px";
    movMeId.style.top = ptop+e.clientY-ycoor+"px";
    return false;
  }

  function mouseup(e) {
    document.onmousemove = null;
  }
}
</script>
</head>

<body>
  <img id="ImgMov" src="http://placehold.it/100x100&text=JS" width="64" height="64" />
  <p>Drag and drop around the image in this page.</p>
</body>

</html>

Ejemplo: Redimensionando cosas

Example of resizing an image (the actual image is not resized, only the image's rendering.)
  <!DOCTYPE html>
  <html>
    <head>
      <style>
        #resizeImage {
          margin-left: 100px;
        }
      </style>
      <script>
      window.onload = function() {

        var resizeId = document.getElementById("resizeImage");
        var resizeStartCoordsX,
            resizeStartCoordsY,
            resizeEndCoordsX,
            resizeEndCoordsY;

        var resizeEndCoords;
        var resizing = false;

        document.onmousedown = coordinatesMousedown;
        document.onmouseup = coordinatesMouseup;

        function coordinatesMousedown(e) {
          if (e == null) {
            e = window.event;
          }

          var element = (typeof( window.event ) != 'undefined' ) ? e.srcElement : e.target;

          if (element.id == "resizeImage") {
            resizing = true;
            resizeStartCoordsX = e.clientX;
            resizeStartCoordsY = e.clientY;
          }
          return false;
        }

        function coordinatesMouseup(e) {
          if (e == null) {
            e = window.event;
          }

          if (resizing === true) {
            var currentImageWidth = parseInt(resizeId.width);
            var currentImageHeight = parseInt(resizeId.height);

            resizeEndCoordsX = e.clientX;
            resizeEndCoordsY = e.clientY;

            resizeId.style.height = currentImageHeight - (resizeStartCoordsY - resizeEndCoordsY) + 'px';
            resizeId.style.width = currentImageWidth - (resizeStartCoordsX - resizeEndCoordsX) + 'px';

            resizing = false;
          }
          return false;
        }
      }
      </script>
    </head>

    <body>
      <img id="resizeImage" src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Mozilla_Firefox_3.5_logo_256.png" 
width="64" height="64" />
      <p>Click on the image and drag for resizing.</p>
    </body>

  </html>

Ejemplo: Dibujando líneas

FIXME: Need Content. Or, remove headline

Etiquetas y colaboradores del documento

Colaboradores de esta página: Christian_Bravo, gsus
Última actualización por: Christian_Bravo,