Mostrando entradas con la etiqueta Javascript. Mostrar todas las entradas
Mostrando entradas con la etiqueta Javascript. Mostrar todas las entradas

31 mar 2011

DOM Element

element

« Gecko DOM Reference
This chapter provides a brief reference for the general methods, properties, and events available to most HTML and XML elements in the Gecko DOM.
Various W3C specifications apply to elements:
The articles listed here span the above and include links to the appropriate W3C DOM specification.
While these interfaces are generally shared by most HTML and XML elements, there are more specialized interfaces for particular objects listed in the DOM HTML Specification. Note, however, that these HTML interfaces are "only for [HTML 4.01] and [XHTML 1.0] documents and are not guaranteed to work with any future version of XHTML." The HTML 5 draft does state it aims for backwards compatibility with these HTML interfaces but says of them that "some features that were formerly deprecated, poorly supported, rarely used or considered unnecessary have been removed." One can avoid the potential conflict by moving entirely to DOM XML attribute methods such as getAttribute().
Html, Head, Link, Title, Meta, Base, IsIndex, Style, Body, Form, Select, OptGroup, Option, Input, TextArea, Button, Label, FieldSet, Legend, UList, OList, DList, Directory, Menu, LI, Div, Paragraph, Heading, Quote, Pre, BR, BaseFont, Font, HR, Mod, Anchor, Image, Object, Param, Applet, Map, Area, Script, Table, TableCaption, TableCol, TableSection, TableRow, TableCell, FrameSet, Frame, IFrame

Properties

Name Description Type Availability
attributes All attributes associated with an element. NamedNodeMap All
baseURI Base URI as a string String HTML, XUL
baseURIObject New in Firefox 3 The read-only nsIURI object representing the base URI for the element. nsIURI All (with UniversalXPConnect privileges)
childElementCount New in Firefox 3.5 The number of child nodes that are elements. Number HTML, XUL
childNodes All child nodes of an element. NodeList All
children Requires Gecko 1.9 A live nsIDOMNodeList of the current child elements. NodeList HTML, XUL
classList Requires Gecko 1.9.2 Token list of class attribute DOMTokenList HTML
className Gets/sets the class of the element. String HTML, XUL
clientHeight The inner height of an element. Number HTML
clientLeft The width of the left border of an element. Number HTML
clientTop The width of the top border of an element. Number HTML
clientWidth The inner width of an element. Number HTML
contentEditable Requires Gecko 1.9 Gets/sets whether or not the element is editable. String HTML, XUL
dir Gets/sets the directionality of the element. String HTML, XUL
firstChild The first direct child node of an element, or null if this element has no child nodes. Node All
firstElementChild Requires Gecko 1.9 The first direct child element of an element, or null if the element has no child elements. Element HTML, XUL
id Gets/sets the id of the element. String HTML, XUL
innerHTML Gets/sets the markup and content of the element. String HTML
isContentEditable Requires Gecko 2 Indicates whether or not the content of the element can be edited. Read only. Boolean HTML, XUL
lang Gets/sets the language of an element's attributes, text, and element contents. String HTML
lastChild The last direct child node of an element, or null if this element has no child nodes. Node All
lastElementChild Requires Gecko 1.9 The last direct child element of an element, or null if the element has no child elements. Element HTML, XUL
localName The local part of the qualified name of an element. In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML. Requires Gecko 1.9.2 String All
Name Description Type Availability
name Gets/sets the name attribute of an element. String HTML
namespaceURI The namespace URI of this node, or null if it is no namespace. In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the http://www.w3.org/1999/xhtml namespace in both HTML and XML trees. Requires Gecko 1.9.2 String All
nextSibling The node immediately following the given one in the tree, or null if there is no sibling node. Node All
nextElementSibling New in Firefox 3.5 The element immediately following the given one in the tree, or null if there's no sibling node. Element HTML, XUL
nodeName The name of the node. String All
nodePrincipal New in Firefox 3 The node's principal. nsIPrincipal All (with UniversalXPConnect privileges)
nodeType A number representing the type of the node. Is always equal to 1 for DOM elements. Number All
nodeValue The value of the node. Is always equal to null for DOM elements. String All
offsetHeight The height of an element, relative to the layout. Number HTML
offsetLeft The distance from this element's left border to its offsetParent's left border. Number HTML
offsetParent The element from which all offset calculations are currently computed. Element HTML
offsetTop The distance from this element's top border to its offsetParent's top border. Number HTML
offsetWidth The width of an element, relative to the layout. Number HTML
ownerDocument The document that this node is in, or null if the node is not inside of one. Document All
Name Description Type Availability
parentNode The parent element of this node, or null if the node is not inside of a DOM Document. Node All
prefix The namespace prefix of the node, or null if no prefix is specified. String All
previousSibling The node immediately preceding the given one in the tree, or null if there is no sibling node. Node All
previousElementSibling New in Firefox 3.5 The element immediately preceding the given one in the tree, or null if there is no sibling element. Element HTML, XUL
schemaTypeInfo Returns TypeInfo regarding schema information for the element (also available on Attr). TypeInfo Not supported
scrollHeight The scroll view height of an element. Number HTML
scrollLeft Gets/sets the left scroll offset of an element. Number HTML
scrollTop Gets/sets the top scroll offset of an element. Number HTML
scrollWidth The scroll view width of an element. Number HTML
spellcheck Controls spell-checking (present on all HTML elements) Boolean HTML
style An object representing the declarations of an element's style attributes. CSSStyleDeclaration HTML, XUL
tabIndex Gets/sets the position of the element in the tabbing order. Number HTML
tagName The name of the tag for the given element. String All
textContent Gets/sets the textual contents of an element and all its descendants. String All
title A string that appears in a popup box when mouse is over the element. String HTML

Methods

Name & Description Return Availability
addEventListener( type, listener, useCapture )
Register an event handler to a specific event type on the element.
- All
appendChild( appendedNode )
Insert a node as the last child node of this element.
Node All
blur()
Removes keyboard focus from the current element.
- HTML, XUL
click()
Simulates a click on the current element.
- HTML, XUL
cloneNode( deep )
Clone a node, and optionally, all of its contents.
Node All
compareDocumentPosition ( otherNode ) Number All
dispatchEvent( event )
Dispatch an event to this node in the DOM.
Boolean All
focus()
Gives keyboard focus to the current element.
- HTML, XUL
getAttribute( name )
Retrieve the value of the named attribute from the current node.
Object All
getAttributeNS( namespace, name )
Retrieve the value of the attribute with the specified name and namespace, from the current node.
Object All
getAttributeNode( name )
Retrieve the node representation of the named attribute from the current node.
Attr All
getAttributeNodeNS( namespace, name )
Retrieve the node representation of the attribute with the specified name and namespace, from the current node.
Attr All
getBoundingClientRect ( )
getClientRects ( )
Returns a collection of rectangles that indicate the bounding rectangles for each line of text in a client.
Name & Description Return Availability
getElementsByClassName ( ) NodeList
getElementsByTagName( name )
Retrieve a set of all descendant elements, of a particular tag name, from the current element.
NodeList All
getElementsByTagNameNS( namespace, name )
Retrieve a set of all descendant elements, of a particular tag name and namespace, from the current element.
NodeList All
getFeature ( feature, version  ) Object All
getUserDatakey ) DOMUserData All
hasAttribute( name )
Check if the element has the specified attribute, or not.
Boolean All
hasAttributeNS( namespace, name )
Check if the element has the specified attribute, in the specified namespace, or not.
Boolean All
hasAttributes()
Check if the element has any attributes, or not.
Boolean All
hasChildNodes()
Check if the element has any child nodes, or not.
Boolean All
insertBefore( insertedNode, adjacentNode )
Inserts the first node before the second, child, Node in the DOM.
Node All
isDefaultNamespace ( namespaceURI ) Boolean All
isEqualNode ( nodeArg ) Boolean All
isSameNode ( otherNode Boolean All
isSupported ( feature, version ) Boolean All
lookupNamespaceURI ( prefix ) String All
lookupPrefix ( namespaceURI ) String All
mozMatchesSelector( selector )
Returns whether or not the element would be selected by the specified selector string.
Boolean All
normalize()
Clean up all the text nodes under this element (merge adjacent, remove empty).
- All
querySelector( selectors[, nsresolver] ) New in Firefox 3.5 Node All
querySelectorAll( selectors[, nsresolver] ) New in Firefox 3.5 NodeList All
removeAttribute( name )
Remove the named attribute from the current node.
- All
removeAttributeNS( namespace, name )
Remove the attribute with the specified name and namespace, from the current node.
- All
Name & Description Return Availability
removeAttributeNode( attrNode )
Remove the node representation of the named attribute from the current node.
- All
removeChild( removedNode )
Removes a child node from the current element.
Node All
removeEventListener( type, handler, useCapture )
Removes an event listener from the element.
- All
replaceChild( insertedNode, replacedNode )
Replaces one child node in the current element with another.
Node All
scrollIntoView( alignWithTop )
Scrolls the page until the element gets into the view.
- HTML
setAttribute( name, value )
Set the value of the named attribute from the current node.
- All
setAttributeNS( namespace, name, value )
Set the value of the attribute with the specified name and namespace, from the current node.
- All
setAttributeNode( name, attrNode )
Set the node representation of the named attribute from the current node.
- All
setAttributeNodeNS( namespace, name, attrNode )
Set the node representation of the attribute with the specified name and namespace, from the current node.
- All
setCapture( retargetToElement )
Sets up mouse event capture, redirecting all mouse events to this element.
- All
setIdAttribute (name, isIdBoolean)
Sets the attribute to be treated as an ID type attribute.
- Not supported
setIdAttributeNS ( namespaceURI, localName, isIdBoolean )
Sets the attribute to be treated as an ID type attribute.
- Not supported
setIdAttributeNode ( idAttr, isIdBoolean )
Sets the attribute to be treated as an ID type attribute.
- Not supported
setUserData ( key, data, handler ) DOMUserData All

Event Handlers

These are properties that correspond to the HTML 'on' event attributes.
Unlike the corresponding attributes, the values of these properties are functions (or any other object implementing the EventListener interface) rather than a string. In fact, assigning an event attribute in HTML creates a wrapper function around the specified code. For example, given the following HTML:
click me!
If element is a reference to this div, the value of element.onclick is effectively:
function onclick(event) {
   foo();
}
Note how the event object is passed as parameter event to this wrapper function.
element.onafterscriptexecute Requires Gecko 2.0 Non-standard
The event handling code for the afterscriptexecute event; this is used only for

6 ago 2010

Efectos con Mootools

Dentro de la librería Mootools, nos encontramos los siguientes recursos para construir efectos para nuestras webs:

Clase Fx

La clase Fx es la clase base para el core de Mootools para realizar varias clases derivadas, que implementan diversos tipos de efectos útiles para enriquecer la experiencia de usuario.

Es importante, no obstante, conocer un poco esta clase, o al menos tenerla en cuenta cuando consultemos la documentación de Mootools, porque tiene muchas cosas que son comunes a todas las clases derivadas para hacer efectos.

Clases que heredan de Fx

Fx.CSS

Esta clase tiene funcionalidades para interpretar estilos y clases CSS.
Todos los métodos y propiedades de esta clase son privados.
Sirve para que las otras clases de Fx la utilicen.

Fx.Tween

Una clase que sirve para hacer una transición de cualquier propiedad CSS, de un valor a otro. Con ella podremos hacer efectos con cualquier duración, de modo que su presentación sea suave. Por ejemplo si hacemos un efecto para alterar la propiedad "top" de un elemento de la página, desde el valor 0 al 100, lo que ocurrirá es que el elemento se moverá por la página 100 píxeles hacia abajo, desde el pixel 0 al 100. Si habíamos configurado el estilo con una duración de, por ejemplo, 1 segundo, el movimiento del elemento, desde que está en la posición inicial a que llega a la final, tardará 1 segundo, con lo que el usuario lo verá suavizado.

Fx.Morph

Esta clase es parecida a Fx.Teen, con la diferencia que permite alterar varias propiedades CSS al mismo tiempo.

Fx.Transitions

Para hacer efectos más detallistas, que ajustan el proceso de transición con una función matemática. Por ejemplo esto sirve para hacer un desplazamiento de un elemento, pero donde la velocidad del movimiento no es linear, sino que es por ejemplo exponencial, siendo más rápido al inicio o al final del movimiento. Existen diferentes funciones matemáticas preestablecidas para genera efectos simpáticos, como movimientos con un rebote cuando llegan al final o que se pasan y luego vuelven, como si fuera un elástico.

Método fade()

Podríamos hacer un fundido de opaco a transparente con la sentencia:
$("mielemento").fade("out");

Para hacer un fundido de transparente a opaco, se puede invocar el método fade() de esta manera:
$("mielemento").fade("in");

Método highlight()

$("mielemento").highlight("#ccc");
El método genera un efecto de cambio gradual del color de fondo del elemento, desde su color actual hasta el color que le enviamos por parámetro, volviendo de nuevo a su color original. Si el elemento anteriormente no tenía color asignado, o si era transparente, se toma el blanco como color por defecto del elemento.

$("mielemento").highlight("#f07990","#ccc");
Doble transición de color.

Método tween()

Tiene 3 parámetros:
- nombre de atributo CSS.
- valor inicial, ( con unidades ).
- valor final, ( con unidades ).

El efecto que resultará es una transición entre el valor inicial y el final.

$("micapa").tween("width", "0px", "300px");
Transforma el elemento cuyo id="micapa" en ancho de 0 a 300 px.


$("micapa").tween("width", "300px");
En este caso solo recibe el valor final.

Clase Fx.Tween

Sirve para hacer efectos avanzados.
Para hacer efectos con esta clase tenemos que instanciar un objeto Fx.Tween. Al constructor tenemos que enviarle el identificador del elemento HTML sobre el que queramos hacer los efectos, así como otros datos opcionales que veremos más tarde.

miEfecto = new Fx.Tween("micapa");

Con esto tenemos un objeto en la variable "miEfecto" con el que podemos invocar diversas acciones para realizar transiciones mendiante la alteración de propiedades CSS del elemento "micapa".
Lo más básico que podremos desear hacer con esta clase es poner en marcha un efecto y para ello disponemos del método start(), que podemos usar por ejemplo de esta manera:

miEfecto.start("background-color", "#ff8800");

Datos opcionales

Forma de setear ciertos parámetros avanzados de los efectos Mootools, como definir la duración o la propiedad CSS que se debe alterar cuando se ponga en marcha el efecto.
Todos estos parámetros opcionales se envían en un objeto "options" al constructor.

efectoColorTexto = new Fx.Tween("capatxt", {
property: 'color',
duration: 'long',
fps: 100
});


property: 'color'
Sirve para especificar que la propiedad CSS sobre la que queremos hacer el efecto es "color", para cambiar el color del texto.

duration: 'long'
Sirve para indicar que la duración del efecto debe ser larga ("long" equivale a 1 segundo de duración). Podríamos haber especificado una duración con un número en milisegundos (ms) u otros valores en texto como "normal" que equivale a 500 ms o "short" que equivale a 250 ms.

fps: 100
Con fps indicamos los "frames por segundo", es decir, la cantidad de veces que se actualiza la propiedad CSS en cada segundo que ocupe la transición.

Una vez creado el objeto de la clase Fx.Tween, habría que invocar al método start() para iniciar el efecto, de manera similar a como vimos en el ejemplo anterior. Sin embargo, como en este caso ya hemos indicado la propiedad CSS que se debe alterar en las "options", dentro del la propiedad "property", ya no es necesario indicar esa propiedad en el método start().

efectoColorTexto.start("#ff8800");


Nota: como podremos ver en la documentación de Mootools, el método start() de la clase Fx.Tween recibe como mínimo un parámetro y como máximo tres. El único parámetro que es obligado es el valor de finalización del efecto. Los otros dos parámetros opcionales son el nombre del atributo CSS a alterar y el valor del atributo de inicio para el efecto.

myFx.start([property,] [from,] to);

Eventos de efectos en Mootools

Para codificar comportamientos a realizar en respuesta a eventos tenemos dos posibilidades:

1. Codificar el evento dentro de los "options" enviados al contructor de la clase.

Eventos en la clase Fx y las que heredan de ésta
Los eventos que soportan las clases de efectos en Mootools, es decir, las clases que dependen en la jerarquía de herencia de Fx, son los siguientes:

* Evento start: que se produce cuando el efecto comienza a ejecutarse
* Evento cancel: que se lanza cuando se para manualmente un efecto
* Evento complete: ocurre en el momento que el efecto termina su ejecución
* Evento chainComplete: en caso de encadenar varios eventos con chain, algo que no hemos visto todavía en el manual, se lanza cuando la pila de efectos ha sido completada.

var efecto = new Fx.Tween("capaefectos",{
property: 'width',
duration: 1000,
unit: "px",
onStart: function(){
$("mensaje").set("html", "Comenzando el efecto...");
}
});



2. Codificar el evento por medio del método addEvent() sobre el objeto ya instanciado.

Ahora veremos otro modo posible de asignar eventos, que se hace con el propio evento instanciado y el método addEvent.

efecto.addEvent("complete", function(){
$("mensaje").set("html", "Terminó el efecto.");
});


Con este código conseguimos que al efecto, instanciado en la variable "efecto", se le añada un evento "complete", que se ejecutará cuando el proceso del efecto termine.

El código del evento es bien simple, ya que sólo actualiza el HTML de la capa "mensaje".

Ahora, cuando iniciemos el efecto y éste se complete, se actualizará el texto de la capa mensaje. Sólo nos quedaría llamar al método start() del evento, que invocaremos cuando el usuario haga clic sobre un par de enlaces creados en la página.

$("enlaceencoger").addEvent("click", function(e){
e.stop();
efecto.start(100);
});
$("enlaceestirar").addEvent("click", function(e){
e.stop();
efecto.start(750);
});


Tenemos pues dos enlaces con identificadores "enlaceencoger" y "enlaceestirar", que llaman al método start() del efecto creado anteriormente, enviando el valor numérico que queremos asignar a la propiedad CSS dada de alta en las "options", que era width. Además, como en las "options" ya habíamos asignado las unidades CSS "px", con pasar un valor numérico a start(), será suficiente, porque el efecto ya sabe que son píxeles lo que estamos midiendo.

Podemos ver el código :


window.addEvent("domready", function(){
var efecto = new Fx.Tween("capaefectos",{
property: 'width',
duration: 1000,
unit: "px",
onStart: function(){
$("mensaje").set("html", "Comenzando el efecto...");
}
});
efecto.addEvent("complete", function(){
$("mensaje").set("html", "Terminó el efecto.");
});

$("enlaceencoger").addEvent("click", function(e){
e.stop();
efecto.start(100);
});
$("enlaceestirar").addEvent("click", function(e){
e.stop();
efecto.start(750);
});
});

Y el body tendría algo así
<div id="capaefectos" style="width: 500px; background-color: #ffcc66; padding: 10px; overflow: hidden;">
Esta capa es sobre la que voy a crear los efectos con la clase Fx.Tween, a los que asignaremos diferentes eventos para probar.
</div>
<a href="#" id="enlaceestirar">Estirar capa con efecto</a>
<a href="#" id="enlaceencoger">contraer capa con efecto</a>
<div id="mensaje"></div>