From 3601b7bb982e958927e069715cfe07430bce7196 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Thu, 15 Jul 2021 12:59:34 -0400 Subject: delete pages that were never translated from en-US (es, part 1) (#1547) --- .../tutorial/applying_styles_and_colors/index.html | 727 --------------------- files/es/web/api/constraint_validation/index.html | 154 ----- .../es/web/api/cssrule/parentstylesheet/index.html | 27 - files/es/web/api/datatransfer/index.html | 376 ----------- files/es/web/api/document/evaluate/index.html | 211 ------ files/es/web/api/element/shadowroot/index.html | 83 --- files/es/web/api/file/type/index.html | 72 -- .../onloadedmetadata/index.html | 48 -- files/es/web/api/history_api/example/index.html | 416 ------------ .../getdistributednodes/index.html | 95 --- files/es/web/api/htmlcontentelement/index.html | 110 ---- .../web/api/htmlcontentelement/select/index.html | 95 --- files/es/web/api/htmlelement/innertext/index.html | 84 --- files/es/web/api/htmlhtmlelement/index.html | 121 ---- .../api/htmlmediaelement/abort_event/index.html | 69 -- .../api/keyboardevent/getmodifierstate/index.html | 253 ------- files/es/web/api/keyboardevent/key/index.html | 212 ------ files/es/web/api/navigator/mediadevices/index.html | 49 -- .../web/api/pushmanager/permissionstate/index.html | 111 ---- files/es/web/api/range/intersectsnode/index.html | 48 -- .../using_service_workers/index.html | 526 --------------- .../web/api/serviceworkerregistration/index.html | 145 ---- .../animating_objects_with_webgl/index.html | 119 ---- files/es/web/api/window/sidebar/index.html | 56 -- .../api/windoweventhandlers/onunload/index.html | 46 -- .../web/api/xmlhttprequesteventtarget/index.html | 68 -- .../xmlhttprequesteventtarget/onload/index.html | 55 -- 27 files changed, 4376 deletions(-) delete mode 100644 files/es/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html delete mode 100644 files/es/web/api/constraint_validation/index.html delete mode 100644 files/es/web/api/cssrule/parentstylesheet/index.html delete mode 100644 files/es/web/api/datatransfer/index.html delete mode 100644 files/es/web/api/document/evaluate/index.html delete mode 100644 files/es/web/api/element/shadowroot/index.html delete mode 100644 files/es/web/api/file/type/index.html delete mode 100644 files/es/web/api/globaleventhandlers/onloadedmetadata/index.html delete mode 100644 files/es/web/api/history_api/example/index.html delete mode 100644 files/es/web/api/htmlcontentelement/getdistributednodes/index.html delete mode 100644 files/es/web/api/htmlcontentelement/index.html delete mode 100644 files/es/web/api/htmlcontentelement/select/index.html delete mode 100644 files/es/web/api/htmlelement/innertext/index.html delete mode 100644 files/es/web/api/htmlhtmlelement/index.html delete mode 100644 files/es/web/api/htmlmediaelement/abort_event/index.html delete mode 100644 files/es/web/api/keyboardevent/getmodifierstate/index.html delete mode 100644 files/es/web/api/keyboardevent/key/index.html delete mode 100644 files/es/web/api/navigator/mediadevices/index.html delete mode 100644 files/es/web/api/pushmanager/permissionstate/index.html delete mode 100644 files/es/web/api/range/intersectsnode/index.html delete mode 100644 files/es/web/api/service_worker_api/using_service_workers/index.html delete mode 100644 files/es/web/api/serviceworkerregistration/index.html delete mode 100644 files/es/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html delete mode 100644 files/es/web/api/window/sidebar/index.html delete mode 100644 files/es/web/api/windoweventhandlers/onunload/index.html delete mode 100644 files/es/web/api/xmlhttprequesteventtarget/index.html delete mode 100644 files/es/web/api/xmlhttprequesteventtarget/onload/index.html (limited to 'files/es/web/api') diff --git a/files/es/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html b/files/es/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html deleted file mode 100644 index 089f74510c..0000000000 --- a/files/es/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html +++ /dev/null @@ -1,727 +0,0 @@ ---- -title: Applying styles and colors -slug: Web/API/Canvas_API/Tutorial/Applying_styles_and_colors -translation_of: Web/API/Canvas_API/Tutorial/Applying_styles_and_colors -original_slug: Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors ---- -
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_shapes", "Web/API/Canvas_API/Tutorial/Drawing_text")}}
- -
-

En el capítulo acerca de dibujar formas, usamos unicamente los estilos de linea y de relleno por defecto. Aqui exploraremos las opciones del canvas que tenemos a nuestra disposición para hacer los dibujos un tanto más atractivos. Aprenderas como agregar diferentes colores, estilos de linea, gradiantes, patrones y sombras a tus dibujos.

-
- -

Colors

- -

Hasta ahrora nosotros solo me hemos visto metodos en el contexto de dibujo. Si quisieramos aplicar colores a las formas, hay dos importantes propiedades que podemos usar: fillStyle y strokeStyle.

- -
-
{{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle = color")}}
-
Configura el estilo cuando se rellenan las formas.
-
{{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle = color")}}
-
Configura el estilo al contorno perimetral de las formas.
-
- -

color es una cadena que representa  un CSS {{cssxref("<color>")}}, un objeto gradiante, o un objeto patron. Miraremos en objetos de gradientes y patrones mas tarde. Por defecto, el color del trazo y del relleno son configurados en negro (valor de color CSS #000000).

- -
-

Nota:  Cuando configuras la propiedad  strokeStyle y/o fillStyle, el nuevo valor llega a ser el vador por defecto para los dibujos posteriores. Para cada forma que tu quieras en un color difrente, necesitaras reasignar las propiedades anteriores.

-
- -

Las cadenas validas que tu pueden entrar deberian, segun la especificación, ser valores de  {{cssxref("<color>")}} CSS. En el siguiente ejemplo, describimos en mismo color.

- -
// these all set the fillStyle to 'orange'
-
-ctx.fillStyle = 'orange';
-ctx.fillStyle = '#FFA500';
-ctx.fillStyle = 'rgb(255, 165, 0)';
-ctx.fillStyle = 'rgba(255, 165, 0, 1)';
-
- -

A fillStyle example

- -

En este ejemplo, usamos dos bucles for para dibujar una cuadrícula de rectangulos, cada uno de diferente color. La imagen resultante deberia ser similar a la de la screenhot. No hay nada demasiado espectacular en el proceso. Usamos dos variables i y j para generar un unico color RGB para cada celda cuadrada, modificando las componentes rojo y verde. El canal azul tiene un valor fijo. Modificando los canales, puedes generar todo tipo de paletas. Incrementando los paos, puedes lograr algo similar que se parezca a las paletas de colores que Photoshop usa.

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-  for (var i = 0; i < 6; i++) {
-    for (var j = 0; j < 6; j++) {
-      ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ', ' +
-                       Math.floor(255 - 42.5 * j) + ', 0)';
-      ctx.fillRect(j * 25, i * 25, 25, 25);
-    }
-  }
-}
- - - -

The result looks like this:

- -

{{EmbedLiveSample("A_fillStyle_example", 160, 160, "https://mdn.mozillademos.org/files/5417/Canvas_fillstyle.png")}}

- -

A strokeStyle example

- -

Este ejemplo es similar al de arriba, pero usa la propiedad  strokeStyle para cambiar el color del contorno de las formas. Usamos el método  arc() para dibujar circulos en lugar de celdas cuadradas.

- -
  function draw() {
-    var ctx = document.getElementById('canvas').getContext('2d');
-    for (var i = 0; i < 6; i++) {
-      for (var j = 0; j < 6; j++) {
-        ctx.strokeStyle = 'rgb(0, ' + Math.floor(255 - 42.5 * i) + ', ' +
-                         Math.floor(255 - 42.5 * j) + ')';
-        ctx.beginPath();
-        ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true);
-        ctx.stroke();
-      }
-    }
-  }
-
- - - -

The result looks like this:

- -

{{EmbedLiveSample("A_strokeStyle_example", "180", "180", "https://mdn.mozillademos.org/files/253/Canvas_strokestyle.png")}}

- -

Transparency

- -

Ademas de dibujar formas opacas en el canvas, podemos dibujar formas semi-transparentes(o translucidas). Esto se logra bien configurando la propiedad  globalAlpha o asignando un color semi-transparente al estilo del trazo u  u/y al de relleno.

- -
-
{{domxref("CanvasRenderingContext2D.globalAlpha", "globalAlpha = transparencyValue")}}
-
Applies the specified transparency value to all future shapes drawn on the canvas. The value must be between 0.0 (fully transparent) to 1.0 (fully opaque). This value is 1.0 (fully opaque) by default.
-
- -

The globalAlpha property can be useful if you want to draw a lot of shapes on the canvas with similar transparency, but otherwise it's generally more useful to set the transparency on individual shapes when setting their colors.

- -

Debido qaque las propiedades  strokeStyle y fillStyle aceptan valores de color rgba de CSS, podemos usar la siguiente notacion para asignar una color transparente a ellos.

- -
// Assigning transparent colors to stroke and fill style
-
-ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)';
-ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
-
- -

The rgba() function is similar to the rgb() function but it has one extra parameter. The last parameter sets the transparency value of this particular color. The valid range is again between 0.0 (fully transparent) and 1.0 (fully opaque).

- -

A globalAlpha example

- -

In this example, we'll draw a background of four different colored squares. On top of these, we'll draw a set of semi-transparent circles. The globalAlpha property is set at 0.2 which will be used for all shapes from that point on. Every step in the for loop draws a set of circles with an increasing radius. The final result is a radial gradient. By overlaying ever more circles on top of each other, we effectively reduce the transparency of the circles that have already been drawn. By increasing the step count and in effect drawing more circles, the background would completely disappear from the center of the image.

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-  // draw background
-  ctx.fillStyle = '#FD0';
-  ctx.fillRect(0, 0, 75, 75);
-  ctx.fillStyle = '#6C0';
-  ctx.fillRect(75, 0, 75, 75);
-  ctx.fillStyle = '#09F';
-  ctx.fillRect(0, 75, 75, 75);
-  ctx.fillStyle = '#F30';
-  ctx.fillRect(75, 75, 75, 75);
-  ctx.fillStyle = '#FFF';
-
-  // set transparency value
-  ctx.globalAlpha = 0.2;
-
-  // Draw semi transparent circles
-  for (var i = 0; i < 7; i++) {
-    ctx.beginPath();
-    ctx.arc(75, 75, 10 + 10 * i, 0, Math.PI * 2, true);
-    ctx.fill();
-  }
-}
- - - -

{{EmbedLiveSample("A_globalAlpha_example", "180", "180", "https://mdn.mozillademos.org/files/232/Canvas_globalalpha.png")}}

- -

An example using rgba()

- -

In this second example, we do something similar to the one above, but instead of drawing circles on top of each other, I've drawn small rectangles with increasing opacity. Using rgba() gives you a little more control and flexibility because we can set the fill and stroke style individually.

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-
-  // Draw background
-  ctx.fillStyle = 'rgb(255, 221, 0)';
-  ctx.fillRect(0, 0, 150, 37.5);
-  ctx.fillStyle = 'rgb(102, 204, 0)';
-  ctx.fillRect(0, 37.5, 150, 37.5);
-  ctx.fillStyle = 'rgb(0, 153, 255)';
-  ctx.fillRect(0, 75, 150, 37.5);
-  ctx.fillStyle = 'rgb(255, 51, 0)';
-  ctx.fillRect(0, 112.5, 150, 37.5);
-
-  // Draw semi transparent rectangles
-  for (var i = 0; i < 10; i++) {
-    ctx.fillStyle = 'rgba(255, 255, 255, ' + (i + 1) / 10 + ')';
-    for (var j = 0; j < 4; j++) {
-      ctx.fillRect(5 + i * 14, 5 + j * 37.5, 14, 27.5);
-    }
-  }
-}
- - - -

{{EmbedLiveSample("An_example_using_rgba()", "180", "180", "https://mdn.mozillademos.org/files/246/Canvas_rgba.png")}}

- -

Line styles

- -

There are several properties which allow us to style lines.

- -
-
{{domxref("CanvasRenderingContext2D.lineWidth", "lineWidth = value")}}
-
Sets the width of lines drawn in the future.
-
{{domxref("CanvasRenderingContext2D.lineCap", "lineCap = type")}}
-
Sets the appearance of the ends of lines.
-
{{domxref("CanvasRenderingContext2D.lineJoin", "lineJoin = type")}}
-
Sets the appearance of the "corners" where lines meet.
-
{{domxref("CanvasRenderingContext2D.miterLimit", "miterLimit = value")}}
-
Establishes a limit on the miter when two lines join at a sharp angle, to let you control how thick the junction becomes.
-
{{domxref("CanvasRenderingContext2D.getLineDash", "getLineDash()")}}
-
Returns the current line dash pattern array containing an even number of non-negative numbers.
-
{{domxref("CanvasRenderingContext2D.setLineDash", "setLineDash(segments)")}}
-
Sets the current line dash pattern.
-
{{domxref("CanvasRenderingContext2D.lineDashOffset", "lineDashOffset = value")}}
-
Specifies where to start a dash array on a line.
-
- -

You'll get a better understanding of what these do by looking at the examples below.

- -

A lineWidth example

- -

This property sets the current line thickness. Values must be positive numbers. By default this value is set to 1.0 units.

- -

The line width is the thickness of the stroke centered on the given path. In other words, the area that's drawn extends to half the line width on either side of the path. Because canvas coordinates do not directly reference pixels, special care must be taken to obtain crisp horizontal and vertical lines.

- -

In the example below, 10 straight lines are drawn with increasing line widths. The line on the far left is 1.0 units wide. However, the leftmost and all other odd-integer-width thickness lines do not appear crisp, because of the path's positioning.

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-  for (var i = 0; i < 10; i++) {
-    ctx.lineWidth = 1 + i;
-    ctx.beginPath();
-    ctx.moveTo(5 + i * 14, 5);
-    ctx.lineTo(5 + i * 14, 140);
-    ctx.stroke();
-  }
-}
-
- - - -

{{EmbedLiveSample("A_lineWidth_example", "180", "180", "https://mdn.mozillademos.org/files/239/Canvas_linewidth.png")}}

- -

Obtaining crisp lines requires understanding how paths are stroked. In the images below, the grid represents the canvas coordinate grid. The squares between gridlines are actual on-screen pixels. In the first grid image below, a rectangle from (2,1) to (5,5) is filled. The entire area between them (light red) falls on pixel boundaries, so the resulting filled rectangle will have crisp edges.

- -

- -

If you consider a path from (3,1) to (3,5) with a line thickness of 1.0, you end up with the situation in the second image. The actual area to be filled (dark blue) only extends halfway into the pixels on either side of the path. An approximation of this has to be rendered, which means that those pixels being only partially shaded, and results in the entire area (the light blue and dark blue) being filled in with a color only half as dark as the actual stroke color. This is what happens with the 1.0 width line in the previous example code.

- -

To fix this, you have to be very precise in your path creation. Knowing that a 1.0 width line will extend half a unit to either side of the path, creating the path from (3.5,1) to (3.5,5) results in the situation in the third image—the 1.0 line width ends up completely and precisely filling a single pixel vertical line.

- -
-

Note: Be aware that in our vertical line example, the Y position still referenced an integer gridline position—if it hadn't, we would see pixels with half coverage at the endpoints (but note also that this behavior depends on the current lineCap style whose default value is butt; you may want to compute consistent strokes with half-pixel coordinates for odd-width lines, by setting the lineCap style to square, so that the outer border of the stroke around the endpoint will be automatically extended to cover the whole pixel exactly).

- -

Note also that only start and final endpoints of a path are affected: if a path is closed with closePath(), there's no start and final endpoint; instead, all endpoints in the path are connected to their attached previous and next segment using the current setting of the lineJoin style, whose default value is miter, with the effect of automatically extending the outer borders of the connected segments to their intersection point, so that the rendered stroke will exactly cover full pixels centered at each endpoint if those connected segments are horizontal and/or vertical). See the next two sections for demonstrations of these additional line styles.

-
- -

For even-width lines, each half ends up being an integer amount of pixels, so you want a path that is between pixels (that is, (3,1) to (3,5)), instead of down the middle of pixels.

- -

While slightly painful when initially working with scalable 2D graphics, paying attention to the pixel grid and the position of paths ensures that your drawings will look correct regardless of scaling or any other transformations involved. A 1.0-width vertical line drawn at the correct position will become a crisp 2-pixel line when scaled up by 2, and will appear at the correct position.

- -

A lineCap example

- -

The lineCap property determines how the end points of every line are drawn. There are three possible values for this property and those are: butt, round and square. By default this property is set to butt.

- -

- -
-
butt
-
The ends of lines are squared off at the endpoints.
-
round
-
The ends of lines are rounded.
-
square
-
The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness.
-
- -

In this example, we'll draw three lines, each with a different value for the lineCap property. I also added two guides to see the exact differences between the three. Each of these lines starts and ends exactly on these guides.

- -

The line on the left uses the default butt option. You'll notice that it's drawn completely flush with the guides. The second is set to use the round option. This adds a semicircle to the end that has a radius half the width of the line. The line on the right uses the square option. This adds a box with an equal width and half the height of the line thickness.

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-  var lineCap = ['butt', 'round', 'square'];
-
-  // Draw guides
-  ctx.strokeStyle = '#09f';
-  ctx.beginPath();
-  ctx.moveTo(10, 10);
-  ctx.lineTo(140, 10);
-  ctx.moveTo(10, 140);
-  ctx.lineTo(140, 140);
-  ctx.stroke();
-
-  // Draw lines
-  ctx.strokeStyle = 'black';
-  for (var i = 0; i < lineCap.length; i++) {
-    ctx.lineWidth = 15;
-    ctx.lineCap = lineCap[i];
-    ctx.beginPath();
-    ctx.moveTo(25 + i * 50, 10);
-    ctx.lineTo(25 + i * 50, 140);
-    ctx.stroke();
-  }
-}
-
- - - -

{{EmbedLiveSample("A_lineCap_example", "180", "180", "https://mdn.mozillademos.org/files/236/Canvas_linecap.png")}}

- -

A lineJoin example

- -

The lineJoin property determines how two connecting segments (of lines, arcs or curves) with non-zero lengths in a shape are joined together (degenerate segments with zero lengths, whose specified endpoints and control points are exactly at the same position, are skipped).

- -

There are three possible values for this property: round, bevel and miter. By default this property is set to miter. Note that the lineJoin setting has no effect if the two connected segments have the same direction, because no joining area will be added in this case.

- -

- -
-
round
-
Rounds off the corners of a shape by filling an additional sector of disc centered at the common endpoint of connected segments. The radius for these rounded corners is equal to half the line width.
-
bevel
-
Fills an additional triangular area between the common endpoint of connected segments, and the separate outside rectangular corners of each segment.
-
miter
-
Connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area. This setting is effected by the miterLimit property which is explained below.
-
- -

The example below draws three different paths, demonstrating each of these three lineJoin property settings; the output is shown above.

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-  var lineJoin = ['round', 'bevel', 'miter'];
-  ctx.lineWidth = 10;
-  for (var i = 0; i < lineJoin.length; i++) {
-    ctx.lineJoin = lineJoin[i];
-    ctx.beginPath();
-    ctx.moveTo(-5, 5 + i * 40);
-    ctx.lineTo(35, 45 + i * 40);
-    ctx.lineTo(75, 5 + i * 40);
-    ctx.lineTo(115, 45 + i * 40);
-    ctx.lineTo(155, 5 + i * 40);
-    ctx.stroke();
-  }
-}
-
- - - -

{{EmbedLiveSample("A_lineJoin_example", "180", "180", "https://mdn.mozillademos.org/files/237/Canvas_linejoin.png")}}

- -

A demo of the miterLimit property

- -

As you've seen in the previous example, when joining two lines with the miter option, the outside edges of the two joining lines are extended up to the point where they meet. For lines which are at large angles with each other, this point is not far from the inside connection point. However, as the angles between each line decreases, the distance (miter length) between these points increases exponentially.

- -

The miterLimit property determines how far the outside connection point can be placed from the inside connection point. If two lines exceed this value, a bevel join gets drawn instead. Note that the maximum miter length is the product of the line width measured in the current coordinate system, by the value of this miterLimit property (whose default value is 10.0 in the HTML {{HTMLElement("canvas")}}), so the miterLimit can be set independently from the current display scale or any affine transforms of paths: it only influences the effectively rendered shape of line edges.

- -

More exactly, the miter limit is the maximum allowed ratio of the extension length (in the HTML canvas, it is measured between the outside corner of the joined edges of the line and the common endpoint of connecting segments specified in the path) to half the line width. It can equivalently be defined as the maximum allowed ratio of the distance between the inside and outside points of jonction of edges, to the total line width. It is then equal to the cosecant of half the minimum inner angle of connecting segments below which no miter join will be rendered, but only a bevel join:

- - - -

Here's a little demo in which you can set miterLimit dynamically and see how this effects the shapes on the canvas. The blue lines show where the start and endpoints for each of the lines in the zig-zag pattern are.

- -

If you specify a miterLimit value below 4.2 in this demo, none of the visible corners will join with a miter extension, but only with a small bevel near the blue lines; with a miterLimit above 10, most corners in this demo should join with a miter far away from the blue lines, and whose height is decreasing between corners from left to right because they connect with growing angles; with intermediate values, the corners on the left side will only join with a bevel near the blue lines, and the corners on the right side with a miter extension (also with a decreasing height).

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-
-  // Clear canvas
-  ctx.clearRect(0, 0, 150, 150);
-
-  // Draw guides
-  ctx.strokeStyle = '#09f';
-  ctx.lineWidth   = 2;
-  ctx.strokeRect(-5, 50, 160, 50);
-
-  // Set line styles
-  ctx.strokeStyle = '#000';
-  ctx.lineWidth = 10;
-
-  // check input
-  if (document.getElementById('miterLimit').value.match(/\d+(\.\d+)?/)) {
-    ctx.miterLimit = parseFloat(document.getElementById('miterLimit').value);
-  } else {
-    alert('Value must be a positive number');
-  }
-
-  // Draw lines
-  ctx.beginPath();
-  ctx.moveTo(0, 100);
-  for (i = 0; i < 24 ; i++) {
-    var dy = i % 2 == 0 ? 25 : -25;
-    ctx.lineTo(Math.pow(i, 1.5) * 2, 75 + dy);
-  }
-  ctx.stroke();
-  return false;
-}
-
- - - -

{{EmbedLiveSample("A_demo_of_the_miterLimit_property", "400", "180", "https://mdn.mozillademos.org/files/240/Canvas_miterlimit.png")}}

- -

Using line dashes

- -

The setLineDash method and the lineDashOffset property specify the dash pattern for lines. The setLineDash method accepts a list of numbers that specifies distances to alternately draw a line and a gap and the lineDashOffset property sets an offset where to start the pattern.

- -

In this example we are creating a marching ants effect. It is an animation technique often found in selection tools of computer graphics programs. It helps the user to distinguish the selection border from the image background by animating the border. In a later part of this tutorial, you can learn how to do this and other basic animations.

- - - -
var ctx = document.getElementById('canvas').getContext('2d');
-var offset = 0;
-
-function draw() {
-  ctx.clearRect(0, 0, canvas.width, canvas.height);
-  ctx.setLineDash([4, 2]);
-  ctx.lineDashOffset = -offset;
-  ctx.strokeRect(10, 10, 100, 100);
-}
-
-function march() {
-  offset++;
-  if (offset > 16) {
-    offset = 0;
-  }
-  draw();
-  setTimeout(march, 20);
-}
-
-march();
- -

{{EmbedLiveSample("Using_line_dashes", "120", "120", "https://mdn.mozillademos.org/files/9853/marching-ants.png")}}

- -

Gradients

- -

Just like any normal drawing program, we can fill and stroke shapes using linear and radial gradients. We create a {{domxref("CanvasGradient")}} object by using one of the following methods. We can then assign this object to the fillStyle or strokeStyle properties.

- -
-
{{domxref("CanvasRenderingContext2D.createLinearGradient", "createLinearGradient(x1, y1, x2, y2)")}}
-
Creates a linear gradient object with a starting point of (x1, y1) and an end point of (x2, y2).
-
{{domxref("CanvasRenderingContext2D.createRadialGradient", "createRadialGradient(x1, y1, r1, x2, y2, r2)")}}
-
Creates a radial gradient. The parameters represent two circles, one with its center at (x1, y1) and a radius of r1, and the other with its center at (x2, y2) with a radius of r2.
-
- -

For example:

- -
var lineargradient = ctx.createLinearGradient(0, 0, 150, 150);
-var radialgradient = ctx.createRadialGradient(75, 75, 0, 75, 75, 100);
-
- -

Once we've created a CanvasGradient object we can assign colors to it by using the addColorStop() method.

- -
-
{{domxref("CanvasGradient.addColorStop", "gradient.addColorStop(position, color)")}}
-
Creates a new color stop on the gradient object. The position is a number between 0.0 and 1.0 and defines the relative position of the color in the gradient, and the color argument must be a string representing a CSS {{cssxref("<color>")}}, indicating the color the gradient should reach at that offset into the transition.
-
- -

You can add as many color stops to a gradient as you need. Below is a very simple linear gradient from white to black.

- -
var lineargradient = ctx.createLinearGradient(0, 0, 150, 150);
-lineargradient.addColorStop(0, 'white');
-lineargradient.addColorStop(1, 'black');
-
- -

A createLinearGradient example

- -

In this example, we'll create two different gradients. As you can see here, both the strokeStyle and fillStyle properties can accept a canvasGradient object as valid input.

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-
-  // Create gradients
-  var lingrad = ctx.createLinearGradient(0, 0, 0, 150);
-  lingrad.addColorStop(0, '#00ABEB');
-  lingrad.addColorStop(0.5, '#fff');
-  lingrad.addColorStop(0.5, '#26C000');
-  lingrad.addColorStop(1, '#fff');
-
-  var lingrad2 = ctx.createLinearGradient(0, 50, 0, 95);
-  lingrad2.addColorStop(0.5, '#000');
-  lingrad2.addColorStop(1, 'rgba(0, 0, 0, 0)');
-
-  // assign gradients to fill and stroke styles
-  ctx.fillStyle = lingrad;
-  ctx.strokeStyle = lingrad2;
-
-  // draw shapes
-  ctx.fillRect(10, 10, 130, 130);
-  ctx.strokeRect(50, 50, 50, 50);
-
-}
-
- - - -

The first is a background gradient. As you can see, we assigned two colors at the same position. You do this to make very sharp color transitions—in this case from white to green. Normally, it doesn't matter in what order you define the color stops, but in this special case, it does significantly. If you keep the assignments in the order you want them to appear, this won't be a problem.

- -

In the second gradient, we didn't assign the starting color (at position 0.0) since it wasn't strictly necessary, because it will automatically assume the color of the next color stop. Therefore, assigning the black color at position 0.5 automatically makes the gradient, from the start to this stop, black.

- -

{{EmbedLiveSample("A_createLinearGradient_example", "180", "180", "https://mdn.mozillademos.org/files/235/Canvas_lineargradient.png")}}

- -

A createRadialGradient example

- -

In this example, we'll define four different radial gradients. Because we have control over the start and closing points of the gradient, we can achieve more complex effects than we would normally have in the "classic" radial gradients we see in, for instance, Photoshop (that is, a gradient with a single center point where the gradient expands outward in a circular shape).

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-
-  // Create gradients
-  var radgrad = ctx.createRadialGradient(45, 45, 10, 52, 50, 30);
-  radgrad.addColorStop(0, '#A7D30C');
-  radgrad.addColorStop(0.9, '#019F62');
-  radgrad.addColorStop(1, 'rgba(1, 159, 98, 0)');
-
-  var radgrad2 = ctx.createRadialGradient(105, 105, 20, 112, 120, 50);
-  radgrad2.addColorStop(0, '#FF5F98');
-  radgrad2.addColorStop(0.75, '#FF0188');
-  radgrad2.addColorStop(1, 'rgba(255, 1, 136, 0)');
-
-  var radgrad3 = ctx.createRadialGradient(95, 15, 15, 102, 20, 40);
-  radgrad3.addColorStop(0, '#00C9FF');
-  radgrad3.addColorStop(0.8, '#00B5E2');
-  radgrad3.addColorStop(1, 'rgba(0, 201, 255, 0)');
-
-  var radgrad4 = ctx.createRadialGradient(0, 150, 50, 0, 140, 90);
-  radgrad4.addColorStop(0, '#F4F201');
-  radgrad4.addColorStop(0.8, '#E4C700');
-  radgrad4.addColorStop(1, 'rgba(228, 199, 0, 0)');
-
-  // draw shapes
-  ctx.fillStyle = radgrad4;
-  ctx.fillRect(0, 0, 150, 150);
-  ctx.fillStyle = radgrad3;
-  ctx.fillRect(0, 0, 150, 150);
-  ctx.fillStyle = radgrad2;
-  ctx.fillRect(0, 0, 150, 150);
-  ctx.fillStyle = radgrad;
-  ctx.fillRect(0, 0, 150, 150);
-}
-
- - - -

In this case, we've offset the starting point slightly from the end point to achieve a spherical 3D effect. It's best to try to avoid letting the inside and outside circles overlap because this results in strange effects which are hard to predict.

- -

The last color stop in each of the four gradients uses a fully transparent color. If you want to have a nice transition from this to the previous color stop, both colors should be equal. This isn't very obvious from the code because it uses two different CSS color methods as a demonstration, but in the first gradient #019F62 = rgba(1,159,98,1).

- -

{{EmbedLiveSample("A_createRadialGradient_example", "180", "180", "https://mdn.mozillademos.org/files/244/Canvas_radialgradient.png")}}

- -

Patterns

- -

In one of the examples on the previous page, we used a series of loops to create a pattern of images. There is, however, a much simpler method: the createPattern() method.

- -
-
{{domxref("CanvasRenderingContext2D.createPattern", "createPattern(image, type)")}}
-
Creates and returns a new canvas pattern object. image is a {{domxref("CanvasImageSource")}} (that is, an {{domxref("HTMLImageElement")}}, another canvas, a {{HTMLElement("video")}} element, or the like. type is a string indicating how to use the image.
-
- -

The type specifies how to use the image in order to create the pattern, and must be one of the following string values:

- -
-
repeat
-
Tiles the image in both vertical and horizontal directions.
-
repeat-x
-
Tiles the image horizontally but not vertically.
-
repeat-y
-
Tiles the image vertically but not horizontally.
-
no-repeat
-
Doesn't tile the image. It's used only once.
-
- -

We use this method to create a {{domxref("CanvasPattern")}} object which is very similar to the gradient methods we've seen above. Once we've created a pattern, we can assign it to the fillStyle or strokeStyle properties. For example:

- -
var img = new Image();
-img.src = 'someimage.png';
-var ptrn = ctx.createPattern(img, 'repeat');
-
- -
-

Note: Like with the drawImage() method, you must make sure the image you use is loaded before calling this method or the pattern may be drawn incorrectly.

-
- -

A createPattern example

- -

In this last example, we'll create a pattern to assign to the fillStyle property. The only thing worth noting is the use of the image's onload handler. This is to make sure the image is loaded before it is assigned to the pattern.

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-
-  // create new image object to use as pattern
-  var img = new Image();
-  img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
-  img.onload = function() {
-
-    // create pattern
-    var ptrn = ctx.createPattern(img, 'repeat');
-    ctx.fillStyle = ptrn;
-    ctx.fillRect(0, 0, 150, 150);
-
-  }
-}
-
- - - -

{{EmbedLiveSample("A_createPattern_example", "180", "180", "https://mdn.mozillademos.org/files/222/Canvas_createpattern.png")}}

- -

Shadows

- -

Using shadows involves just four properties:

- -
-
{{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX = float")}}
-
Indicates the horizontal distance the shadow should extend from the object. This value isn't affected by the transformation matrix. The default is 0.
-
{{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY = float")}}
-
Indicates the vertical distance the shadow should extend from the object. This value isn't affected by the transformation matrix. The default is 0.
-
{{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur = float")}}
-
Indicates the size of the blurring effect; this value doesn't correspond to a number of pixels and is not affected by the current transformation matrix. The default value is 0.
-
{{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor = color")}}
-
A standard CSS color value indicating the color of the shadow effect; by default, it is fully-transparent black.
-
- -

The properties shadowOffsetX and shadowOffsetY indicate how far the shadow should extend from the object in the X and Y directions; these values aren't affected by the current transformation matrix. Use negative values to cause the shadow to extend up or to the left, and positive values to cause the shadow to extend down or to the right. These are both 0 by default.

- -

The shadowBlur property indicates the size of the blurring effect; this value doesn't correspond to a number of pixels and is not affected by the current transformation matrix. The default value is 0.

- -

The shadowColor property is a standard CSS color value indicating the color of the shadow effect; by default, it is fully-transparent black.

- -
-

Note: Shadows are only drawn for source-over compositing operations.

-
- -

A shadowed text example

- -

This example draws a text string with a shadowing effect.

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-
-  ctx.shadowOffsetX = 2;
-  ctx.shadowOffsetY = 2;
-  ctx.shadowBlur = 2;
-  ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
-
-  ctx.font = '20px Times New Roman';
-  ctx.fillStyle = 'Black';
-  ctx.fillText('Sample String', 5, 30);
-}
-
- - - -

{{EmbedLiveSample("A_shadowed_text_example", "180", "100", "https://mdn.mozillademos.org/files/2505/shadowed-string.png")}}

- -

We will look at the font property and fillText method in the next chapter about drawing text.

- -

Canvas fill rules

- -

When using fill (or {{domxref("CanvasRenderingContext2D.clip", "clip")}} and {{domxref("CanvasRenderingContext2D.isPointInPath", "isPointinPath")}}) you can optionally provide a fill rule algorithm by which to determine if a point is inside or outside a path and thus if it gets filled or not. This is useful when a path intersects itself or is nested.
-
- Two values are possible:

- - - -

In this example we are using the evenodd rule.

- -
function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-  ctx.beginPath();
-  ctx.arc(50, 50, 30, 0, Math.PI * 2, true);
-  ctx.arc(50, 50, 15, 0, Math.PI * 2, true);
-  ctx.fill('evenodd');
-}
- - - -

{{EmbedLiveSample("Canvas_fill_rules", "110", "110", "https://mdn.mozillademos.org/files/9855/fill-rule.png")}}

- -

{{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_shapes", "Web/API/Canvas_API/Tutorial/Drawing_text")}}

diff --git a/files/es/web/api/constraint_validation/index.html b/files/es/web/api/constraint_validation/index.html deleted file mode 100644 index 81811b4891..0000000000 --- a/files/es/web/api/constraint_validation/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: Constraint validation API -slug: Web/API/Constraint_validation -tags: - - API - - Constraint validation - - Landing - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/API/Constraint_validation ---- -
{{apiref()}}
- -

The Constraint Validation API enables checking values that users have entered into form controls, before submitting the values to the server.

- -

Concepts and usage

- -

Certain HTML form controls, such as {{HTMLElement("input")}}, {{HTMLElement("select")}} and {{HTMLElement("textarea")}}, can restrict the format of allowable values, using attributes like required and pattern to set basic constraints.

- -

However, you may want to impose more complex constraints, or to provide clearer reporting of validation failures than the defaults. This can be done using the Constraint Validation API.

- -
-

Note: Client-side constraint validation doesn't remove the need for validation on the server side. Even though client-side validation can prevent many common kinds of invalid values, invalid ones can still be sent by older browsers or by attackers trying to trick your web application. Therefore, you need to also validate input values on the server side, in a way that is consistent with what is done on the client side. Client side validation is a tool for giving quick feedback to the user. You should not rely on it to completely sanitize data received by the server.

-
- -

Validation of constraints through the constraint validation API is done either on a single form element or at the form level, on the {{ HTMLElement("form") }} element itself.

- -

Constraint validation interfaces

- -
-
ValidityState
-
The ValidityState interface represents the validity states that a form control element can have, with respect to its defined constraints. Together, they help explain whether and why an element's value fails to validate.
-
invalid event
-
This event type is fired at a form control element if the element does not satisfy its constraints.
-
- -

Extensions to other interfaces

- -

The constraint validation API extends the interfaces for the form-associated elements listed below with a number of new properties and methods (elements that can have a form attribute that indicates their form owner):

- - - -

Properties

- -
-
validity
-
A read-only properity that returns a ValidityState object, whose properties represent validation errors for the value of that element.
-
validationMessage
-
A read-only property that returns an empty string if the element is not a candidate for constraint validation, or if the element's value is valid. If the element's value is not valid, it returns a localized validation message. This will be displayed in the UI if the element is the only form control with a validity problem; if a custom error message is set using setCustomValidity(), this will be shown.
-
willValidate
-
A read-only boolean property that returns true if the element is a candidate for constraint validation; and false otherwise. Elements with the HTMLObjectElement interface are never candidates for constraint validation. Others may be barred from constraint validation depending on specific conditions.
-
- -

Methods

- -
-
checkValidity()
-
Checks the element's value against its constraints. If the value is invalid, it fires an invalid event at the element and returns false; otherwise it returns true.
-
reportValidity()
-
Checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available. Otherwise, it returns true.
-
setCustomValidity(message)
-
Sets a custom error message string to be shown to the user upon submitting the form, explaining why the value is not valid — when a message is set, the validity state is set to invalid. To clear this state, invoke the function with an empty string passed as its argument. In this case the custom error message is cleared, the element is considered valid, and no message is shown.
-
- -

Examples

- -

Take the following form:

- -
<form>
-  <label for="name">Enter username (upper and lowercase letters): </label>
-  <input type="text" name="name" id="name" required pattern="[A-Za-z]+">
-  <button>Submit</button>
-</form>
- -

The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern.

- -

If you wanted to instead display custom error messages, you could use JavaScript like the following:

- -
const nameInput = document.querySelector('input');
-const form = document.querySelector('form');
-
-nameInput.addEventListener('input', () => {
-  nameInput.setCustomValidity('');
-  nameInput.checkValidity();
-});
-
-nameInput.addEventListener('invalid', () => {
-  if(nameInput.value === '') {
-    nameInput.setCustomValidity('Enter your username!');
-  } else {
-    nameInput.setCustomValidity('Usernames can only contain upper and lowercase letters. Try again!');
-  }
-});
- -

The example renders like so:

- -

{{EmbedLiveSample('Examples')}}

- -

In brief:

- - - -
-

Note: Firefox supported a proprietary error attribute — x-moz-errormessage — for many versions, which allowed you set custom error messages in a similar way. This has been removed as of version 66 (see bug 1513890).

-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{ SpecName('HTML WHATWG', 'forms.html#the-constraint-validation-api', 'constraint validation API') }}{{Spec2('HTML WHATWG')}} 
{{ SpecName('HTML5.1', 'sec-forms.html#the-constraint-validation-api', 'constraint validation API') }}{{Spec2('HTML5.1')}}No change from the previous snapshot {{SpecName('HTML5 W3C')}}.
{{ SpecName('HTML5 W3C', 'forms.html#the-constraint-validation-api', 'constraint validation API') }}{{Spec2('HTML5 W3C')}}First snapshot of  {{SpecName('HTML WHATWG')}} containing this interface.
- -

See also

- - diff --git a/files/es/web/api/cssrule/parentstylesheet/index.html b/files/es/web/api/cssrule/parentstylesheet/index.html deleted file mode 100644 index f66c603137..0000000000 --- a/files/es/web/api/cssrule/parentstylesheet/index.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: cssRule.parentStyleSheet -slug: Web/API/CSSRule/parentStyleSheet -translation_of: Web/API/CSSRule/parentStyleSheet ---- -
- {{APIRef}}
-
-  
-

Summary

-

parentStyleSheet returns the object type of style sheet, in which the rule is defined.

-

Syntax

-
stylesheet = cssRule.parentStyleSheet
-
-

Parameters

- -

Instance

-
if (bgRule.parentStyleSheet! = MySheet) {
-   // Style alien rule!
-}
-
-

Letters

-

See Gecko DOM Reference: event # DOM_styleSheet_Object for more information about the interface type objects stylesheet.

-

Specification

-

DOM Level 2 Style - cssRule

diff --git a/files/es/web/api/datatransfer/index.html b/files/es/web/api/datatransfer/index.html deleted file mode 100644 index 01c9ba4fbf..0000000000 --- a/files/es/web/api/datatransfer/index.html +++ /dev/null @@ -1,376 +0,0 @@ ---- -title: DataTransfer -slug: Web/API/DataTransfer -translation_of: Web/API/DataTransfer ---- -
{{APIRef("HTML DOM")}}
- -

{{ gecko_minversion_header("1.9") }} El objeto DataTransfer es usado como contenedor de datos que estan siendo manipulados durante la operación de drag and drop. Este puede contener uno o varios objetos, de uno o varios tipos de datos. Para más información  en cuanto a drag and drop, ver Drag and Drop.

- -

Este objeto esta disponible desde la propiedad dataTransfer de todos los eventos de drag . No pueden ser creados por separado.

- -

Lista de propiedades

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertiesType
dropEffectString
effectAllowedString
files {{ gecko_minversion_inline("1.9.2") }}{{ domxref("FileList") }}
mozCursor {{ non-standard_inline() }} {{ gecko_minversion_inline("1.9.1") }}String
mozItemCount {{ non-standard_inline() }}unsigned long
mozSourceNode {{ non-standard_inline() }} {{ gecko_minversion_inline("2") }}{{ domxref("Node") }}
mozUserCancelledBoolean
typesDOMStringList
- -

Lista de métodos

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void addElement(in Element element)
void clearData([in String type])
String getData(in String type)
void setData(in String type, in String data)
void setDragImage(in nsIDOMElement image, in long x, in long y)
void mozClearDataAt([in String type, in unsigned long index])
nsIVariant mozGetDataAt(in String type, in unsigned long index)
void mozSetDataAt(in String type, in nsIVariant data, in unsigned long index)
StringList mozTypesAt([in unsigned long index])
- -

Propiedades

- -

dropEffect

- -

The actual effect that will be used, and should always be one of the possible values of effectAllowed.

- -

For the dragenter and dragover events, the dropEffect will be initialized based on what action the user is requesting. How this is determined is platform specific, but typically the user can press modifier keys to adjust which action is desired. Within an event handler for the dragenter and dragover events, the dropEffect should be modified if the action the user is requesting is not the one that is desired.

- -

For dragstart, drag, and dragleave events, the dropEffect is initialized to "none". Any value assigned to the dropEffect will be set, but the value isn't used for anything.

- -

For the drop and dragend events, the dropEffect will be initialized to the action that was desired, which will be the value that the dropEffect had after the last dragenter or dragover event.

- -

Possible values:

- - - -

Assigning any other value has no effect and retains the old value.

- -

effectAllowed

- -

Specifies the effects that are allowed for this drag. You may set this in the dragstart event to set the desired effects for the source, and within the dragenter and dragover events to set the desired effects for the target. The value is not used for other events.

- -

Possible values:

- - - -

Assigning any other value has no effect and retains the old value.

- -

files

- -

{{ gecko_minversion_header("1.9.2") }}

- -

Contains a list of all the local files available on the data transfer. If the drag operation doesn't involve dragging files, this property is an empty list. An invalid index access on the {{ domxref("FileList") }} specified by this property will return null.

- -

Example

- -

This example dumps the list of files dragged into the browser window: http://jsfiddle.net/9C2EF/

- -

types

- -

Holds a list of the format types of the data that is stored for the first item, in the same order the data was added. An empty list will be returned if no data was added.

- -

{{ h3_gecko_minversion("mozCursor", "1.9.1", "mozCursor") }}

- -

The drag cursor's state. This is primarily used to control the cursor during tab drags.

- -
Note: This method is currently only implemented on Windows.
- -

Possible values

- -
-
auto
-
Uses the default system behavior.
-
default
-
Uses the default Gecko behavior, which is to set the cursor to an arrow during the drag operation.
-
- -
Note: If you specify any value other than "default", "auto" is assumed.
- -

mozItemCount

- -

The number of items being dragged.

- -
Note: This property is Gecko-specific.
- -

mozSourceNode

- -

{{ gecko_minversion_header("2") }}

- -

The {{ domxref("Node") }} over which the mouse cursor was located when the button was pressed to initiate the drag operation. This value is null for external drags or if the caller can't access the node.

- -
Note: This property is Gecko-specific.
- -

mozUserCancelled

- -

This property applies only to the dragend event, and is true if the user canceled the drag operation by pressing escape. It will be false in all other cases, including if the drag failed for any other reason, for instance due to a drop over an invalid location. This property is not currently implemented on Linux.

- -
Note: This property is Gecko-specific.
- -

Métodos

- -

addElement()

- -

Set the drag source. Usually you would not change this, but it will affect which node the drag and dragend events are fired at. The default target is the node that was dragged.

- -
 void addElement(
-   in Element element
- );
-
- -
Parameters
- -
-
element
-
The element to add.
-
- -

clearData()

- -

Remove the data associated with a given type. The type argument is optional. If the type is empty or not specified, the data associated with all types is removed. If data for the specified type does not exist, or the data transfer contains no data, this method will have no effect.

- -
 void clearData(
-   [optional] in String type
- );
-
- -
Parameters
- -
-
type
-
The type of data to remove.
-
- -

getData()

- -

Retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data.

- -

A security error will occur if you attempt to retrieve data during a drag that was set from a different domain, or the caller would otherwise not have access to. This data will only be available once a drop occurs during the drop event.

- -
 String getData(
-   in String type
- );
-
- -
Parameters
- -
-
type
-
The type of data to retrieve.
-
- -

setData()

- -

Set the data for a given type. If data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format. If data for the type already exists, the existing data is replaced in the same position. That is, the order of the types list is not changed when replacing data of the same type.

- -
 void setData(
-   in String type,
-   in String data
- );
-
- -
Parameters
- -
-
type
-
The type of data to add.
-
data
-
The data to add.
-
- -

setDragImage()

- -

Set the image to be used for dragging if a custom one is desired. Most of the time, this would not be set, as a default image is created from the node that was dragged.

- -

If the node is an HTML img element, an HTML canvas element or a XUL image element, the image data is used. Otherwise, image should be a visible node and the drag image will be created from this. If image is null, any custom drag image is cleared and the default is used instead.

- -

The coordinates specify the offset into the image where the mouse cursor should be. To center the image, for instance, use values that are half the width and height of the image.

- -
 void setDragImage(
-   in Element image,
-   in long x,
-   in long y
- );
-
- -
Parameters
- -
-
image
-
An element to use as the drag feedback image
-
x
-
Horizontal offset within the image.
-
y
-
Vertical offset within the image.
-
- -

mozClearDataAt()

- -

Removes the data associated with the given format for an item at the specified index. The index is in the range from zero to the number of items minus one.

- -

If the last format for the item is removed, the entire item is removed, reducing mozItemCount by one.

- -

If the format list is empty, then the data associated with all formats is removed. If the format is not found, then this method has no effect.

- -
Note: This method is Gecko-specific.
- -
 void mozClearDataAt(
-   [optional] in String type,
-   in unsigned long index
- );
-
- -
Parameters
- -
-
type
-
The type of data to remove.
-
index
-
The index of the data to remove.
-
- -

mozGetDataAt()

- -

Retrieves the data associated with the given format for an item at the specified index, or null if it does not exist. The index should be in the range from zero to the number of items minus one.

- -
Note: This method is Gecko-specific.
- -
 nsIVariant mozGetDataAt(
-   [optional] in String type,
-   in unsigned long index
- );
-
- -
Parameters
- -
-
type
-
The type of data to retrieve.
-
index
-
The index of the data to retrieve.
-
- -

mozSetDataAt()

- -

A data transfer may store multiple items, each at a given zero-based index. mozSetDataAt() may only be called with an index argument less than mozItemCount in which case an existing item is modified, or equal to mozItemCount in which case a new item is added, and the mozItemCount is incremented by one.

- -

Data should be added in order of preference, with the most specific format added first and the least specific format added last. If data of the given format already exists, it is replaced in the same position as the old data.

- -

The data should be either a string, a primitive boolean or number type (which will be converted into a string) or an {{ interface("nsISupports") }}.

- -
Note: This method is Gecko-specific.
- -
 void mozSetDataAt(
-   [optional] in String type,
-   in nsIVariant data,
-   in unsigned long index
- );
-
- -
Parameters
- -
-
type
-
The type of data to add.
-
data
-
The data to add.
-
index
-
The index of the data to add.
-
- -

mozTypesAt()

- -

Holds a list of the format types of the data that is stored for an item at the specified index. If the index is not in the range from 0 to the number of items minus one, an empty string list is returned.

- -
Note: This method is Gecko-specific.
- -
 nsIVariant mozTypesAt(
-   in unsigned long index
- );
-
- -
Parameters
- -
-
index
-
The index of the data for which to retrieve the types.
-
- -

Mira también

- -

Drag and Drop

- -

{{ languages( { "ja": "Ja/DragDrop/DataTransfer" } ) }}

diff --git a/files/es/web/api/document/evaluate/index.html b/files/es/web/api/document/evaluate/index.html deleted file mode 100644 index 67bc5d432e..0000000000 --- a/files/es/web/api/document/evaluate/index.html +++ /dev/null @@ -1,211 +0,0 @@ ---- -title: Document.evaluate() -slug: Web/API/Document/evaluate -translation_of: Web/API/Document/evaluate ---- -
{{ ApiRef("DOM") }}
- -

Retorna XPathResult basado en una expresión XPath y otros parametros dados .

- -

Sintaxis

- -
var xpathResult = document.evaluate(
- xpathExpression,
- contextNode,
- namespaceResolver,
- resultType,
- result
-);
- - - -

Ejemplo

- -
var headings = document.evaluate("/html/body//h2", document, null, XPathResult.ANY_TYPE, null);
-/* Search the document for all h2 elements.
- * The result will likely be an unordered node iterator. */
-var thisHeading = headings.iterateNext();
-var alertText = "Level 2 headings in this document are:\n";
-while (thisHeading) {
-  alertText += thisHeading.textContent + "\n";
-  thisHeading = headings.iterateNext();
-}
-alert(alertText); // Alerts the text of all h2 elements
-
- -

Note, in the above example, a more verbose XPath is preferred over common shortcuts such as //h2. Generally, more specific XPath selectors as in the above example usually gives a significant performance improvement, especially on very large documents. This is because the evaluation of the query spends does not waste time visiting unnecessary nodes. Using // is generally slow as it visits every node from the root and all subnodes looking for possible matches.

- -

Further optimization can be achieved by careful use of the context parameter. For example, if you know the content you are looking for is somewhere inside the body tag, you can use this:

- -
document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);
-
- -

Notice in the above document.body has been used as the context instead of document so the XPath starts from the body element. (In this example, the "." is important to indicate that the querying should start from the context node, document.body. If the "." was left out (leaving //h2) the query would start from the root node (html) which would be more wasteful.)

- -

See Introduction to using XPath in JavaScript for more information.

- -

Nota

- - - -

Tipos de resultados

- -

(Merge with Template:XPathResultConstants?

- -

These are supported values for the resultType parameter of the evaluate method:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Result TypeValueDescription
ANY_TYPE0Whatever type naturally results from the given expression.
NUMBER_TYPE1A result set containing a single number. Useful, for example, in an XPath expression using the count() function.
STRING_TYPE2A result set containing a single string.
BOOLEAN_TYPE3A result set containing a single boolean value. Useful, for example, an an XPath expression using the not() function.
UNORDERED_NODE_ITERATOR_TYPE4A result set containing all the nodes matching the expression. The nodes in the result set are not necessarily in the same order they appear in the document.
ORDERED_NODE_ITERATOR_TYPE5A result set containing all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document.
UNORDERED_NODE_SNAPSHOT_TYPE6A result set containing snapshots of all the nodes matching the expression. The nodes in the result set are not necessarily in the same order they appear in the document.
ORDERED_NODE_SNAPSHOT_TYPE7A result set containing snapshots of all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document.
ANY_UNORDERED_NODE_TYPE8A result set containing any single node that matches the expression. The node is not necessarily the first node in the document that matches the expression.
FIRST_ORDERED_NODE_TYPE9A result set containing the first node in the document that matches the expression.
- -

Results of NODE_ITERATOR types contain references to nodes in the document. Modifying a node will invalidate the iterator. After modifying a node, attempting to iterate through the results will result in an error.

- -

Results of NODE_SNAPSHOT types are snapshots, which are essentially lists of matched nodes. You can make changes to the document by altering snapshot nodes. Modifying the document doesn't invalidate the snapshot; however, if the document is changed, the snapshot may not correspond to the current state of the document, since nodes may have moved, been changed, added, or removed.

- -

Especificaciones

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("DOM3 XPath", "xpath.html#XPathEvaluator-evaluate", "Document.evaluate")}}{{Spec2("DOM3 XPath")}}Initial specification
- -

Compatibilidad del navegador

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
XPath 1.0{{CompatChrome(1.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.8)}}{{CompatNo}}{{CompatOpera(9.0)}}{{CompatVersionUnknown}}[1]
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
XPath 1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Implemented in WebKit 5.0 (531) or earlier.

- -

Ver también

- - diff --git a/files/es/web/api/element/shadowroot/index.html b/files/es/web/api/element/shadowroot/index.html deleted file mode 100644 index 17af57bb3c..0000000000 --- a/files/es/web/api/element/shadowroot/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Element.shadowRoot -slug: Web/API/Element/shadowRoot -translation_of: Web/API/Element/shadowRoot ---- -
{{APIRef("Shadow DOM")}}
- - - -

La propiedad de solo lectura 'Element.shadowRoot' representa el shadow root alojado por el elemento. Use {{DOMxRef("Element.attachShadow()")}} para agregar un shadow root a un elemento existente.

- -

Syntax

- -
var shadowroot = element.shadowRoot;
-
- -

Value

- -

A {{DOMxRef("ShadowRoot")}} object instance, or null if the associated shadow root was attached with its {{DOMxRef("ShadowRoot.mode", "mode")}} set to closed. (See {{DOMxRef("Element.attachShadow()")}} for further details).

- -

Examples

- -

The following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes.

- -

Inside the <custom-square> element's class definition we include some life cycle callbacks that make a call to an external function, updateStyle(), which actually applies the size and color to the element. You'll see that we are passing it this (the custom element itself) as a parameter.

- -
connectedCallback() {
-  console.log('Custom square element added to page.');
-  updateStyle(this);
-}
-
-attributeChangedCallback(name, oldValue, newValue) {
-  console.log('Custom square element attributes changed.');
-  updateStyle(this);
-}
- -

In the updateStyle() function itself, we get a reference to the shadow DOM using {{domxref("Element.shadowRoot")}}. From here we use standard DOM traversal techniques to find the {{htmlelement("style")}} element inside the shadow DOM and then update the CSS found inside it:

- -
function updateStyle(elem) {
-  const shadow = elem.shadowRoot;
-  const childNodes = Array.from(shadow.childNodes);
-
-  childNodes.forEach(childNode => {
-    if (childNode.nodeName === 'STYLE') {
-      childNode.textContent = `
-        div {
-          width: ${elem.getAttribute('l')}px;
-          height: ${elem.getAttribute('l')}px;
-          background-color: ${elem.getAttribute('c')};
-        }
-      `;
-    }
-  });
-}
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-shadowroot', 'shadowRoot')}}{{Spec2('DOM WHATWG')}}
- -

Browser compatibility

- - - -

{{Compat("api.Element.shadowRoot")}}

- -

See also

- - diff --git a/files/es/web/api/file/type/index.html b/files/es/web/api/file/type/index.html deleted file mode 100644 index b433446aa4..0000000000 --- a/files/es/web/api/file/type/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: File.type -slug: Web/API/File/type -tags: - - API - - Archivos - - File API - - Propiedad - - Referencia - - Tipo de archivo -translation_of: Web/API/File/type ---- -
{{APIRef("File API")}}
- -

Retorna el tipo de media (MIME) del archivo representado por un objeto {{domxref("File")}}.

- -

Sintaxis

- -
var tipo = file.type;
- -

Valor

- -

Una cadena (string), conteniendo el tipo de media (MIME) indicando el tipo del archivo, por ejemplo "image/png" para imágenes PNG.

- -

Ejemplo

- -
<input type="file" multiple onchange="mostrarTipo(this)">
-
- -
function mostrarTipo(fileInput) {
-  const archivos = fileInput.files;
-
-  for (let i = 0; i < archivos.length; i++) {
-    const nombre = archivos[i].name;
-    const tipo = archivos[i].type;
-    alert("Nombre del archivo: " + nombre + " , Tipo: " + tipo);
-  }
-}
- -

Note: Based on the current implementation, browsers won't actually read the bytestream of a file to determine its media type. It is assumed based on the file extension; a PNG image file renamed to .txt would give "text/plain" and not "image/png". Moreover, file.type is generally reliable only for common file types like images, HTML documents, audio and video. Uncommon file extensions would return an empty string. Client configuration (for instance, the Windows Registry) may result in unexpected values even for common types. Developers are advised not to rely on this property as a sole validation scheme.

- -

Especificaciones

- - - - - - - - - - - - - - - - -
EspecificaciónEstadoComentario
{{SpecName('File API', '#dfn-type', 'type')}}{{Spec2('File API')}}Definición inicial.
- -

Compatibilidad de los navegadores

- - - -

{{Compat("api.File.type")}}

- -

Ver también

- - diff --git a/files/es/web/api/globaleventhandlers/onloadedmetadata/index.html b/files/es/web/api/globaleventhandlers/onloadedmetadata/index.html deleted file mode 100644 index bbe3e8e7d6..0000000000 --- a/files/es/web/api/globaleventhandlers/onloadedmetadata/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: GlobalEventHandlers.onloadedmetadata -slug: Web/API/GlobalEventHandlers/onloadedmetadata -translation_of: Web/API/GlobalEventHandlers/onloadedmetadata ---- -
{{ ApiRef("HTML DOM") }}
- -

The onloadedmetadata property of the {{domxref("GlobalEventHandlers")}} mixin is the {{event("Event_handlers", "event handler")}} for processing {{event("loadedmetadata")}} events.

- -

The loadedmetadata event is fired when the metadata has been loaded.

- -

Syntax

- -
element.onloadedmetadata = handlerFunction;
-var handlerFunction = element.onloadedmetadata;
-
- -

handlerFunction should be either null or a JavaScript function specifying the handler for the event.

- -

Specification

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG','#handler-onloadedmetadata','onloadedmetadata')}}{{Spec2('HTML WHATWG')}}
- -

Browser compatibility

- - - -

{{Compat("api.GlobalEventHandlers.onloadedmetadata")}}

- -

See also

- - diff --git a/files/es/web/api/history_api/example/index.html b/files/es/web/api/history_api/example/index.html deleted file mode 100644 index aed471d057..0000000000 --- a/files/es/web/api/history_api/example/index.html +++ /dev/null @@ -1,416 +0,0 @@ ---- -title: Ejemplo de Navegación usando Ajax -slug: Web/API/History_API/Example -translation_of: Web/API/History_API/Example -original_slug: DOM/Manipulando_el_historial_del_navegador/Ejemplo ---- -

This is an example of an AJAX web site composed only of three pages (first_page.php, second_page.php and third_page.php). To see how it works, please, create the following files (or git clone https://github.com/giabao/mdn-ajax-nav-example.git ):

- -
Note: For fully integrating the {{HTMLElement("form")}} elements within this mechanism, please take a look at the paragraph Submitting forms and uploading files.
- -

first_page.php:

- -
-
<?php
-    $page_title = "First page";
-
-    $as_json = false;
-    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
-        $as_json = true;
-        ob_start();
-    } else {
-?>
-<!doctype html>
-<html>
-<head>
-<?php
-        include "include/header.php";
-        echo "<title>" . $page_title . "</title>";
-?>
-</head>
-
-<body>
-
-<?php include "include/before_content.php"; ?>
-
-<p>This paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p>
-
-<div id="ajax-content">
-<?php } ?>
-
-    <p>This is the content of <strong>first_page.php</strong>.</p>
-
-<?php
-    if ($as_json) {
-        echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
-    } else {
-?>
-</div>
-
-<p>This paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p>
-
-<?php
-        include "include/after_content.php";
-        echo "</body>\n</html>";
-    }
-?>
-
-
- -

second_page.php:

- -
-
<?php
-    $page_title = "Second page";
-
-    $as_json = false;
-    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
-        $as_json = true;
-        ob_start();
-    } else {
-?>
-<!doctype html>
-<html>
-<head>
-<?php
-        include "include/header.php";
-        echo "<title>" . $page_title . "</title>";
-?>
-</head>
-
-<body>
-
-<?php include "include/before_content.php"; ?>
-
-<p>This paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p>
-
-<div id="ajax-content">
-<?php } ?>
-
-    <p>This is the content of <strong>second_page.php</strong>.</p>
-
-<?php
-    if ($as_json) {
-        echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
-    } else {
-?>
-</div>
-
-<p>This paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p>
-
-<?php
-        include "include/after_content.php";
-        echo "</body>\n</html>";
-    }
-?>
-
-
- -

third_page.php:

- -
-
<?php
-    $page_title = "Third page";
-    $page_content = "<p>This is the content of <strong>third_page.php</strong>. This content is stored into a php variable.</p>";
-
-    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
-        echo json_encode(array("page" => $page_title, "content" => $page_content));
-    } else {
-?>
-<!doctype html>
-<html>
-<head>
-<?php
-        include "include/header.php";
-        echo "<title>" . $page_title . "</title>";
-?>
-</head>
-
-<body>
-
-<?php include "include/before_content.php"; ?>
-
-<p>This paragraph is shown only when the navigation starts from <strong>third_page.php</strong>.</p>
-
-<div id="ajax-content">
-<?php echo $page_content; ?>
-</div>
-
-<p>This paragraph is shown only when the navigation starts from <strong>third_page.php</strong>.</p>
-
-<?php
-        include "include/after_content.php";
-        echo "</body>\n</html>";
-    }
-?>
-
-
- -

css/style.css:

- -
#ajax-loader {
-    position: fixed;
-    display: table;
-    top: 0;
-    left: 0;
-    width: 100%;
-    height: 100%;
-}
-
-#ajax-loader > div {
-    display: table-cell;
-    width: 100%;
-    height: 100%;
-    vertical-align: middle;
-    text-align: center;
-    background-color: #000000;
-    opacity: 0.65;
-}
-
- -

include/after_content.php:

- -
<p>This is the footer. It is shared between all ajax pages.</p>
-
- -

include/before_content.php:

- -
<p>
-[ <a class="ajax-nav" href="first_page.php">First example</a>
-| <a class="ajax-nav" href="second_page.php">Second example</a>
-| <a class="ajax-nav" href="third_page.php">Third example</a>
-| <a class="ajax-nav" href="unexisting.php">Unexisting page</a> ]
-</p>
-
-
- -

include/header.php:

- -
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<script type="text/javascript" src="js/ajax_nav.js"></script>
-<link rel="stylesheet" href="css/style.css" />
-
- -

js/ajax_nav.js:

- -

(before implementing it in a working environment, please read the note about the const statement compatibility)

- -
-
"use strict";
-
-const ajaxRequest = new (function () {
-
-    function closeReq () {
-        oLoadingBox.parentNode && document.body.removeChild(oLoadingBox);
-        bIsLoading = false;
-    }
-
-    function abortReq () {
-        if (!bIsLoading) { return; }
-        oReq.abort();
-        closeReq();
-    }
-
-    function ajaxError () {
-        alert("Unknown error.");
-    }
-
-    function ajaxLoad () {
-        var vMsg, nStatus = this.status;
-        switch (nStatus) {
-            case 200:
-                vMsg = JSON.parse(this.responseText);
-                document.title = oPageInfo.title = vMsg.page;
-                document.getElementById(sTargetId).innerHTML = vMsg.content;
-                if (bUpdateURL) {
-                    history.pushState(oPageInfo, oPageInfo.title, oPageInfo.url);
-                    bUpdateURL = false;
-                }
-                break;
-            default:
-                vMsg = nStatus + ": " + (oHTTPStatus[nStatus] || "Unknown");
-                switch (Math.floor(nStatus / 100)) {
-                    /*
-                    case 1:
-                        // Informational 1xx
-                        console.log("Information code " + vMsg);
-                        break;
-                    case 2:
-                        // Successful 2xx
-                        console.log("Successful code " + vMsg);
-                        break;
-                    case 3:
-                        // Redirection 3xx
-                        console.log("Redirection code " + vMsg);
-                        break;
-                    */
-                    case 4:
-                        /* Client Error 4xx */
-                        alert("Client Error #" + vMsg);
-                        break;
-                    case 5:
-                        /* Server Error 5xx */
-                        alert("Server Error #" + vMsg);
-                        break;
-                    default:
-                        /* Unknown status */
-                        ajaxError();
-                }
-        }
-        closeReq();
-    }
-
-    function filterURL (sURL, sViewMode) {
-        return sURL.replace(rSearch, "") + ("?" + sURL.replace(rHost, "&").replace(rView, sViewMode ? "&" + sViewKey + "=" + sViewMode : "").slice(1)).replace(rEndQstMark, "");
-    }
-
-    function getPage (sPage) {
-        if (bIsLoading) { return; }
-        oReq = new XMLHttpRequest();
-        bIsLoading = true;
-        oReq.onload = ajaxLoad;
-        oReq.onerror = ajaxError;
-        if (sPage) { oPageInfo.url = filterURL(sPage, null); }
-        oReq.open("get", filterURL(oPageInfo.url, "json"), true);
-        oReq.send();
-        oLoadingBox.parentNode || document.body.appendChild(oLoadingBox);
-    }
-
-    function requestPage (sURL) {
-        if (history.pushState) {
-            bUpdateURL = true;
-            getPage(sURL);
-        } else {
-            /* Ajax navigation is not supported */
-            location.assign(sURL);
-        }
-    }
-
-    function processLink () {
-        if (this.className === sAjaxClass) {
-            requestPage(this.href);
-            return false;
-        }
-        return true;
-    }
-
-    function init () {
-        oPageInfo.title = document.title;
-        for (var oLink, nIdx = 0, nLen = document.links.length; nIdx < nLen; document.links[nIdx++].onclick = processLink);
-    }
-
-    const
-
-        /* customizable constants */
-        sTargetId = "ajax-content", sViewKey = "view_as", sAjaxClass = "ajax-nav",
-
-        /* not customizable constants */
-        rSearch = /\?.*$/, rHost = /^[^\?]*\?*&*/, rView = new RegExp("&" + sViewKey + "\\=[^&]*|&*$", "i"), rEndQstMark = /\?$/,
-        oLoadingBox = document.createElement("div"), oCover = document.createElement("div"), oLoadingImg = new Image(),
-        oPageInfo = {
-            title: null,
-            url: location.href
-        }, oHTTPStatus = /* http://www.iana.org/assignments/http-status-codes/http-status-codes.xml */ {
-            100: "Continue",
-            101: "Switching Protocols",
-            102: "Processing",
-            200: "OK",
-            201: "Created",
-            202: "Accepted",
-            203: "Non-Authoritative Information",
-            204: "No Content",
-            205: "Reset Content",
-            206: "Partial Content",
-            207: "Multi-Status",
-            208: "Already Reported",
-            226: "IM Used",
-            300: "Multiple Choices",
-            301: "Moved Permanently",
-            302: "Found",
-            303: "See Other",
-            304: "Not Modified",
-            305: "Use Proxy",
-            306: "Reserved",
-            307: "Temporary Redirect",
-            308: "Permanent Redirect",
-            400: "Bad Request",
-            401: "Unauthorized",
-            402: "Payment Required",
-            403: "Forbidden",
-            404: "Not Found",
-            405: "Method Not Allowed",
-            406: "Not Acceptable",
-            407: "Proxy Authentication Required",
-            408: "Request Timeout",
-            409: "Conflict",
-            410: "Gone",
-            411: "Length Required",
-            412: "Precondition Failed",
-            413: "Request Entity Too Large",
-            414: "Request-URI Too Long",
-            415: "Unsupported Media Type",
-            416: "Requested Range Not Satisfiable",
-            417: "Expectation Failed",
-            422: "Unprocessable Entity",
-            423: "Locked",
-            424: "Failed Dependency",
-            425: "Unassigned",
-            426: "Upgrade Required",
-            427: "Unassigned",
-            428: "Precondition Required",
-            429: "Too Many Requests",
-            430: "Unassigned",
-            431: "Request Header Fields Too Large",
-            500: "Internal Server Error",
-            501: "Not Implemented",
-            502: "Bad Gateway",
-            503: "Service Unavailable",
-            504: "Gateway Timeout",
-            505: "HTTP Version Not Supported",
-            506: "Variant Also Negotiates (Experimental)",
-            507: "Insufficient Storage",
-            508: "Loop Detected",
-            509: "Unassigned",
-            510: "Not Extended",
-            511: "Network Authentication Required"
-        };
-
-    var
-
-        oReq, bIsLoading = false, bUpdateURL = false;
-
-    oLoadingBox.id = "ajax-loader";
-    oCover.onclick = abortReq;
-    oLoadingImg.src = "data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==";
-    oCover.appendChild(oLoadingImg);
-    oLoadingBox.appendChild(oCover);
-
-    onpopstate = function (oEvent) {
-        bUpdateURL = false;
-        oPageInfo.title = oEvent.state.title;
-        oPageInfo.url = oEvent.state.url;
-        getPage();
-    };
-
-    window.addEventListener ? addEventListener("load", init, false) : window.attachEvent ? attachEvent("onload", init) : (onload = init);
-
-    // Public methods
-
-    this.open = requestPage;
-    this.stop = abortReq;
-    this.rebuildLinks = init;
-
-})();
-
-
- -
Note: The current implementation of const (constant statement) is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8) and partially supported in Opera 9+ and Safari. It is not supported in Internet Explorer 6-9, or in the preview of Internet Explorer 10. const is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the let statement, constants declared with const will be block-scoped. We used it only for didactic purpose. If you want a full browser compatibility of this library, please replace all the const statements with the var statements.
- -

For more information, please see: Manipulating the browser history.

- -

See also

- - diff --git a/files/es/web/api/htmlcontentelement/getdistributednodes/index.html b/files/es/web/api/htmlcontentelement/getdistributednodes/index.html deleted file mode 100644 index c4aad9ddb8..0000000000 --- a/files/es/web/api/htmlcontentelement/getdistributednodes/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: HTMLContentElement.getDistributedNodes() -slug: Web/API/HTMLContentElement/getDistributedNodes -tags: - - Necesita traducción -translation_of: Web/API/HTMLContentElement/getDistributedNodes ---- -

{{ APIRef("Web Components") }}

- -

The HTMLContentElement.getDistributedNodes() method returns a static {{domxref("NodeList")}} of the {{glossary("distributed nodes")}} associated with this <content> element.

- -

Syntax

- -
var nodeList = object.getDistributedNodes()
-
- -

Example

- -
// Get the distributed nodes
-var nodes = myContentObject.getDistributedNodes();
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Shadow DOM', '#the-content-element', 'content')}}{{Spec2('Shadow DOM')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support35{{CompatGeckoDesktop("28")}} [1]{{CompatNo}}26{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support37{{CompatGeckoMobile("28")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] If Shadow DOM is not enabled in Firefox, <content> elements will behave like {{domxref("HTMLUnknownElement")}}. Shadow DOM was first implemented in Firefox 28 and is behind a preference, dom.webcomponents.enabled, which is disabled by default.

- -

See also

- - diff --git a/files/es/web/api/htmlcontentelement/index.html b/files/es/web/api/htmlcontentelement/index.html deleted file mode 100644 index 637210416d..0000000000 --- a/files/es/web/api/htmlcontentelement/index.html +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: HTMLContentElement -slug: Web/API/HTMLContentElement -tags: - - Necesita traducción -translation_of: Web/API/HTMLContentElement ---- -

{{ APIRef("Web Components") }}

- -

{{Deprecated_header}}

- -

The HTMLContentElement interface represents a {{HTMLElement("content")}} HTML Element, which is used in Shadow DOM

- -

Properties

- -

This interface inherits the properties of {{domxref("HTMLElement")}}.

- -
-
{{domxref("HTMLContentElement.select")}}
-
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("select", "content") }} HTML attribute. The value is a comma-separated list of CSS selectors that select the content to insert in place of the <content> element.
-
- -

Methods

- -

This interface inherits the methods of {{domxref("HTMLElement")}}.

- -
-
{{domxref("HTMLContentElement.getDistributedNodes()")}}
-
Returns a static {{domxref("NodeList")}} of the {{glossary("distributed nodes")}} associated with this <content> element. 
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Shadow DOM', '#the-content-element', 'content')}}{{Spec2('Shadow DOM')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support35{{CompatGeckoDesktop("28")}} [1]{{CompatNo}}26{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support37{{CompatGeckoMobile("28")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] If Shadow DOM is not enabled in Firefox, <content> elements will behave like {{domxref("HTMLUnknownElement")}}. Shadow DOM was first implemented in Firefox 28 and is behind a preference, dom.webcomponents.enabled, which is disabled by default.

- -

See also

- - - -
-
 
-
diff --git a/files/es/web/api/htmlcontentelement/select/index.html b/files/es/web/api/htmlcontentelement/select/index.html deleted file mode 100644 index 916be57621..0000000000 --- a/files/es/web/api/htmlcontentelement/select/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: HTMLContentElement.select -slug: Web/API/HTMLContentElement/select -tags: - - Necesita traducción -translation_of: Web/API/HTMLContentElement/select ---- -

{{ APIRef("Web Components") }}

- -

The HTMLContentElement.select property reflects the select attribute. It is a {{domxref("DOMString")}} containing a space-separated list of CSS selectors that select the content to insert in place of the <content> element.

- -

Syntax

- -
object.select = "CSSselector CSSselector ...";
-
- -

Example

- -
// Select <h1> elements and elements with class="error"
-myContentObject.select = "h1 .error";
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Shadow DOM', '#the-content-element', 'content')}}{{Spec2('Shadow DOM')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support35{{CompatGeckoDesktop("28")}} [1]{{CompatNo}}26{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support37{{CompatGeckoMobile("28")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] If Shadow DOM is not enabled in Firefox, <content> elements will behave like {{domxref("HTMLUnknownElement")}}. Shadow DOM was first implemented in Firefox 28 and is behind a preference, dom.webcomponents.enabled, which is disabled by default.

- -

See also

- - diff --git a/files/es/web/api/htmlelement/innertext/index.html b/files/es/web/api/htmlelement/innertext/index.html deleted file mode 100644 index 403f3c0bc1..0000000000 --- a/files/es/web/api/htmlelement/innertext/index.html +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: HTMLElement.innerText -slug: Web/API/HTMLElement/innerText -translation_of: Web/API/HTMLElement/innerText ---- -
{{APIRef("HTML DOM")}}
- -

The innerText property of the {{domxref("HTMLElement")}} interface represents the "rendered" text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.

- -
-

Note: innerText is easily confused with {{domxref("Node.textContent")}}, but there are important differences between the two. Basically, innerText is aware of the rendered appearance of text, while textContent is not.

-
- -

Syntax

- -
const renderedText = htmlElement.innerText
-htmlElement.innerText = string
- -

Value

- -

A {{domxref("DOMString")}} representing the rendered text content of an element. If the element itself is not being rendered (e.g detached from the document or is hidden from view), the returned value is the same as the {{domxref("Node.textContent")}} property.

- -

Example

- -

This example compares innerText with {{domxref("Node.textContent")}}. Note how innerText is aware of things like {{htmlElement("br")}} elements, and ignores hidden elements.

- -

HTML

- -
<h3>Source element:</h3>
-<p id="source">
-  <style>#source { color: red; }</style>
-Take a look at<br>how this text<br>is interpreted
-       below.
-  <span style="display:none">HIDDEN TEXT</span>
-</p>
-<h3>Result of textContent:</h3>
-<textarea id="textContentOutput" rows="6" cols="30" readonly>...</textarea>
-<h3>Result of innerText:</h3>
-<textarea id="innerTextOutput" rows="6" cols="30" readonly>...</textarea>
- -

JavaScript

- -
const source = document.getElementById('source');
-const textContentOutput = document.getElementById('textContentOutput');
-const innerTextOutput = document.getElementById('innerTextOutput');
-
-textContentOutput.innerHTML = source.textContent;
-innerTextOutput.innerHTML = source.innerText;
- -

Result

- -

{{EmbedLiveSample("Example", 700, 450)}}

- -

Specification

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'dom.html#the-innertext-idl-attribute', 'innerText')}}{{Spec2('HTML WHATWG')}}Introduced, based on the draft of the innerText specification. See whatwg/html#465 and whatwg/compat#5 for history.
- -

Browser compatibility

- - - -

{{Compat("api.HTMLElement.innerText")}}

- -

See also

- - diff --git a/files/es/web/api/htmlhtmlelement/index.html b/files/es/web/api/htmlhtmlelement/index.html deleted file mode 100644 index f079c9a07a..0000000000 --- a/files/es/web/api/htmlhtmlelement/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: HTMLHtmlElement -slug: Web/API/HTMLHtmlElement -tags: - - API - - HTML DOM - - Interface - - Referencia -translation_of: Web/API/HTMLHtmlElement ---- -
{{ APIRef("HTML DOM") }}
- -

The HTMLHtmlElement interface serves as the root node for a given HTML document.  This object inherits the properties and methods described in the {{domxref("HTMLElement")}} interface.

- -

You can retrieve the HTMLHtmlElement object for a given document by reading the value of the {{domxref("document.documentElement")}} property.

- -

Properties

- -

Inherits properties from its parent, {{domxref("HTMLElement")}}.

- -
-
{{domxref("HTMLHtmlElement.version")}}  {{ obsolete_inline() }}
-
Is a {{domxref("DOMString")}} representing the version of the HTML Document Type Definition (DTD) that governs this document. This property should not be used any more as it is non-conforming. Simply omit it.
-
- -

Methods

- -

No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', "semantics.html#the-html-element", "HTMLHtmlElement")}}{{Spec2('HTML WHATWG')}}Live specification, no change since last snapshot
{{SpecName('HTML5.1', "semantics.html#the-html-element", "HTMLHtmlElement")}}{{Spec2('HTML5.1')}}No change since the last snapshot
{{SpecName('HTML5 W3C', "semantics.html#the-html-element", "HTMLHtmlElement")}}{{Spec2('HTML5 W3C')}}The version element has been removed, as it is non-conforming.
{{SpecName('DOM2 HTML', 'html.html#ID-33759296', 'HTMLHtmlElement')}}{{Spec2('DOM2 HTML')}}Reflecting the element change in {{SpecName("HTML4.01")}}, the version property is now deprecated.
{{SpecName('DOM1', 'level-one-html.html#ID-33759296', 'HTMLHtmlElement')}}{{Spec2('DOM1')}}Initial definition
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/es/web/api/htmlmediaelement/abort_event/index.html b/files/es/web/api/htmlmediaelement/abort_event/index.html deleted file mode 100644 index 597993df26..0000000000 --- a/files/es/web/api/htmlmediaelement/abort_event/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: abort -slug: Web/API/HTMLMediaElement/abort_event -translation_of: Web/API/HTMLMediaElement/abort_event -translation_of_original: Web/Events/abort -original_slug: Web/Events/abort ---- -

The abort event is fired when the loading of a resource has been aborted.

- -

Información general

- -
-
Specification
-
DOM L3
-
Interface
-
UIEvent if generated from a user interface, Event otherwise.
-
Bubbles
-
No
-
Cancelable
-
No
-
Target
-
Element
-
Default Action
-
None
-
- -

Propiedades

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not.
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not.
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
diff --git a/files/es/web/api/keyboardevent/getmodifierstate/index.html b/files/es/web/api/keyboardevent/getmodifierstate/index.html deleted file mode 100644 index b44ecc6da3..0000000000 --- a/files/es/web/api/keyboardevent/getmodifierstate/index.html +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: KeyboardEvent.getModifierState() -slug: Web/API/KeyboardEvent/getModifierState -tags: - - API - - DOM - - KeyboardEvent - - Referencia - - getModifierState - - metodo -translation_of: Web/API/KeyboardEvent/getModifierState ---- -

{{APIRef("DOM Events")}}

- -

El método KeyboardEvent.getModifierState() retorna true respecto al estado actual de la tecla modificadora especificada si la misma está presionada o bloqueada, en caso contrario devuelve false.

- -

Sintaxis

- -
var active = event.getModifierState(keyArg);
- -

Retorna

- -

A {{jsxref("Boolean")}}

- -

Parámetros

- -
-
keyArg
-
El valor de la tecla modificadora. El valor debe ser uno de los valores {{domxref("KeyboardEvent.key")}} que representan las teclas modificadoras, o el string "Accel" {{deprecated_inline}}, el cual es case-sensitive.
-
- -

Teclas modificadoras en Internet Explorer

- -

IE9 usa "Scroll" para "ScrollLock" y "Win" para "OS".

- -

Teclas modificadoras en Gecko

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
When getModifierState() returns true on Gecko?
 WindowsLinux (GTK)MacAndroid 2.3Android 3.0 or latter
"Alt"Either Alt key or AltGr key pressedAlt key pressed⌥ Option key pressedAlt key or option key pressed
"AltGraph" -

Both Alt and Ctrl keys are pressed, or AltGr key is pressed

-
Level 3 Shift key (or Level 5 Shift key {{gecko_minversion_inline("20.0")}}) pressed⌥ Option key pressedNot supported
"CapsLock"During LED for ⇪ Caps Lock turned onNot supportedWhile CapsLock is locked {{gecko_minversion_inline("29.0")}}
"Control"Either Ctrl key or AltGr key pressedCtrl key pressedcontrol key pressedmenu key pressed.Ctrl key, control key or menu key pressed.
"Fn"Not supportedFunction key is pressed, but we're not sure what key makes the modifier state active. Fn key on Mac keyboard doesn't cause this active. {{gecko_minversion_inline("29.0")}}
"FnLock"Not supported
"Hyper"Not supported
"Meta"Not supportedMeta key pressed {{gecko_minversion_inline("17.0")}}⌘ Command key pressedNot supported⊞ Windows Logo key or command key pressed
"NumLock"During LED for Num Lock turned onA key on numpad pressedNot supportedWhile NumLock is locked {{gecko_minversion_inline("29.0")}}
"OS"⊞ Windows Logo key pressedSuper key or Hyper key pressed (typically, mapped to ⊞ Windows Logo key)Not supported
"ScrollLock"During LED for Scroll Lock turned onDuring LED for Scroll Lock turned on, but typically this isn't supported by platformNot supportedWhile ScrollLock is locked {{gecko_minversion_inline("29.0")}}
"Shift"⇧ Shift key pressed
"Super"Not supported
"Symbol"Not supported
"SymbolLock"Not supported
- - - -

 El modificador virtual "Accel"

- -
Note: The "Accel" virtual modifier has been effectively deprecated in current drafts of the DOM3 Events specification.
- -

getModifierState() also accepts a deprecated virtual modifier named "Accel". event.getModifierState("Accel") returns true when at least one of {{domxref("KeyboardEvent.ctrlKey")}} or {{domxref("KeyboardEvent.metaKey")}} is true.

- -

In old implementations and outdated specifications, it returned true when a modifier which is the typical modifier key for the shortcut key is pressed. For example, on Windows, pressing Ctrl key may make it return true. However, on Mac, pressing ⌘ Command key may make it return true. Note that which modifier key makes it return true depends on platforms, browsers, and user settings. For example, Firefox users can customize this with a pref, "ui.key.accelKey".

- -

Ejemplo

- -
// Ignore if following modifier is active.
-if (event.getModifierState("Fn") ||
-    event.getModifierState("Hyper") ||
-    event.getModifierState("OS") ||
-    event.getModifierState("Super") ||
-    event.getModifierState("Win") /* hack for IE */) {
-  return;
-}
-
-// Also ignore if two or more modifiers except Shift are active.
-if (event.getModifierState("Control") +
-    event.getModifierState("Alt") +
-    event.getModifierState("Meta") > 1) {
-  return;
-}
-
-// Handle shortcut key with standard modifier
-if (event.getModifierState("Accel")) {
-  switch (event.key.toLowerCase()) {
-    case "c":
-      if (event.getModifierState("Shift")) {
-        // Handle Accel + Shift + C
-        event.preventDefault(); // consume the key event
-      }
-      break;
-    case "k":
-      if (!event.getModifierState("Shift")) {
-        // Handle Accel + K
-        event.preventDefault(); // consume the key event
-      }
-      break;
-  }
-  return;
-}
-
-// Do somethig different for arrow keys if ScrollLock is locked.
-if ((event.getModifierState("ScrollLock") ||
-       event.getModifierState("Scroll") /* hack for IE */) &&
-    !event.getModifierState("Control") &&
-    !event.getModifierState("Alt") &&
-    !event.getModifierState("Meta")) {
-  switch (event.key) {
-    case "ArrowDown":
-    case "Down": // hack for IE and old Gecko
-      event.preventDefault(); // consume the key event
-      break;
-    case "ArrowLeft":
-    case "Left": // hack for IE and old Gecko
-      // Do something different if ScrollLock is locked.
-      event.preventDefault(); // consume the key event
-      break;
-    case "ArrowRight":
-    case "Right": // hack for IE and old Gecko
-      // Do something different if ScrollLock is locked.
-      event.preventDefault(); // consume the key event
-      break;
-    case "ArrowUp":
-    case "Up": // hack for IE and old Gecko
-      // Do something different if ScrollLock is locked.
-      event.preventDefault(); // consume the key event
-      break;
-  }
-}
-
- -
-

Although, this example uses .getModifierState() with "Alt", "Control", "Meta" and "Shift", perhaps it's better for you to use altKey, ctrlKey, metaKey and shiftKey because they are shorter and may be faster.

-
- -

Especificaciones

- - - - - - - - - - - - - - -
EspecificacionesEstadoComentario
{{SpecName('DOM3 Events', '#widl-KeyboardEvent-getModifierState', 'getModifierState()')}}{{Spec2('DOM3 Events')}}Initial definition (Modifier Keys spec)
- -

Compatibilidad con Browsers

- - - -

{{Compat("api.KeyboardEvent.getModifierState")}}

- -

Ver también

- - diff --git a/files/es/web/api/keyboardevent/key/index.html b/files/es/web/api/keyboardevent/key/index.html deleted file mode 100644 index ed765b38b3..0000000000 --- a/files/es/web/api/keyboardevent/key/index.html +++ /dev/null @@ -1,212 +0,0 @@ ---- -title: KeyboardEvent.key -slug: Web/API/KeyboardEvent/key -translation_of: Web/API/KeyboardEvent/key ---- -

{{APIRef("DOM Events")}}

- -

La propiedad de solo lectura KeyboardEvent.key retorna el valor de la tecla presionada por el usuario while taking into considerations the state of modifier keys such as the shiftKey as well as the keyboard locale/layout. Its value is determined as follows:

- -
-

See a full list of key values.

-
- - - -

KeyboardEvent Sequence

- -

KeyboardEvents are fired in a pre-determined sequence and understanding this will go a long way into understanding the key property value for a particular KeyboardEvent. For a given key press, the sequence of KeyboardEvents fired is as follows assuming that {{domxref("Event.preventDefault")}} is not called:

- -
    -
  1. A {{event("keydown")}} event is first fired. If the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the {{domxref("KeyboardEvent.repeat")}} read only property  is set to true.
  2. -
  3. If the key produces a character key that would result in a character being inserted into possibly an {{HTMLElement("input")}}, {{HTMLElement("textarea")}} or an element with {{domxref("HTMLElement.contentEditable")}} set to true, the {{event("beforeinput")}} and {{event("input")}} event types are fired in that order. Note that some other implementations may fire {{event("keypress")}} event if supported. The events will be fired repeatedly while the key is held down.
  4. -
  5. A {{event("keyup")}} event is fired once the key is released. This completes the process.
  6. -
- -

In sequence 1 & 3, the KeyboardEvent.key attribute is defined and is set appropriately to a value according to the rules defined ealier.

- -

KeyboardEvent Sequence Sample

- -

Consider the event sequence generated when we interact with the ShiftKey and the legend key 2 using a U.S keyboard layout and a UK keyboard layout.

- -

Try experimenting using the following two test cases:

- -
    -
  1. Press and hold the shift key, then press key 2 and release it. Next, release the shift key.
  2. -
  3. Press and hold the shift key, then press and hold key 2. Release the shift key. Finally, release key 2.
  4. -
- -

HTML

- -
<div class="fx">
-  <div>
-    <textarea rows="5" name="test-target" id="test-target"></textarea>
-    <button type="button" name="btn-clear-console" id="btn-clear-console">clear console</button>
-  </div>
-  <div class="flex">
-    <div id="console-log"></div>
-  </div>
-</div>
-
- -

CSS

- -
.fx {
-  -webkit-display: flex;
-  display: flex;
-  margin-left: -20px;
-  margin-right: -20px;
-}
-
-.fx > div {
-  padding-left: 20px;
-  padding-right: 20px;
-}
-
-.fx > div:first-child {
-   width: 30%;
-}
-
-.flex {
-  -webkit-flex: 1;
-  flex: 1;
-}
-
-#test-target {
-  display: block;
-  width: 100%;
-  margin-bottom: 10px;
-}
- -

JavaScript

- -
let textarea = document.getElementById('test-target'),
-consoleLog = document.getElementById('console-log'),
-btnClearConsole = document.getElementById('btn-clear-console');
-
-function logMessage(message) {
-  let p = document.createElement('p');
-  p.appendChild(document.createTextNode(message));
-  consoleLog.appendChild(p);
-}
-
-textarea.addEventListener('keydown', (e) => {
-  if (!e.repeat)
-    logMessage(`first keydown event. key property value is "${e.key}"`);
-  else
-    logMessage(`keydown event repeats. key property value is "${e.key}"`);
-});
-
-textarea.addEventListener('beforeinput', (e) => {
-  logMessage(`beforeinput event. you are about inputing "${e.data}"`);
-});
-
-textarea.addEventListener('input', (e) => {
-  logMessage(`input event. you have just inputed "${e.data}"`);
-});
-
-textarea.addEventListener('keyup', (e) => {
-  logMessage(`keyup event. key property value is "${e.key}"`);
-});
-
-btnClearConsole.addEventListener('click', (e) => {
-  let child = consoleLog.firstChild;
-  while (child) {
-   consoleLog.removeChild(child);
-   child = consoleLog.firstChild;
-  }
-});
- -

Result

- -

{{EmbedLiveSample('KeyboardEvent_Sequence_Sample')}}

- -

Case 1

- -

When the shift key is pressed, a {{event("keydown")}} event is first fired, and the key property value is set to the string "Shift". As we keep holding this key, the {{event("keydown")}} event does not continue to fire repeatedly because it does not produce a character key.

- -

When key 2 is pressed, another {{event("keydown")}} event is fired for this new key press, and the key property value for the event is set to the string "@" for the U.S keyboard type and """ for the UK keyboard type, because of the active modifier shift key. The {{event("beforeinput")}} and {{event("input")}} events are fired next because a character key has been produced.

- -

As we release the key 2, a {{event("keyup")}} event is fired and the key property will maintain the string values "@" and """ for the different keyboard layouts respectively.

- -

As we finally release the shift key, another {{event("keyup")}} event is fired for it, and the key attribute value remains "Shift".

- -

Case 2

- -

When the shift key is pressed, a {{event("keydown")}} event is first fired, and the key property value is set to be the string "Shift". As we keep holding this key, the keydown event does not continue to fire repeatedly because it produced no character key.

- -

When key 2 is pressed, another {{event("keydown")}} event is fired for this new key press, and the key property value for the event is set to be the string "@" for the U.S keyboard type and """ for the UK keyboard type, because of the active modifier shift key. The {{event("beforeinput")}} and {{event("input")}} events are fired next because a character key has been produced. As we keep holding the key, the {{event("keydown")}} event continues to fire repeatedly and the {{domxref("KeyboardEvent.repeat")}}  property is set to true. The {{event("beforeinput")}} and {{event("input")}} events are fired repeatedly as well.

- -

As we release the shift key, a {{event("keyup")}} event is fired for it, and the key attribute value remains "Shift". At this point, notice that the key property value for the repeating keydown event of the key 2 key press is now "2" because the modifier shift key is no longer active. The same goes for the {{domxref("InputEvent.data")}} property of the {{event("beforeinput")}} and {{event("input")}} events.

- -

As we finally release the key 2, a {{event("keyup")}} event is fired but the key property will be set to the string value "2" for both keyboard layouts because the modifier shift key is no longer active.

- -

Example

- -

This example uses {{domxref("EventTarget.addEventListener()")}} to listen for {{event("keydown")}} events. When they occur,  the key's value is checked to see if it's one of the keys the code is interested in, and if it is, it gets processed in some way (possibly by steering a spacecraft, perhaps by changing the selected cell in a spreadsheet).

- -
window.addEventListener("keydown", function (event) {
-  if (event.defaultPrevented) {
-    return; // Do nothing if the event was already processed
-  }
-
-  switch (event.key) {
-    case "Down": // IE specific value
-    case "ArrowDown":
-      // Do something for "down arrow" key press.
-      break;
-    case "Up": // IE specific value
-    case "ArrowUp":
-      // Do something for "up arrow" key press.
-      break;
-    case "Left": // IE specific value
-    case "ArrowLeft":
-      // Do something for "left arrow" key press.
-      break;
-    case "Right": // IE specific value
-    case "ArrowRight":
-      // Do something for "right arrow" key press.
-      break;
-    case "Enter":
-      // Do something for "enter" or "return" key press.
-      break;
-    case "Escape":
-      // Do something for "esc" key press.
-      break;
-    default:
-      return; // Quit when this doesn't handle the key event.
-  }
-
-  // Cancel the default action to avoid it being handled twice
-  event.preventDefault();
-}, true);
-
- -

Specification

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('DOM3 Events', '#widl-KeyboardEvent-key', 'KeyboardEvent.key')}}{{Spec2('DOM3 Events')}}Initial definition, included key values.
- -

Browser compatibility

- - - -

{{Compat("api.KeyboardEvent.key")}}

diff --git a/files/es/web/api/navigator/mediadevices/index.html b/files/es/web/api/navigator/mediadevices/index.html deleted file mode 100644 index 0a7e70e7e4..0000000000 --- a/files/es/web/api/navigator/mediadevices/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Navigator.mediaDevices -slug: Web/API/Navigator/mediaDevices -translation_of: Web/API/Navigator/mediaDevices ---- -
{{APIRef("Media Capture and Streams")}}
- -

The Navigator.mediaDevices read-only property returns a {{domxref("MediaDevices")}} object, which provides access to connected media input devices like cameras and microphones, as well as screen sharing.

- -

Syntax

- -
var mediaDevices = navigator.mediaDevices;
-
- -

Return value

- -

The {{domxref("MediaDevices")}} singleton object. Usually, you just use this object's members directly, such as by calling {{domxref("navigator.mediaDevices.getUserMedia()")}}.

- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Media Capture', '#mediadevices', 'NavigatorUserMedia.mediaDevices')}}{{Spec2('Media Capture')}}Initial definition.
- -

Browser compatibility

- - - -

{{Compat("api.Navigator.mediaDevices")}}

- -

See also

- - diff --git a/files/es/web/api/pushmanager/permissionstate/index.html b/files/es/web/api/pushmanager/permissionstate/index.html deleted file mode 100644 index f017b2da93..0000000000 --- a/files/es/web/api/pushmanager/permissionstate/index.html +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: PushManager.permissionState() -slug: Web/API/PushManager/permissionState -translation_of: Web/API/PushManager/permissionState ---- -

{{SeeCompatTable}}{{ApiRef("Push API")}}

- -

El metodo permissionState()  de la interface   {{domxref("PushManager")}} retorna un {{jsxref("Promise")}} that resolves to a {{domxref("DOMString")}} indicating the permission state of the push manager. Possible values are  'prompt', 'denied', or 'granted'.

- -
-

Note: As of Firefox 44, the permissions for Notifications and Push have been merged. If permission is granted for notifications, push will also be enabled.

-
- -

Sintaxis

- -
PushManager.permissionState(options).then(function(PushMessagingState) { ... });
-
- -

Parámetros

- -
-
opciones {{optional_inline}}
-
An object containing optional configuration parameters. It can have the following properties: -
    -
  • userVisibleOnly: A boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user.
  • -
-
-
- -

Retorna

- -

Un {{jsxref("Promise")}} que resuelve a un {{domxref("DOMString")}} con un valor de  'prompt', 'denied', o 'granted'.

- -

Especificaciones

- - - - - - - - - - - - - - -
EspecificaciónEstadoComentario
{{SpecName('Push API','#widl-PushManager-permissionState-Promise-PushPermissionState--PushSubscriptionOptions-options','permissionState()')}}{{Spec2('Push API')}}Initial definition.
- -

Compactibilidad del Navegador

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
-
- -

Ver también

- - diff --git a/files/es/web/api/range/intersectsnode/index.html b/files/es/web/api/range/intersectsnode/index.html deleted file mode 100644 index 5ffd11b79e..0000000000 --- a/files/es/web/api/range/intersectsnode/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: range.intersectsNode -slug: Web/API/Range/intersectsNode -tags: - - Referencia_DOM_de_Gecko -translation_of: Web/API/Range/intersectsNode ---- -

{{ ApiRef() }}

-

Summary

-

{{ Obsolete_header() }} Returns a boolean indicating whether the given node intersects the range.

-

Syntax

-
bool = range.intersectsNode( referenceNode )
-
-

Parameters

-
-
- referenceNode 
-
- The Node to compare with the Range.
-
-

Example

-
range = document.createRange();
-range.selectNode(document.getElementsByTagName("div").item(0));
-bool = range.intersectsNode(document.getElementsByTagName("p").item(0));
-
-

Notes

-

This method is obsolete; you should instead use the W3C DOM Range methods (see compareBoundaryPoints()).

-
- Warning: This method has been removed from Gecko 1.9 and will not exist in future versions of Firefox; you should switch to compareBoundaryPoints() as soon as possible.
-

The following function can be used as replacement:

-
function rangeIntersectsNode(range, node) {
-  var nodeRange = node.ownerDocument.createRange();
-  try {
-    nodeRange.selectNode(node);
-  }
-  catch (e) {
-    nodeRange.selectNodeContents(node);
-  }
-
-  return range.compareBoundaryPoints(Range.END_TO_START, nodeRange) == -1 &&
-         range.compareBoundaryPoints(Range.START_TO_END, nodeRange) == 1;
-}
-
-

Specification

-

This method is not part of a specification.

-
-  
-

{{ languages( { "en": "en/DOM/range.intersectsNode", "pl": "pl/DOM/range.intersectsNode" } ) }}

diff --git a/files/es/web/api/service_worker_api/using_service_workers/index.html b/files/es/web/api/service_worker_api/using_service_workers/index.html deleted file mode 100644 index d687cddd19..0000000000 --- a/files/es/web/api/service_worker_api/using_service_workers/index.html +++ /dev/null @@ -1,526 +0,0 @@ ---- -title: Usando Service Workers -slug: Web/API/Service_Worker_API/Using_Service_Workers -tags: - - Guía - - básico -translation_of: Web/API/Service_Worker_API/Using_Service_Workers ---- -

{{ServiceWorkerSidebar}}

- -

{{ SeeCompatTable() }}

- -
-

Este articulo provee información sobre cómo empezar con los service workers, incluyendo su arquitectura básica, el registro de un service worker, el proceso de instalación y activación de un nuevo service worker, cómo actualizar un service worker, controlar su cache y respuestas personalizadas, todo esto en el contexto de una simple aplicación con la capacidad de trabajar offline (sin internet).

-
- -

La premisa de los service workers

- -

Un problema primordial que los usuarios de la web han sufrido durante años es la pérdida de conectividad. La mejor aplicación web en el mundo ofrecerá una experiencia de usuario terrible si simplemente no se puede utilizar. Han habido varios intentos de crear tecnologías para resolver este problema, como muestra nuestra página offline, y algunos problemas han sido solucionados. Pero el problema primordial es que todavía no hay un mecanismo de control eficiente para el almacenamiento en caché de activos y solicitudes de red personalizadas.

- -

El mecanismo previamente utilizado -el AppCache- parecía una buena idea porque te permitía especificar los recursos que almacenarías en caché de una forma realmente fácil. Sin embargo, AppCache presuponía lo que el desarrollador trataba de crear y fallaba demasiado cuando la aplicación no se comportaba exactamente según las suposiciones iniciales. Veáse el artículo de Jake Archibald Application Cache is a Douchebag para más información.

- -
-

Nota: A partir de Firefox 44, cuando se usa AppCache para proveer soporte offline a una página se muestra un mensaje de advertencia en la consola aconsejandole al desarrollador para que  use Service workers en su lugar ({{bug("1204581")}}.)

-
- -

Los Service workers deberían finalmente solucionar estos inconvenientes. Aunque la sintaxis de Service Worker es más compleja que la de AppCache, presenta la ventaja de que puede usar JavaScript para controlar los recursos de cache con gran detalle, permitiendo gestionar los problemas asociados a  AppCache, y muchos más.

- -

Al utilizar un Service Worker, puedes configurar fácilmente una aplicación para que utilice primero los recursos en caché antes de obtener alguna información de la red (Comunmente conocido como Offline First) lo que proporciona la experiencia de uso predeterminada incluso cuando se está offline. Este paradigma se usa en aplicaciones nativas, y es una de las principales razones por las que a menudo éstas se eligen por encima de las aplicaciones web.

- -

Setting up to play with service workers

- -

Many service workers features are now enabled by default in newer versions of supporting browsers. If however you find that demo code is not working in your installed versions, you might need to enable a pref:

- - - -

You’ll also need to serve your code via HTTPS — Service workers are restricted to running across HTTPS for security reasons. GitHub is therefore a good place to host experiments, as it supports HTTPS. In order to facilitate local development, localhost is considered a secure origin by browsers as well.

- -

Basic architecture

- -

With service workers, the following steps are generally observed for basic set up:

- -
    -
  1. The service worker URL is fetched and registered via {{domxref("serviceWorkerContainer.register()")}}.
  2. -
  3. If successful, the service worker is executed in a {{domxref("ServiceWorkerGlobalScope") }}; this is basically a special kind of worker context, running off the main script execution thread, with no DOM access.
  4. -
  5. The service worker is now ready to process events.
  6. -
  7. Installation of the worker is attempted when service worker-controlled pages are accessed subsequently. An Install event is always the first one sent to a service worker (this can be used to start the process of populating an IndexedDB, and caching site assets). This is really the same kind of procedure as installing a native or Firefox OS app — making everything available for use offline.
  8. -
  9. When the oninstall handler completes, the service worker is considered installed.
  10. -
  11. Next is activation. When the service worker is installed, it then receives an activate event. The primary use of onactivate is for cleanup of resources used in previous versions of a Service worker script.
  12. -
  13. The Service worker will now control pages, but only those opened after the register() is successful. i.e. a document starts life with or without a Service worker and maintains that for its lifetime. So documents will have to be reloaded to actually be controlled.
  14. -
- -

- -

The below graphic shows a summary of the available service worker events:

- -

install, activate, message, fetch, sync, push

- -

Promises

- -

Las promesas (Promises) son un gran mecanismo para ejecutar operaciones asíncronas,  con éxito dependiente el uno del otro. Esto es fundamental para la forma en que trabajan los service workers.
-
- Promises can do a great many things, but for now, all you need to know is that if something returns a promise, you can attach .then() to the end and include callbacks inside it for success, failure, etc., or you can insert .catch() on the end if you want to include a failure callback.

- -

Let’s compare a traditional synchronous callback structure to its asynchronous promise equivalent.

- -

sync

- -
try {
-  var value = myFunction();
-  console.log(value);
-} catch(err) {
-  console.log(err);
-}
- -

async

- -
myFunction().then(function(value) {
-  console.log(value);
-}).catch(function(err) {
-  console.log(err);
-});
- -

In the first example, we have to wait for myFunction() to run and return value before any more of the code can execute. In the second example, myFunction() returns a promise for value, then the rest of the code can carry on running. When the promise resolves, the code inside then will be run, asynchronously.
-
- Now for a real example — what if we wanted to load images dynamically, but we wanted to make sure the images were loaded before we tried to display them? This is a standard thing to want to do, but it can be a bit of a pain. We can use .onload to only display the image after it’s loaded, but what about events that start happening before we start listening to them? We could try to work around this using .complete, but it’s still not foolproof, and what about multiple images? And, ummm, it’s still synchronous, so blocks the main thread.
-
- Instead, we could build our own promise to handle this kind of case. (See our Promises test example for the source code, or look at it running live.)

- -

{{note("A real service worker implementation would use caching and onfetch rather than the deprecated XMLHttpRequest API. Those features are not used here so that you can focus on understanding Promises.")}}

- -
function imgLoad(url) {
-  return new Promise(function(resolve, reject) {
-    var request = new XMLHttpRequest();
-    request.open('GET', url);
-    request.responseType = 'blob';
-
-    request.onload = function() {
-      if (request.status == 200) {
-        resolve(request.response);
-      } else {
-        reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
-      }
-    };
-
-    request.onerror = function() {
-      reject(Error('There was a network error.'));
-    };
-
-    request.send();
-  });
-}
- -

We return a new promise using the Promise() constructor, which takes as an argument a callback function with resolve and reject parameters. Somewhere in the function, we need to define what happens for the promise to resolve successfully or be rejected — in this case return a 200 OK status or not — and then call resolve on success, or reject on failure. The rest of the contents of this function is fairly standard XHR stuff, so we won’t worry about that for now.

- -

When we come to call the imgLoad() function, we call it with the url to the image we want to load, as we might expect, but the rest of the code is a little different:

- -
var body = document.querySelector('body');
-var myImage = new Image();
-
-imgLoad('myLittleVader.jpg').then(function(response) {
-  var imageURL = window.URL.createObjectURL(response);
-  myImage.src = imageURL;
-  body.appendChild(myImage);
-}, function(Error) {
-  console.log(Error);
-});
- -

On to the end of the function call, we chain the promise then() method, which contains two functions — the first one is executed when the promise successfully resolves, and the second is called when the promise is rejected. In the resolved case, we display the image inside myImage and append it to the body (it’s argument is the request.response contained inside the promise’s resolve method); in the rejected case we return an error to the console.

- -

This all happens asynchronously.

- -
-

Note: You can also chain promise calls together, for example:
- myPromise().then(success, failure).then(success).catch(failure);

-
- -
-

Note: You can find a lot more out about promises by reading Jake Archibald’s excellent JavaScript Promises: there and back again.

-
- -

Service workers demo

- -

To demonstrate just the very basics of registering and installing a service worker, we have created a simple demo called sw-test, which is a simple Star wars Lego image gallery. It uses a promise-powered function to read image data from a JSON object and load the images using Ajax, before displaying the images in a line down the page. We’ve kept things static and simple for now. It also registers, installs, and activates a service worker, and when more of the spec is supported by browsers it will cache all the files required so it will work offline!

- -


-
-
- You can see the source code on GitHub, and view the example live. The one bit we’ll call out here is the promise (see app.js lines 22-47), which is a modified version of what you read about above, in the Promises test demo. It is different in the following ways:

- -
    -
  1. In the original, we only passed in a URL to an image we wanted to load. In this version, we pass in a JSON fragment containing all the data for a single image (see what they look like in image-list.js). This is because all the data for each promise resolve has to be passed in with the promise, as it is asynchronous. If you just passed in the url, and then tried to access the other items in the JSON separately when the for() loop is being iterated through later on, it wouldn’t work, as the promise wouldn’t resolve at the same time as the iterations are being done (that is a synchronous process.)
  2. -
  3. We actually resolve the promise with an array, as we want to make the loaded image blob available to the resolving function later on in the code, but also the image name, credits and alt text (see app.js lines 31-34). Promises will only resolve with a single argument, so if you want to resolve with multiple values, you need to use an array/object.
  4. -
  5. To access the resolved promise values, we then access this function as you’d then expect (see app.js lines 60-64). This may seem a bit odd at first, but this is the way promises work.
  6. -
- -

Enter service workers

- -

Now let’s get on to service workers!

- -

Registering your worker

- -

The first block of code in our app’s JavaScript file — app.js — is as follows. This is our entry point into using service workers.

- -
if ('serviceWorker' in navigator) {
-  navigator.serviceWorker.register('/sw-test/sw.js', {scope: '/sw-test/'})
-  .then(function(reg) {
-    // registration worked
-    console.log('Registration succeeded. Scope is ' + reg.scope);
-  }).catch(function(error) {
-    // registration failed
-    console.log('Registration failed with ' + error);
-  });
-}
- -
    -
  1. The outer block performs a feature detection test to make sure service workers are supported before trying to register one.
  2. -
  3. Next, we use the {{domxref("ServiceWorkerContainer.register()") }} function to register the service worker for this site, which is just a JavaScript file residing inside our app (note this is the file's URL relative to the origin, not the JS file that references it.)
  4. -
  5. The scope parameter is optional, and can be used to specify the subset of your content that you want the service worker to control. In this case, we have specified '/sw-test/', which means all content under the app's origin. If you leave it out, it will default to this value anyway, but we specified it here for illustration purposes.
  6. -
  7. The .then() promise function is used to chain a success case onto our promise structure.  When the promise resolves successfully, the code inside it executes.
  8. -
  9. Finally, we chain a .catch() function onto the end that will run if the promise is rejected.
  10. -
- -

This registers a service worker, which runs in a worker context, and therefore has no DOM access. You then run code in the service worker outside of your normal pages to control their loading.
-
- A single service worker can control many pages. Each time a page within your scope is loaded, the service worker is installed against that page and operates on it. Bear in mind therefore that you need to be careful with global variables in the service worker script: each page doesn’t get its own unique worker.

- -
-

Note: Your service worker functions like a proxy server, allowing you to modify requests and responses, replace them with items from its own cache, and more.

-
- -
-

Note: One great thing about service workers is that if you use feature detection like we’ve shown above, browsers that don’t support service workers can just use your app online in the normal expected fashion. Furthermore, if you use AppCache and SW on a page, browsers that don’t support SW but do support AppCache will use that, and browsers that support both will ignore the AppCache and let SW take over.

-
- -

Why is my service worker failing to register?

- -

This could be for the following reasons:

- -
    -
  1. You are not running your application through HTTPS.
  2. -
  3. The path to your service worker file is not written correctly — it needs to be written relative to the origin, not your app’s root directory. In our example, the worker is at https://mdn.github.io/sw-test/sw.js, and the app’s root is https://mdn.github.io/sw-test/. But the path needs to be written as /sw-test/sw.js, not /sw.js.
  4. -
  5. The service worker being pointed to is on a different origin to that of your app. This is also not allowed.
  6. -
- -

- -

Also note:

- - - -

Install and activate: populating your cache

- -

After your service worker is registered, the browser will attempt to install then activate the service worker for your page/site.
-
- The install event is fired when an install is successfully completed. The install event is generally used to populate your browser’s offline caching capabilities with the assets you need to run your app offline. To do this, we use Service Worker’s brand new storage API — {{domxref("cache")}} — a global on the service worker that allows us to store assets delivered by responses, and keyed by their requests. This API works in a similar way to the browser’s standard cache, but it is specific to your domain. It persists until you tell it not to — again, you have full control.

- -
-

Note: The Cache API is not supported in every browser. (See the {{anch("Browser support")}} section for more information.) If you want to use this now, you could consider using a polyfill like the one available in Google's Topeka demo, or perhaps store your assets in IndexedDB.

-
- -

Let’s start this section by looking at a code sample — this is the first block you’ll find in our service worker:

- -
this.addEventListener('install', function(event) {
-  event.waitUntil(
-    caches.open('v1').then(function(cache) {
-      return cache.addAll([
-        '/sw-test/',
-        '/sw-test/index.html',
-        '/sw-test/style.css',
-        '/sw-test/app.js',
-        '/sw-test/image-list.js',
-        '/sw-test/star-wars-logo.jpg',
-        '/sw-test/gallery/',
-        '/sw-test/gallery/bountyHunters.jpg',
-        '/sw-test/gallery/myLittleVader.jpg',
-        '/sw-test/gallery/snowTroopers.jpg'
-      ]);
-    })
-  );
-});
- -
    -
  1. Here we add an install event listener to the service worker (hence this), and then chain a {{domxref("ExtendableEvent.waitUntil()") }} method onto the event — this ensures that the service worker will not install until the code inside waitUntil() has successfully occurred.
  2. -
  3. Inside waitUntil() we use the caches.open() method to create a new cache called v1, which will be version 1 of our site resources cache. This returns a promise for a created cache; once resolved, we then call a function that calls addAll() on the created cache, which for its parameter takes an array of origin-relative URLs to all the resources you want to cache.
  4. -
  5. If the promise is rejected, the install fails, and the worker won’t do anything. This is ok, as you can fix your code and then try again the next time registration occurs.
  6. -
  7. After a successful installation, the service worker activates. This doesn’t have much of a distinct use the first time your service worker is installed/activated, but it means more when the service worker is updated (see the {{anch("Updating your service worker") }} section later on.)
  8. -
- -
-

Note: localStorage works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.

-
- -
-

Note: IndexedDB can be used inside a service worker for data storage if you require it.

-
- -

Custom responses to requests

- -

Now you’ve got your site assets cached, you need to tell service workers to do something with the cached content. This is easily done with the fetch event.

- -

- -

A fetch event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents (for example if index.html makes a cross origin request to embed an image, that still goes through its service worker.)

- -

You can attach a fetch event listener to the service worker, then call the respondWith() method on the event to hijack our HTTP responses and update them with your own magic.

- -
this.addEventListener('fetch', function(event) {
-  event.respondWith(
-    // magic goes here
-  );
-});
- -

We could start by simply responding with the resource whose url matches that of the network request, in each case:

- -
this.addEventListener('fetch', function(event) {
-  event.respondWith(
-    caches.match(event.request)
-  );
-});
- -

caches.match(event.request) allows us to match each resource requested from the network with the equivalent resource available in the cache, if there is a matching one available. The matching is done via url and vary headers, just like with normal HTTP requests.

- -

Let’s look at a few other options we have when defining our magic (see our Fetch API documentation for more information about {{domxref("Request")}} and {{domxref("Response")}} objects.)

- -
    -
  1. -

    The {{domxref("Response.Response","Response()")}} constructor allows you to create a custom response. In this case, we are just returning a simple text string:

    - -
    new Response('Hello from your friendly neighbourhood service worker!');
    -
  2. -
  3. -

    This more complex Response below shows that you can optionally pass a set of headers in with your response, emulating standard HTTP response headers. Here we are just telling the browser what the content type of our synthetic response is:

    - -
    new Response('<p>Hello from your friendly neighbourhood service worker!</p>', {
    -  headers: { 'Content-Type': 'text/html' }
    -});
    -
  4. -
  5. -

    If a match wasn’t found in the cache, you could tell the browser to simply {{domxref("GlobalFetch.fetch","fetch")}} the default network request for that resource, to get the new resource from the network if it is available:

    - -
    fetch(event.request);
    -
  6. -
  7. -

    If a match wasn’t found in the cache, and the network isn’t available, you could just match the request with some kind of default fallback page as a response using {{domxref("CacheStorage.match","match()")}}, like this:

    - -
    caches.match('/fallback.html');
    -
  8. -
  9. -

    You can retrieve a lot of information about each request by calling parameters of the {{domxref("Request")}} object returned by the {{domxref("FetchEvent")}}:

    - -
    event.request.url
    -event.request.method
    -event.request.headers
    -event.request.body
    -
  10. -
- -

Recovering failed requests

- -

So caches.match(event.request) is great when there is a match in the service worker cache, but what about cases when there isn’t a match? If we didn’t provide any kind of failure handling, our promise would resolve with undefined and we wouldn't get anything returned.

- -

Fortunately service workers’ promise-based structure makes it trivial to provide further options towards success. We could do this:

- -
this.addEventListener('fetch', function(event) {
-  event.respondWith(
-    caches.match(event.request).then(function(response) {
-      return response || fetch(event.request);
-    })
-  );
-});
- -

If the resources isn't in the cache, it is requested from the network.

- -

If we were being really clever, we would not only request the resource from the network; we would also save it into the cache so that later requests for that resource could be retrieved offline too! This would mean that if extra images were added to the Star Wars gallery, our app could automatically grab them and cache them. The following would do the trick:

- -
this.addEventListener('fetch', function(event) {
-  event.respondWith(
-    caches.match(event.request).then(function(resp) {
-      return resp || fetch(event.request).then(function(response) {
-        return caches.open('v1').then(function(cache) {
-          cache.put(event.request, response.clone());
-          return response;
-        });
-      });
-    })
-  );
-});
- -

Here we return the default network request with return fetch(event.request), which returns a promise. When this promise is resolved, we respond by running a function that grabs our cache using caches.open('v1'); this also returns a promise. When that promise resolves, cache.put() is used to add the resource to the cache. The resource is grabbed from event.request, and the response is then cloned with response.clone() and added to the cache. The clone is put in the cache, and the original response is returned to the browser to be given to the page that called it.

- -

Cloning the response is necessary because request and response streams can only be read once.  In order to return the response to the browser and put it in the cache we have to clone it. So the original gets returned to the browser and the clone gets sent to the cache.  They are each read once.

- -

The only trouble we have now is that if the request doesn’t match anything in the cache, and the network is not available, our request will still fail. Let’s provide a default fallback so that whatever happens, the user will at least get something:

- -
this.addEventListener('fetch', function(event) {
-  event.respondWith(
-    caches.match(event.request).then(function(resp) {
-      return resp || fetch(event.request).then(function(response) {
-        caches.open('v1').then(function(cache) {
-          cache.put(event.request, response.clone());
-        });
-        return response;
-      });
-    }).catch(function() {
-      return caches.match('/sw-test/gallery/myLittleVader.jpg');
-    })
-  );
-});
- -

We have opted for this fallback image because the only updates that are likely to fail are new images, as everything else is depended on for installation in the install event listener we saw earlier.

- -

Updating your service worker

- -

If your service worker has previously been installed, but then a new version of the worker is available on refresh or page load, the new version is installed in the background, but not yet activated. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates.

- -

You’ll want to update your install event listener in the new service worker to something like this (notice the new version number):

- -
this.addEventListener('install', function(event) {
-  event.waitUntil(
-    caches.open('v2').then(function(cache) {
-      return cache.addAll([
-        '/sw-test/',
-        '/sw-test/index.html',
-        '/sw-test/style.css',
-        '/sw-test/app.js',
-        '/sw-test/image-list.js',
-
-        …
-
-        // include other new resources for the new version...
-      ]);
-    })
-  );
-});
- -

While this happens, the previous version is still responsible for fetches. The new version is installing in the background. We are calling the new cache v2, so the previous v1 cache isn't disturbed.

- -

When no pages are using the current version, the new worker activates and becomes responsible for fetches.

- -

Deleting old caches

- -

You also get an activate event. This is a generally used to do stuff that would have broken the previous version while it was still running, for example getting rid of old caches. This is also useful for removing data that is no longer needed to avoid filling up too much disk space — each browser has a hard limit on the amount of cache storage that a given service worker can use. The browser does its best to manage disk space, but it may delete the Cache storage for an origin.  The browser will generally delete all of the data for an origin or none of the data for an origin.

- -

Promises passed into waitUntil() will block other events until completion, so you can rest assured that your clean-up operation will have completed by the time you get your first fetch event on the new cache.

- -
this.addEventListener('activate', function(event) {
-  var cacheWhitelist = ['v2'];
-
-  event.waitUntil(
-    caches.keys().then(function(keyList) {
-      return Promise.all(keyList.map(function(key) {
-        if (cacheWhitelist.indexOf(key) === -1) {
-          return caches.delete(key);
-        }
-      }));
-    })
-  );
-});
- -

Developer tools

- -

Chrome has chrome://inspect/#service-workers, which shows current service worker activity and storage on a device, and chrome://serviceworker-internals, which shows more detail and allows you to start/stop/debug the worker process. In the future they will have throttling/offline modes to simulate bad or non-existent connections, which will be a really good thing.

- -

Firefox has also started to implement some useful tools related to service workers:

- - - -
-

Note: You may serve your app from http://localhost (e.g. using me@localhost:/my/app$ python -m SimpleHTTPServer) for local development. See Security considerations

-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Service Workers', '')}}{{Spec2('Service Workers')}}Initial definition.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("33.0") }}[1]{{CompatNo}}24{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(40.0)}}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}{{CompatNo}}{{ CompatVersionUnknown() }}{{CompatNo}}
-
- -

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

- -

See also

- - diff --git a/files/es/web/api/serviceworkerregistration/index.html b/files/es/web/api/serviceworkerregistration/index.html deleted file mode 100644 index 88f1c3da52..0000000000 --- a/files/es/web/api/serviceworkerregistration/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: ServiceWorkerRegistration -slug: Web/API/ServiceWorkerRegistration -tags: - - API - - Interface - - NeedsTranslation - - Offline - - Reference - - Service Workers - - Service worker API - - ServiceWorkerRegistration - - TopicStub - - Workers -translation_of: Web/API/ServiceWorkerRegistration ---- -
-
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
-
- -

The ServiceWorkerRegistration interface of the ServiceWorker API represents the service worker registration. You register a service worker to control one or more pages that share the same origin.

- -

The lifetime of a service worker registration is beyond that of the ServiceWorkerRegistration objects that represent them within the lifetime of their corresponding service worker clients. The browser maintains a persistent list of active ServiceWorkerRegistration objects.

- -
-

Note: This feature is available in Web Workers.

-
- -

Properties

- -

Also implements properties from its parent interface, {{domxref("EventTarget")}}.

- -
-
{{domxref("ServiceWorkerRegistration.scope")}} {{readonlyinline}}
-
Returns a unique identifier for a service worker registration. This must be on the same origin as the document that registers the {{domxref("ServiceWorker")}}.
-
{{domxref("ServiceWorkerRegistration.installing")}} {{readonlyinline}}
-
Returns a service worker whose state is installing. This is initially set to null.
-
{{domxref("ServiceWorkerRegistration.waiting")}} {{readonlyinline}}
-
Returns a service worker whose state is waiting. This is initially set to null.
-
{{domxref("ServiceWorkerRegistration.active")}} {{readonlyinline}}
-
Returns a service worker whose state is either activating or activated. This is initially set to null. An active worker will control a {{domxref("ServiceWorkerClient")}} if the client's URL falls within the scope of the registration (the scope option set when {{domxref("ServiceWorkerContainer.register")}} is first called.)
-
{{domxref("ServiceWorkerRegistration.navigationPreload")}} {{readonlyinline}}
-
Returns the instance of {{domxref("NavigationPreloadManager")}} associated with the current service worker registration.
-
{{domxref("serviceWorkerRegistration.periodicSync")}} {{non-standard_inline}} {{readonlyinline}}
-
Returns a reference to the {{domxref("PeriodicSyncManager")}} interface, which manages periodic background synchronization processes.
-
{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}
-
Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status.
-
{{domxref("ServiceWorkerRegistration.sync")}} {{non-standard_inline}} {{readonlyinline}} 
-
Returns a reference to the {{domxref("SyncManager")}} interface, which manages background synchronization processes.
-
- -

Event handlers

- -
-
{{domxref("ServiceWorkerRegistration.onupdatefound")}} {{readonlyinline}}
-
An EventListener property called whenever an event of type updatefound is fired; it is fired any time the {{domxref("ServiceWorkerRegistration.installing")}} property acquires a new service worker.
-
- -

Methods

- -

Also implements methods from its parent interface, {{domxref("EventTarget")}}.

- -
-
{{domxref("ServiceWorkerRegistration.getNotifications()")}}
-
Returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("Notification")}} objects.
-
{{domxref("ServiceWorkerRegistration.showNotification()")}}
-
Displays the notification with the requested title.
-
{{domxref("ServiceWorkerRegistration.update()")}}
-
Checks the server for an updated version of the service worker without consulting caches.
-
{{domxref("ServiceWorkerRegistration.unregister()")}}
-
Unregisters the service worker registration and returns a {{jsxref("Promise")}}. The service worker will finish any ongoing operations before it is unregistered.
-
- -

Examples

- -

In this example, the code first checks whether the browser supports service workers and if so registers one. Next, it adds and updatefound event in which it uses the service worker registration to listen for further changes to the service worker's state. If the service worker hasn't changed since the last time it was registered, than the updatefound event will not be fired.

- -
if ('serviceWorker' in navigator) {
-  navigator.serviceWorker.register('/sw.js')
-  .then(function(registration) {
-    registration.addEventListener('updatefound', function() {
-      // If updatefound is fired, it means that there's
-      // a new service worker being installed.
-      var installingWorker = registration.installing;
-      console.log('A new service worker is being installed:',
-        installingWorker);
-
-      // You can listen for changes to the installing service worker's
-      // state via installingWorker.onstatechange
-    });
-  })
-  .catch(function(error) {
-    console.log('Service worker registration failed:', error);
-  });
-} else {
-  console.log('Service workers are not supported.');
-}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-registration-obj', 'ServiceWorkerRegistration')}}{{Spec2('Service Workers')}}Initial definition.
{{SpecName('Push API', '#widl-ServiceWorkerRegistration-pushManager', 'PushManager')}}{{Spec2('Push API')}}Adds the {{domxref("PushManager","pushManager")}} property.
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Adds the {{domxref("ServiceWorkerRegistration.showNotification()","showNotification()")}} method and the {{domxref("ServiceWorkerRegistration.getNotifications()","getNotifications()")}} method.
{{SpecName('Background Sync')}}{{Spec2('Background Sync')}}Adds the {{domxref("ServiceWorkerRegistration.sync","sync")}} property.
- -

Browser compatibility

- - - -

{{Compat("api.ServiceWorkerRegistration")}}

- -

See also

- - diff --git a/files/es/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html b/files/es/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html deleted file mode 100644 index ad9b98310a..0000000000 --- a/files/es/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Animación de Objetos con WebGL -slug: Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL -tags: - - WebGL -translation_of: Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL ---- -

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL", "Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL") }}

- -

Our existing code from the previous examples is already configured to redraw our WebGL scene every 15 milliseconds. Until now, it's simply redrawing everything exactly the same way every time. It's time to change that, so that our square actually moves.

- -

In this example, we'll actually rotate and move our 2D square in all three dimensions; this will prove that even though we're only creating a 2D object, it still exists in 3D space.

- -

Making the square rotate

- -

Let's start by making the square rotate. The first thing we'll need is a variable in which to track the current rotation of the square:

- -
var squareRotation = 0.0;
-
- -

Now we need to update the drawScene() function to apply the current rotation to the square when drawing it. After translating to the initial drawing position for the square, we apply the rotation like this:

- -
mvPushMatrix();
-mvRotate(squareRotation, [1, 0, 1]);
-
- -

This saves the current model-view matrix, then rotates the matrix by the current value of squareRotation, around the X and Z axes.

- -

After drawing, we need to restore the original matrix:

- -
  mvPopMatrix();
-
- -

We save and restore the original matrix to avoid having this rotation applied to other objects we might draw.

- -

To actually animate, we need to add code that changes the value of squareRotation over time. We can do that by creating a new variable to track the time at which we last animated (let's call it lastSquareUpdateTime), then adding the following code to the end of the drawScene() function:

- -
  var currentTime = (new Date).getTime();
-  if (lastSquareUpdateTime) {
-  	var delta = currentTime - lastSquareUpdateTime;
-
-  	squareRotation += (30 * delta) / 1000.0;
-  }
-
-  lastSquareUpdateTime = currentTime;
-
- -

This code uses the amount of time that's passed since the last time we updated the value of squareRotation to determine how far to rotate the square.

- -

Making the square move

- -

We can also move the square around by translating to a different position before drawing it. This example is going to do some very basic animation; obviously in the real world you'd want to do something less insane.

- -

Let's track offsets to each axis for our translation in new variables:

- -
var squareXOffset = 0.0;
-var squareYOffset = 0.0;
-var squareZOffset = 0.0;
-
- -

And the amount by which to change our position on each axis in these variables:

- -
var xIncValue = 0.2;
-var yIncValue = -0.4;
-var zIncValue = 0.3;
-
- -

Now we can simply add this code to the previous code that updates the rotation:

- -
    squareXOffset += xIncValue * ((30 * delta) / 1000.0);
-    squareYOffset += yIncValue * ((30 * delta) / 1000.0);
-    squareZOffset += zIncValue * ((30 * delta) / 1000.0);
-
-    if (Math.abs(squareYOffset) > 2.5) {
-      xIncValue = -xIncValue;
-      yIncValue = -yIncValue;
-      zIncValue = -zIncValue;
-    }
-
- -

This causes our square to zoom around, moving haphazardly around the context as well as toward and away from the viewer, all while rotating. It looks rather like a screen saver.

- -

If your browser supports WebGL, click here to take a look at this example in action.

- -

More matrix operations

- -

This example uses a few additional matrix operations, including two routines to push and pop matrices from a stack to preserve them, and one that rotates a matrix a given number of degrees. These follow, for your reference:

- -
var mvMatrixStack = [];
-
-function mvPushMatrix(m) {
-  if (m) {
-    mvMatrixStack.push(m.dup());
-    mvMatrix = m.dup();
-  } else {
-    mvMatrixStack.push(mvMatrix.dup());
-  }
-}
-
-function mvPopMatrix() {
-  if (!mvMatrixStack.length) {
-    throw("Can't pop from an empty matrix stack.");
-  }
-
-  mvMatrix = mvMatrixStack.pop();
-  return mvMatrix;
-}
-
-function mvRotate(angle, v) {
-  var inRadians = angle * Math.PI / 180.0;
-
-  var m = Matrix.Rotation(inRadians, $V([v[0], v[1], v[2]])).ensure4x4();
-  multMatrix(m);
-}
-
- -

These routines were borrowed from a sample previously written by Vlad Vukićević.

- -

{{PreviousNext("Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL", "Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL") }}

diff --git a/files/es/web/api/window/sidebar/index.html b/files/es/web/api/window/sidebar/index.html deleted file mode 100644 index 280b5dcce3..0000000000 --- a/files/es/web/api/window/sidebar/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Window.sidebar -slug: Web/API/Window/sidebar -tags: - - DOM - - NeedsTranslation - - Non-standard - - Property - - Reference - - TopicStub - - Window -translation_of: Web/API/Window/sidebar ---- -
{{APIRef}} {{Non-standard_header}}
- -

Returns a sidebar object, which contains several methods for registering add-ons with the browser.

- -

Notes

- -

The sidebar object returned has the following methods:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MethodDescription (SeaMonkey)Description (Firefox)
addPanel(title, contentURL, "")Adds a sidebar panel.Obsolete since Firefox 23 (only present in SeaMonkey).
- End users can use the "load this bookmark in the sidebar" option instead. Also see Creating a Firefox sidebar.
addPersistentPanel(title, contentURL, "")Adds a sidebar panel, which is able to work in the background.
AddSearchProvider(descriptionURL)Installs a search provider (OpenSearch). Adding OpenSearch search engines contains more details. Added in Firefox 2.
addSearchEngine(engineURL, iconURL, suggestedTitle, suggestedCategory) {{Obsolete_inline(44)}}Installs a search engine (Sherlock). Adding Sherlock search engines contains more details.
IsSearchProviderInstalled(descriptionURL)Indicates if a specific search provider (OpenSearch) is installed.
- -

Specification

- -

Mozilla-specific. Not part of any standard.

diff --git a/files/es/web/api/windoweventhandlers/onunload/index.html b/files/es/web/api/windoweventhandlers/onunload/index.html deleted file mode 100644 index 111f87edf2..0000000000 --- a/files/es/web/api/windoweventhandlers/onunload/index.html +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: window.onunload -slug: Web/API/WindowEventHandlers/onunload -translation_of: Web/API/WindowEventHandlers/onunload -original_slug: Web/API/GlobalEventHandlers/onunload ---- -

{{ ApiRef() }}

-

Test Summary

-

The unload event is raised when the document is unloaded.

-

Syntax

-
window.onunload = funcRef;
-
- -

Example

-
<html>
-<head>
-
-<title>onunload test</title>
-
-<script type="text/javascript">
-
-window.onunload = unloadPage;
-
-function unloadPage()
-{
- alert("unload event detected!");
-}
-</script>
-</head>
-
-<body>
-<p>Reload a new page into the browser<br />
- to fire the unload event for this page.</p>
-<p>You can also use the back or forward buttons<br />
- to load a new page and fire this event.</p>
-</body>
-</html>
-
-

Notes

-

Note that using this event handler in your page prevents Firefox 1.5 from caching the page in the in-memory bfcache. See Using Firefox 1.5 caching for details.

-

Browsers equipped with pop-up window blockers will ignore all window.open() method calls in onunload event handler functions.

-

Specification

-

{{ DOM0() }}

-

{{ languages( {"zh-cn": "zh-cn/DOM/window.onunload" } ) }}

diff --git a/files/es/web/api/xmlhttprequesteventtarget/index.html b/files/es/web/api/xmlhttprequesteventtarget/index.html deleted file mode 100644 index f53063d82b..0000000000 --- a/files/es/web/api/xmlhttprequesteventtarget/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: XMLHttpRequestEventTarget -slug: Web/API/XMLHttpRequestEventTarget -tags: - - AJAX - - API - - NeedsBrowserCompatibility - - NeedsContent - - NeedsTranslation - - Reference - - TopicStub - - XMLHttpRequest -translation_of: Web/API/XMLHttpRequestEventTarget ---- -

{{APIRef("XMLHttpRequest")}}

- -

XMLHttpRequestEventTarget is the interface that describes the event handlers you can implement in an object that will handle events for an {{ domxref("XMLHttpRequest") }}.

- -

{{InheritanceDiagram}}

- -

Properties

- -
-
{{ domxref("XMLHttpRequestEventTarget.onabort") }}
-
Contains the function to call when a request is aborted and the {{event('abort')}} event is received by this object.
-
{{ domxref("XMLHttpRequestEventTarget.onerror") }}
-
Contains the function to call when a request encounters an error and the {{event('error')}} event is received by this object.
-
{{ domxref("XMLHttpRequestEventTarget.onload") }}
-
Contains the function to call when an HTTP request returns after successfully fetching content and the {{event('load')}} event is received by this object.
-
{{ domxref("XMLHttpRequestEventTarget.onloadstart") }}
-
Contains the function that gets called when the HTTP request first begins loading data and the {{event('loadstart')}} event is received by this object.
-
{{ domxref("XMLHttpRequestEventTarget.onprogress") }}
-
Contains the function that is called periodically with information about the progress of the request and the {{event('progress')}} event is received by this object.
-
{{ domxref("XMLHttpRequestEventTarget.ontimeout") }}
-
Contains the function that is called if the event times out and the {{event("timeout")}} event is received by this object; this only happens if a timeout has been previously established by setting the value of the XMLHttpRequest object's timeout attribute.
-
{{ domxref("XMLHttpRequestEventTarget.onloadend") }}
-
Contains the function that is called when the load is completed, even if the request failed, and the {{event('loadend')}} event is received by this object.
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
- -

Browser compatibility

- - - -

{{Compat("api.XMLHttpRequestEventTarget")}}

- -

See also

- - diff --git a/files/es/web/api/xmlhttprequesteventtarget/onload/index.html b/files/es/web/api/xmlhttprequesteventtarget/onload/index.html deleted file mode 100644 index c6d6f78974..0000000000 --- a/files/es/web/api/xmlhttprequesteventtarget/onload/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: XMLHttpRequestEventTarget.onload -slug: Web/API/XMLHttpRequestEventTarget/onload -translation_of: Web/API/XMLHttpRequestEventTarget/onload ---- -
{{APIRef("XMLHttpRequest")}}
- -

El evento XMLHttpRequestEventTarget.onload es la función que se llama cuando una transacción del {{domxref("XMLHttpRequest")}} es ejecutada correctamente.

- -

Sintaxis

- -
XMLHttpRequest.onload = callback;
- -

 Valores

- - - -

Ejemplo

- -
var xmlhttp = new XMLHttpRequest(),
-  method = 'GET',
-  url = 'https://developer.mozilla.org/';
-
-xmlhttp.open(method, url, true);
-xmlhttp.onload = function () {
-  // Hacer algo con la información recivida ( found in xmlhttp.response )
-};
-xmlhttp.send();
-
- -

Especificaciones

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#handler-xhr-onload')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
- -

Browser compatibility

- - - -

{{Compat("api.XMLHttpRequestEventTarget.onload")}}

-- cgit v1.2.3-54-g00ecf