JavaScript - Eventos
JavaScript - Eventos
¿Qué es un evento?
La interacción de JavaScript con HTML se maneja a través de eventos que ocurren cuando el usuario o el navegador manipula una página.
Cuando la página se carga, se llama evento. Cuando el usuario hace clic en un botón, ese clic también es un evento. Otros ejemplos incluyen eventos como presionar cualquier tecla, cerrar una ventana, cambiar el tamaño de una ventana, etc.
Los desarrolladores pueden usar estos eventos para ejecutar respuestas codificadas en JavaScript, lo que provoca que los botones se cierren, los mensajes que se mostrarán a los usuarios, los datos que deben validarse y prácticamente cualquier otro tipo de respuesta imaginable.
Los eventos son parte del Nivel 3 del Modelo de Objetos de Documento (DOM) y cada elemento HTML contiene un conjunto de eventos que pueden desencadenar código JavaScript.
Siga este pequeño tutorial para comprender mejor Referencia de eventos HTML . Aquí veremos algunos ejemplos para comprender una relación entre Evento y JavaScript:
tipo de evento onclick
Este es el tipo de evento más utilizado que ocurre cuando un usuario hace clic en el botón izquierdo de su mouse. Puede poner su validación, advertencia, etc., contra este tipo de evento.
Ejemplo
Prueba el siguiente ejemplo.
<html> <head> <script type="text/javascript"> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <p>Click the following button and see result</p> <form> <input type="button" onclick="sayHello()" value="Say Hello" /> </form> </body> </html>
Salida
tipo de evento onsubmit
onsubmit es un evento que ocurre cuando intentas enviar un formulario. Puede poner su validación de formulario contra este tipo de evento.
Ejemplo
El siguiente ejemplo muestra cómo usar onsubmit. Aquí llamamos a una función validate() antes de enviar los datos de un formulario al servidor web. Si la función validate() devuelve verdadero, el formulario será enviado, de lo contrario no enviará los datos.
Prueba el siguiente ejemplo.
<html> <head> <script type="text/javascript"> <!-- function validation() { all validation goes here ......... return either true or false } //--> </script> </head> <body> <form method="POST" action="t.cgi" onsubmit="return validate()"> ....... <input type="submit" value="Submit" /> </form> </body> </html>
onmouseover y onmouseout
Estos dos tipos de eventos te ayudarán a crear buenos efectos con imágenes o incluso con texto. El eventoonmouseover se activa cuando coloca el mouse sobre cualquier elemento y el onmouseout se activa cuando saca el mouse de ese elemento. Prueba el siguiente ejemplo.
<html> <head> <script type="text/javascript"> <!-- function over() { document.write ("Mouse Over"); } function out() { document.write ("Mouse Out"); } //--> </script> </head> <body> <p>Bring your mouse inside the division to see the result:</p> <div onmouseover="over()" onmouseout="out()"> <h2> This is inside the division </h2> </div> </body> </html>
Salida
HTML 5 Eventos estándar
Los eventos estándar de HTML 5 se enumeran aquí para su referencia. Aquí el script indica una función de Javascript que se ejecutará contra ese evento.
Attribute | Value | Description |
---|---|---|
Offline | script | Triggers when the document goes offline |
Onabort | script | Triggers on an abort event |
onafterprint | script | Triggers after the document is printed |
onbeforeonload | script | Triggers before the document loads |
onbeforeprint | script | Triggers before the document is printed |
onblur | script | Triggers when the window loses focus |
oncanplay | script | Triggers when media can start play, but might has to stop for buffering |
oncanplaythrough | script | Triggers when media can be played to the end, without stopping for buffering |
onchange | script | Triggers when an element changes |
onclick | script | Triggers on a mouse click |
oncontextmenu | script | Triggers when a context menu is triggered |
ondblclick | script | Triggers on a mouse double-click |
ondrag | script | Triggers when an element is dragged |
ondragend | script | Triggers at the end of a drag operation |
ondragenter | script | Triggers when an element has been dragged to a valid drop target |
ondragleave | script | Triggers when an element is being dragged over a valid drop target |
ondragover | script | Triggers at the start of a drag operation |
ondragstart | script | Triggers at the start of a drag operation |
ondrop | script | Triggers when dragged element is being dropped |
ondurationchange | script | Triggers when the length of the media is changed |
onemptied | script | Triggers when a media resource element suddenly becomes empty. |
onended | script | Triggers when media has reach the end |
onerror | script | Triggers when an error occur |
onfocus | script | Triggers when the window gets focus |
onformchange | script | Triggers when a form changes |
onforminput | script | Triggers when a form gets user input |
onhaschange | script | Triggers when the document has change |
oninput | script | Triggers when an element gets user input |
oninvalid | script | Triggers when an element is invalid |
onkeydown | script | Triggers when a key is pressed |
onkeypress | script | Triggers when a key is pressed and released |
onkeyup | script | Triggers when a key is released |
onload | script | Triggers when the document loads |
onloadeddata | script | Triggers when media data is loaded |
onloadedmetadata | script | Triggers when the duration and other media data of a media element is loaded |
onloadstart | script | Triggers when the browser starts to load the media data |
onmessage | script | Triggers when the message is triggered |
onmousedown | script | Triggers when a mouse button is pressed |
onmousemove | script | Triggers when the mouse pointer moves |
onmouseout | script | Triggers when the mouse pointer moves out of an element |
onmouseover | script | Triggers when the mouse pointer moves over an element |
onmouseup | script | Triggers when a mouse button is released |
onmousewheel | script | Triggers when the mouse wheel is being rotated |
onoffline | script | Triggers when the document goes offline |
onoine | script | Triggers when the document comes online |
ononline | script | Triggers when the document comes online |
onpagehide | script | Triggers when the window is hidden |
onpageshow | script | Triggers when the window becomes visible |
onpause | script | Triggers when media data is paused |
onplay | script | Triggers when media data is going to start playing |
onplaying | script | Triggers when media data has start playing |
onpopstate | script | Triggers when the window's history changes |
onprogress | script | Triggers when the browser is fetching the media data |
onratechange | script | Triggers when the media data's playing rate has changed |
onreadystatechange | script | Triggers when the ready-state changes |
onredo | script | Triggers when the document performs a redo |
onresize | script | Triggers when the window is resized |
onscroll | script | Triggers when an element's scrollbar is being scrolled |
onseeked | script | Triggers when a media element's seeking attribute is no longer true, and the seeking has ended |
onseeking | script | Triggers when a media element's seeking attribute is true, and the seeking has begun |
onselect | script | Triggers when an element is selected |
onstalled | script | Triggers when there is an error in fetching media data |
onstorage | script | Triggers when a document loads |
onsubmit | script | Triggers when a form is submitted |
onsuspend | script | Triggers when the browser has been fetching media data, but stopped before the entire media file was fetched |
ontimeupdate | script | Triggers when media changes its playing position |
onundo | script | Triggers when a document performs an undo |
onunload | script | Triggers when the user leaves the document |
onvolumechange | script | Triggers when media changes the volume, also when volume is set to "mute" |
onwaiting | script | Triggers when media has stopped playing, but is expected to resume |
No comments