diff options
Diffstat (limited to 'files/es/web/api')
27 files changed, 0 insertions, 4376 deletions
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 ---- -<div>{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_shapes", "Web/API/Canvas_API/Tutorial/Drawing_text")}}</div> - -<div class="summary"> -<p>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.</p> -</div> - -<h2 id="Colors" name="Colors">Colors</h2> - -<p>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: <code>fillStyle</code> y <code>strokeStyle</code>.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle = color")}}</dt> - <dd>Configura el estilo cuando se rellenan las formas.</dd> - <dt>{{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle = color")}}</dt> - <dd>Configura el estilo al contorno perimetral de las formas.</dd> -</dl> - -<p><code>color</code> 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 <code>#000000</code>).</p> - -<div class="note"> -<p><strong>Nota: </strong> Cuando configuras la propiedad <code>strokeStyle</code> y/o <code>fillStyle</code>, 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.</p> -</div> - -<p>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.</p> - -<pre class="brush: js">// 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)'; -</pre> - -<h3 id="A_fillStyle_example" name="A_fillStyle_example">A <code>fillStyle</code> example</h3> - -<p>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.</p> - -<pre class="brush: js;highlight[5,6]">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); - } - } -}</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>The result looks like this:</p> - -<p>{{EmbedLiveSample("A_fillStyle_example", 160, 160, "https://mdn.mozillademos.org/files/5417/Canvas_fillstyle.png")}}</p> - -<h3 id="A_strokeStyle_example" name="A_strokeStyle_example">A <code>strokeStyle</code> example</h3> - -<p>Este ejemplo es similar al de arriba, pero usa la propiedad <code>strokeStyle</code> para cambiar el color del contorno de las formas. Usamos el método <code>arc()</code> para dibujar circulos en lugar de celdas cuadradas.</p> - -<pre class="brush: js;highlight[5,6]"> 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(); - } - } - } -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>The result looks like this:</p> - -<p>{{EmbedLiveSample("A_strokeStyle_example", "180", "180", "https://mdn.mozillademos.org/files/253/Canvas_strokestyle.png")}}</p> - -<h2 id="Transparency" name="Transparency">Transparency</h2> - -<p>Ademas de dibujar formas opacas en el canvas, podemos dibujar formas semi-transparentes(o translucidas). Esto se logra bien configurando la propiedad <code>globalAlpha</code> o asignando un color semi-transparente al estilo del trazo u u/y al de relleno.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.globalAlpha", "globalAlpha = transparencyValue")}}</dt> - <dd>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.</dd> -</dl> - -<p>The <code>globalAlpha</code> 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.</p> - -<p>Debido qaque las propiedades <code>strokeStyle</code> y <code>fillStyle</code> aceptan valores de color rgba de CSS, podemos usar la siguiente notacion para asignar una color transparente a ellos.</p> - -<pre class="brush: js">// Assigning transparent colors to stroke and fill style - -ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)'; -ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'; -</pre> - -<p>The <code>rgba()</code> function is similar to the <code>rgb()</code> 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).</p> - -<h3 id="A_globalAlpha_example" name="A_globalAlpha_example">A <code>globalAlpha</code> example</h3> - -<p>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 <code>globalAlpha</code> property is set at <code>0.2</code> which will be used for all shapes from that point on. Every step in the <code>for</code> 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.</p> - -<pre class="brush: js;highlight[15]">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(); - } -}</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_globalAlpha_example", "180", "180", "https://mdn.mozillademos.org/files/232/Canvas_globalalpha.png")}}</p> - -<h3 id="An_example_using_rgba" name="An_example_using_rgba()">An example using <code>rgba()</code></h3> - -<p>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 <code>rgba()</code> gives you a little more control and flexibility because we can set the fill and stroke style individually.</p> - -<pre class="brush: js;highlight[16]">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); - } - } -}</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("An_example_using_rgba()", "180", "180", "https://mdn.mozillademos.org/files/246/Canvas_rgba.png")}}</p> - -<h2 id="Line_styles" name="Line_styles">Line styles</h2> - -<p>There are several properties which allow us to style lines.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.lineWidth", "lineWidth = value")}}</dt> - <dd>Sets the width of lines drawn in the future.</dd> - <dt>{{domxref("CanvasRenderingContext2D.lineCap", "lineCap = type")}}</dt> - <dd>Sets the appearance of the ends of lines.</dd> - <dt>{{domxref("CanvasRenderingContext2D.lineJoin", "lineJoin = type")}}</dt> - <dd>Sets the appearance of the "corners" where lines meet.</dd> - <dt>{{domxref("CanvasRenderingContext2D.miterLimit", "miterLimit = value")}}</dt> - <dd>Establishes a limit on the miter when two lines join at a sharp angle, to let you control how thick the junction becomes.</dd> - <dt>{{domxref("CanvasRenderingContext2D.getLineDash", "getLineDash()")}}</dt> - <dd>Returns the current line dash pattern array containing an even number of non-negative numbers.</dd> - <dt>{{domxref("CanvasRenderingContext2D.setLineDash", "setLineDash(segments)")}}</dt> - <dd>Sets the current line dash pattern.</dd> - <dt>{{domxref("CanvasRenderingContext2D.lineDashOffset", "lineDashOffset = value")}}</dt> - <dd>Specifies where to start a dash array on a line.</dd> -</dl> - -<p>You'll get a better understanding of what these do by looking at the examples below.</p> - -<h3 id="A_lineWidth_example" name="A_lineWidth_example">A <code>lineWidth</code> example</h3> - -<p>This property sets the current line thickness. Values must be positive numbers. By default this value is set to 1.0 units.</p> - -<p>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.</p> - -<p>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.</p> - -<pre class="brush: js;highlight[4]">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(); - } -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_lineWidth_example", "180", "180", "https://mdn.mozillademos.org/files/239/Canvas_linewidth.png")}}</p> - -<p>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.</p> - -<p><img alt="" class="internal" src="https://mdn.mozillademos.org/files/201/Canvas-grid.png"></p> - -<p>If you consider a path from (3,1) to (3,5) with a line thickness of <code>1.0</code>, 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 <code>1.0</code> width line in the previous example code.</p> - -<p>To fix this, you have to be very precise in your path creation. Knowing that a <code>1.0</code> 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 <code>1.0</code> line width ends up completely and precisely filling a single pixel vertical line.</p> - -<div class="note"> -<p><strong>Note:</strong> 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 <code>lineCap</code> style whose default value is <code>butt</code>; you may want to compute consistent strokes with half-pixel coordinates for odd-width lines, by setting the <code>lineCap</code> style to <code>square</code>, so that the outer border of the stroke around the endpoint will be automatically extended to cover the whole pixel exactly).</p> - -<p>Note also that only start and final endpoints of a path are affected: if a path is closed with <code>closePath()</code>, 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 <code>lineJoin</code> style, whose default value is <code>miter</code>, 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.</p> -</div> - -<p>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.</p> - -<p>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.</p> - -<h3 id="A_lineCap_example" name="A_lineCap_example">A <code>lineCap</code> example</h3> - -<p>The <code>lineCap</code> property determines how the end points of every line are drawn. There are three possible values for this property and those are: <code>butt</code>, <code>round</code> and <code>square</code>. By default this property is set to <code>butt</code>.</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/236/Canvas_linecap.png" style="float: right; height: 190px; width: 190px;"></p> - -<dl> - <dt><code>butt</code></dt> - <dd>The ends of lines are squared off at the endpoints.</dd> - <dt><code>round</code></dt> - <dd>The ends of lines are rounded.</dd> - <dt><code>square</code></dt> - <dd>The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness.</dd> -</dl> - -<p>In this example, we'll draw three lines, each with a different value for the <code>lineCap</code> 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.</p> - -<p>The line on the left uses the default <code>butt</code> option. You'll notice that it's drawn completely flush with the guides. The second is set to use the <code>round</code> 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 <code>square</code> option. This adds a box with an equal width and half the height of the line thickness.</p> - -<pre class="brush: js;highlight[18]">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(); - } -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_lineCap_example", "180", "180", "https://mdn.mozillademos.org/files/236/Canvas_linecap.png")}}</p> - -<h3 id="A_lineJoin_example" name="A_lineJoin_example">A <code>lineJoin</code> example</h3> - -<p>The <code>lineJoin</code> 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).</p> - -<p>There are three possible values for this property: <code>round</code>, <code>bevel</code> and <code>miter</code>. By default this property is set to <code>miter</code>. Note that the <code>lineJoin</code> setting has no effect if the two connected segments have the same direction, because no joining area will be added in this case.</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/237/Canvas_linejoin.png" style="float: right; height: 190px; width: 190px;"></p> - -<dl> - <dt><code>round</code></dt> - <dd>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.</dd> - <dt><code>bevel</code></dt> - <dd>Fills an additional triangular area between the common endpoint of connected segments, and the separate outside rectangular corners of each segment.</dd> - <dt><code>miter</code></dt> - <dd>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 <code>miterLimit</code> property which is explained below.</dd> -</dl> - -<p>The example below draws three different paths, demonstrating each of these three <code>lineJoin</code> property settings; the output is shown above.</p> - -<pre class="brush: js;highlight[6]">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(); - } -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_lineJoin_example", "180", "180", "https://mdn.mozillademos.org/files/237/Canvas_linejoin.png")}}</p> - -<h3 id="A_demo_of_the_miterLimit_property" name="A_demo_of_the_miterLimit_property">A demo of the <code>miterLimit</code> property</h3> - -<p>As you've seen in the previous example, when joining two lines with the <code>miter</code> 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.</p> - -<p>The <code>miterLimit</code> 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 <code>miterLimit</code> property (whose default value is 10.0 in the HTML {{HTMLElement("canvas")}}), so the <code>miterLimit</code> 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.</p> - -<p>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:</p> - -<ul> - <li><code>miterLimit</code> = <strong>max</strong> <code>miterLength</code> / <code>lineWidth</code> = 1 / <strong>sin</strong> ( <strong>min</strong> <em>θ</em> / 2 )</li> - <li>The default miter limit of 10.0 will strip all miters for sharp angles below about 11 degrees.</li> - <li>A miter limit equal to √2 ≈ 1.4142136 (rounded up) will strip miters for all acute angles, keeping miter joins only for obtuse or right angles.</li> - <li>A miter limit equal to 1.0 is valid but will disable all miters.</li> - <li>Values below 1.0 are invalid for the miter limit.</li> -</ul> - -<p>Here's a little demo in which you can set <code>miterLimit</code> 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.</p> - -<p>If you specify a <code>miterLimit</code> 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 <code>miterLimit</code> 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).</p> - -<pre class="brush: js;highlight[18]">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; -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><table> - <tr> - <td><canvas id="canvas" width="150" height="150"></canvas></td> - <td>Change the <code>miterLimit</code> by entering a new value below and clicking the redraw button.<br><br> - <form onsubmit="return draw();"> - <label>Miter limit</label> - <input type="number" size="3" id="miterLimit"/> - <input type="submit" value="Redraw"/> - </form> - </td> - </tr> -</table></pre> - -<pre class="brush: js">document.getElementById('miterLimit').value = document.getElementById('canvas').getContext('2d').miterLimit; -draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_demo_of_the_miterLimit_property", "400", "180", "https://mdn.mozillademos.org/files/240/Canvas_miterlimit.png")}}</p> - -<h3 id="Using_line_dashes">Using line dashes</h3> - -<p>The <code>setLineDash</code> method and the <code>lineDashOffset</code> property specify the dash pattern for lines. The <code>setLineDash</code> method accepts a list of numbers that specifies distances to alternately draw a line and a gap and the <code>lineDashOffset</code> property sets an offset where to start the pattern.</p> - -<p>In this example we are creating a marching ants effect. It is an animation technique often found in <span class="new">selection</span> 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 <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations">basic animations</a>.</p> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="110" height="110"></canvas></pre> -</div> - -<pre class="brush: js;highlight[6]">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();</pre> - -<p>{{EmbedLiveSample("Using_line_dashes", "120", "120", "https://mdn.mozillademos.org/files/9853/marching-ants.png")}}</p> - -<h2 id="Gradients" name="Gradients">Gradients</h2> - -<p>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 <code>fillStyle</code> or <code>strokeStyle</code> properties.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.createLinearGradient", "createLinearGradient(x1, y1, x2, y2)")}}</dt> - <dd>Creates a linear gradient object with a starting point of (<code>x1</code>, <code>y1</code>) and an end point of (<code>x2</code>, <code>y2</code>).</dd> - <dt>{{domxref("CanvasRenderingContext2D.createRadialGradient", "createRadialGradient(x1, y1, r1, x2, y2, r2)")}}</dt> - <dd>Creates a radial gradient. The parameters represent two circles, one with its center at (<code>x1</code>, <code>y1</code>) and a radius of <code>r1</code>, and the other with its center at (<code>x2</code>, <code>y2</code>) with a radius of <code>r2</code>.</dd> -</dl> - -<p>For example:</p> - -<pre class="brush: js">var lineargradient = ctx.createLinearGradient(0, 0, 150, 150); -var radialgradient = ctx.createRadialGradient(75, 75, 0, 75, 75, 100); -</pre> - -<p>Once we've created a <code>CanvasGradient</code> object we can assign colors to it by using the <code>addColorStop()</code> method.</p> - -<dl> - <dt>{{domxref("CanvasGradient.addColorStop", "gradient.addColorStop(position, color)")}}</dt> - <dd>Creates a new color stop on the <code>gradient</code> object. The <code>position</code> is a number between 0.0 and 1.0 and defines the relative position of the color in the gradient, and the <code>color</code> argument must be a string representing a CSS {{cssxref("<color>")}}, indicating the color the gradient should reach at that offset into the transition.</dd> -</dl> - -<p>You can add as many color stops to a gradient as you need. Below is a very simple linear gradient from white to black.</p> - -<pre class="brush: js">var lineargradient = ctx.createLinearGradient(0, 0, 150, 150); -lineargradient.addColorStop(0, 'white'); -lineargradient.addColorStop(1, 'black'); -</pre> - -<h3 id="A_createLinearGradient_example" name="A_createLinearGradient_example">A <code>createLinearGradient</code> example</h3> - -<p>In this example, we'll create two different gradients. As you can see here, both the <code>strokeStyle</code> and <code>fillStyle</code> properties can accept a <code>canvasGradient</code> object as valid input.</p> - -<pre class="brush: js;highlight[5,11]">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); - -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>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.</p> - -<p>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.</p> - -<p>{{EmbedLiveSample("A_createLinearGradient_example", "180", "180", "https://mdn.mozillademos.org/files/235/Canvas_lineargradient.png")}}</p> - -<h3 id="A_createRadialGradient_example" name="A_createRadialGradient_example">A <code>createRadialGradient</code> example</h3> - -<p>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).</p> - -<pre class="brush: js;highlight[5,10,15,20]">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); -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>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.</p> - -<p>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 <code>#019F62 = rgba(1,159,98,1)</code>.</p> - -<p>{{EmbedLiveSample("A_createRadialGradient_example", "180", "180", "https://mdn.mozillademos.org/files/244/Canvas_radialgradient.png")}}</p> - -<h2 id="Patterns" name="Patterns">Patterns</h2> - -<p>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 <code>createPattern()</code> method.</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.createPattern", "createPattern(image, type)")}}</dt> - <dd>Creates and returns a new canvas pattern object. <code>image</code> is a {{domxref("CanvasImageSource")}} (that is, an {{domxref("HTMLImageElement")}}, another canvas, a {{HTMLElement("video")}} element, or the like. <code>type</code> is a string indicating how to use the image.</dd> -</dl> - -<p>The type specifies how to use the image in order to create the pattern, and must be one of the following string values:</p> - -<dl> - <dt><code>repeat</code></dt> - <dd>Tiles the image in both vertical and horizontal directions.</dd> - <dt><code>repeat-x</code></dt> - <dd>Tiles the image horizontally but not vertically.</dd> - <dt><code>repeat-y</code></dt> - <dd>Tiles the image vertically but not horizontally.</dd> - <dt><code>no-repeat</code></dt> - <dd>Doesn't tile the image. It's used only once.</dd> -</dl> - -<p>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 <code>fillStyle</code> or <code>strokeStyle</code> properties. For example:</p> - -<pre class="brush: js">var img = new Image(); -img.src = 'someimage.png'; -var ptrn = ctx.createPattern(img, 'repeat'); -</pre> - -<div class="note"> -<p><strong>Note:</strong> Like with the <code>drawImage()</code> method, you must make sure the image you use is loaded before calling this method or the pattern may be drawn incorrectly.</p> -</div> - -<h3 id="A_createPattern_example" name="A_createPattern_example">A <code>createPattern</code> example</h3> - -<p>In this last example, we'll create a pattern to assign to the <code>fillStyle</code> property. The only thing worth noting is the use of the image's <code>onload</code> handler. This is to make sure the image is loaded before it is assigned to the pattern.</p> - -<pre class="brush: js;highlight[10]">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); - - } -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="150"></canvas></pre> - -<pre class="brush: js">draw();</pre> - -<p>The result looks like this:</p> -</div> - -<p>{{EmbedLiveSample("A_createPattern_example", "180", "180", "https://mdn.mozillademos.org/files/222/Canvas_createpattern.png")}}</p> - -<h2 id="Shadows">Shadows</h2> - -<p>Using shadows involves just four properties:</p> - -<dl> - <dt>{{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX = float")}}</dt> - <dd>Indicates the horizontal distance the shadow should extend from the object. This value isn't affected by the transformation matrix. The default is 0.</dd> - <dt>{{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY = float")}}</dt> - <dd>Indicates the vertical distance the shadow should extend from the object. This value isn't affected by the transformation matrix. The default is 0.</dd> - <dt>{{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur = float")}}</dt> - <dd>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.</dd> - <dt>{{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor = color")}}</dt> - <dd>A standard CSS color value indicating the color of the shadow effect; by default, it is fully-transparent black.</dd> -</dl> - -<p>The properties <code>shadowOffsetX</code> and <code>shadowOffsetY</code> 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.</p> - -<p>The <code>shadowBlur</code> 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.</p> - -<p>The <code>shadowColor</code> property is a standard CSS color value indicating the color of the shadow effect; by default, it is fully-transparent black.</p> - -<div class="note"> -<p><strong>Note:</strong> Shadows are only drawn for <code>source-over</code> <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing" title="Web/Guide/HTML/Canvas_tutorial/Compositing">compositing operations</a>.</p> -</div> - -<h3 id="A_shadowed_text_example">A shadowed text example</h3> - -<p>This example draws a text string with a shadowing effect.</p> - -<pre class="brush: js;highlight[4,5,6,7]">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); -} -</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="150" height="80"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("A_shadowed_text_example", "180", "100", "https://mdn.mozillademos.org/files/2505/shadowed-string.png")}}</p> - -<p>We will look at the <code>font</code> property and <code>fillText</code> method in the next chapter about <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text">drawing text</a>.</p> - -<h2 id="Canvas_fill_rules">Canvas fill rules</h2> - -<p>When using <code>fill</code> (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.<br> - <br> - Two values are possible:</p> - -<ul> - <li><code><strong>"nonzero</strong></code>": The <a class="external external-icon" href="http://en.wikipedia.org/wiki/Nonzero-rule">non-zero winding rule</a>, which is the default rule.</li> - <li><code><strong>"evenodd"</strong></code>: The <a class="external external-icon" href="http://en.wikipedia.org/wiki/Even%E2%80%93odd_rule">even-odd winding rule</a>.</li> -</ul> - -<p>In this example we are using the <code>evenodd</code> rule.</p> - -<pre class="brush: js;highlight[6]">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'); -}</pre> - -<div class="hidden"> -<pre class="brush: html"><canvas id="canvas" width="100" height="100"></canvas></pre> - -<pre class="brush: js">draw();</pre> -</div> - -<p>{{EmbedLiveSample("Canvas_fill_rules", "110", "110", "https://mdn.mozillademos.org/files/9855/fill-rule.png")}}</p> - -<p>{{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_shapes", "Web/API/Canvas_API/Tutorial/Drawing_text")}}</p> 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 ---- -<div>{{apiref()}}</div> - -<p><span class="seoSummary">The Constraint Validation API enables checking values that users have entered into form controls, before submitting the values to the server.</span></p> - -<h2 id="Concepts_and_usage">Concepts and usage</h2> - -<p>Certain HTML form controls, such as {{HTMLElement("input")}}, {{HTMLElement("select")}} and {{HTMLElement("textarea")}}, can restrict the format of allowable values, using attributes like <code>required</code> and <code>pattern</code> to set basic constraints.</p> - -<p>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.</p> - -<div class="note"> -<p><strong>Note:</strong> 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.</p> -</div> - -<p>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.</p> - -<h2 id="Constraint_validation_interfaces">Constraint validation interfaces</h2> - -<dl> - <dt><a href="/en-US/docs/Web/API/ValidityState">ValidityState</a></dt> - <dd>The ValidityState interface represents the <em>validity states</em> 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.</dd> - <dt><a href="/en-US/docs/Web/Events/invalid">invalid</a> event</dt> - <dd>This event type is fired at a form control element if the element does not satisfy its constraints.</dd> -</dl> - -<h3 id="Extensions_to_other_interfaces">Extensions to other interfaces</h3> - -<p>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 <code>form</code> attribute that indicates their form owner):</p> - -<ul> - <li><code><strong><a href="/en-US/docs/Web/API/HTMLButtonElement">HTMLButtonElement</a></strong></code></li> - <li><code><strong><a href="/en-US/docs/Web/API/HTMLFieldsetElement">HTMLFieldsetElement</a></strong></code></li> - <li><code><strong><a href="/en-US/docs/Web/API/HTMLInputElement">HTMLInputElement</a></strong></code></li> - <li><code><strong><a href="/en-US/docs/Web/API/HTMLObjectElement">HTMLObjectElement</a></strong></code></li> - <li><code><strong><a href="/en-US/docs/Web/API/HTMLOutputElement">HTMLOutputElement</a></strong></code></li> - <li><code><strong><a href="/en-US/docs/Web/API/HTMLSelectElement">HTMLSelectElement</a></strong></code></li> - <li><code><strong><a href="/en-US/docs/Web/API/HTMLTextAreaElement">HTMLTextAreaElement</a></strong></code></li> -</ul> - -<h4 id="Properties">Properties</h4> - -<dl> - <dt><code>validity</code></dt> - <dd>A read-only properity that returns a <code><a href="/en-US/docs/Web/API/ValidityState">ValidityState</a></code> object, whose properties represent validation errors for the value of that element.</dd> - <dt><code>validationMessage</code></dt> - <dd>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 <code>setCustomValidity()</code>, this will be shown.</dd> - <dt><code>willValidate</code></dt> - <dd>A read-only boolean property that returns <code>true</code> if the element is a candidate for constraint validation; and <code>false</code> otherwise. Elements with the <code>HTMLObjectElement</code> interface are <em>never</em> candidates for constraint validation. Others may be barred from constraint validation depending on specific conditions.</dd> -</dl> - -<h4 id="Methods">Methods</h4> - -<dl> - <dt><code>checkValidity()</code></dt> - <dd>Checks the element's value against its constraints. If the value is invalid, it fires an <a href="/en-US/docs/Web/Events/invalid">invalid</a> event at the element and returns <code>false</code>; otherwise it returns <code>true</code>.</dd> - <dt><code>reportValidity()</code></dt> - <dd>Checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an <a href="/en-US/docs/Web/Events/invalid">invalid</a> event at the element, returns <code>false</code>, and then reports the validity status to the user in whatever way the user agent has available. Otherwise, it returns <code>true</code>.</dd> - <dt><code>setCustomValidity(<em>message</em>)</code></dt> - <dd>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.</dd> -</dl> - -<h2 id="Examples">Examples</h2> - -<p>Take the following form:</p> - -<pre class="brush: html"><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></pre> - -<p>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 <code>pattern</code>.</p> - -<p>If you wanted to instead display custom error messages, you could use JavaScript like the following:</p> - -<pre class="brush: js">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!'); - } -});</pre> - -<p>The example renders like so:</p> - -<p>{{EmbedLiveSample('Examples')}}</p> - -<p>In brief:</p> - -<ul> - <li>We check the valid state of the input element every time its value is changed by running the <code>checkValidity()</code> method via the <code>input</code> event handler.</li> - <li>If the value is invalid, an <code>invalid</code> event is raised, and the <code>invalid</code> event handler function is run. Inside this function we work out whether the value is invalid because it is empty, or because it doesn't match the pattern, using an <code>if()</code> block, and set a custom validity error message.</li> - <li>As a result, if the input value is invalid when the submit button is pressed, one of the custom error messages will be shown.</li> - <li>If it is valid, it will submit as you'd expect. For this to happen, the custom validity has to be cancelled, by invoking <code>setCustomValidity()</code> with an empty string value. We therefore do this every time the <code>input</code> event is raised. If you don't do this, and a custom validity was previously set, the input will register as invalid, even if it current contains a valid value on submission.</li> -</ul> - -<div class="blockIndicator note"> -<p><strong>Note</strong>: Firefox supported a proprietary error attribute — <code>x-moz-errormessage</code> — for many versions, which allowed you set custom error messages in a similar way. This has been removed as of version 66 (see <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1513890">bug 1513890</a>).</p> -</div> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{ SpecName('HTML WHATWG', 'forms.html#the-constraint-validation-api', 'constraint validation API') }}</td> - <td>{{Spec2('HTML WHATWG')}}</td> - <td> </td> - </tr> - <tr> - <td>{{ SpecName('HTML5.1', 'sec-forms.html#the-constraint-validation-api', 'constraint validation API') }}</td> - <td>{{Spec2('HTML5.1')}}</td> - <td>No change from the previous snapshot {{SpecName('HTML5 W3C')}}.</td> - </tr> - <tr> - <td>{{ SpecName('HTML5 W3C', 'forms.html#the-constraint-validation-api', 'constraint validation API') }}</td> - <td>{{Spec2('HTML5 W3C')}}</td> - <td>First snapshot of {{SpecName('HTML WHATWG')}} containing this interface.</td> - </tr> - </tbody> -</table> - -<h2 id="See_also">See also</h2> - -<ul> - <li><code><a href="/en-US/docs/Web/HTML/Element/input"><input></a></code></li> - <li><code><a href="/en-US/docs/Web/HTML/Element/select"><select></a></code></li> - <li><code><a href="/en-US/docs/Web/HTML/Element/textarea"><textarea></a></code></li> -</ul> 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 ---- -<div> - {{APIRef}}</div> -<div> - </div> -<p><span style="font-size: 1.71428571428571rem; letter-spacing: -0.5px; line-height: 24px;">Summary</span></p> -<p><strong><font><font>parentStyleSheet</font></font></strong><font><font> returns the object type of style sheet, in which the rule is defined.</font></font></p> -<h3 id="Syntax" name="Syntax"><font><font>Syntax</font></font></h3> -<pre class="eval"><em><font><font>stylesheet</font></font></em> = cssRule.parentStyleSheet -</pre> -<h3 id="Parameters" name="Parameters"><font><font>Parameters</font></font></h3> -<ul> - <li><code><font><font>stylesheet</font></font></code><font><font> stylesheet is an object type.</font></font></li> -</ul> -<h3 id="Example" name="Example"><font><font>Instance</font></font></h3> -<pre class="eval">if (bgRule.parentStyleSheet! = MySheet) { - // Style alien rule! -} -</pre> -<h3 id="Notes" name="Notes"><font><font>Letters</font></font></h3> -<p><font><font>See </font></font><a href="/es/DOM/event#DOM_styleSheet_Object" title="en / DOM / event # DOM_styleSheet_Object"><font><font>Gecko DOM Reference: event # DOM_styleSheet_Object</font></font></a><font><font> for more information about the interface type objects stylesheet.</font></font></p> -<h3 id="Specification" name="Specification"><font><font>Specification</font></font></h3> -<p><font><font>DOM Level 2 Style - cssRule</font></font></p> 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 ---- -<div>{{APIRef("HTML DOM")}}</div> - -<p>{{ gecko_minversion_header("1.9") }} El objeto <code>DataTransfer</code> 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 <a class="internal" href="/En/DragDrop/Drag_and_Drop" title="En/DragDrop/Drag and Drop">Drag and Drop</a>.</p> - -<p>Este objeto esta disponible desde la propiedad <code>dataTransfer</code> de todos los eventos de drag . No pueden ser creados por separado.</p> - -<h2 id="Properties" name="Properties">Lista de propiedades</h2> - -<table class="standard-table"> - <tbody> - <tr> - <td class="header">Properties</td> - <td class="header">Type</td> - </tr> - <tr> - <td><code><a href="#dropEffect.28.29" title="En/DragDrop/DataTransfer#dropEffect">dropEffect</a></code></td> - <td><code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String" title="en/String">String</a></code></td> - </tr> - <tr> - <td><code><a href="#effectAllowed.28.29" title="En/DragDrop/DataTransfer#effectAllowed">effectAllowed</a></code></td> - <td><code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String" title="en/String">String</a></code></td> - </tr> - <tr> - <td><a href="#files.28.29" title="En/DragDrop/DataTransfer#files"><code>files</code></a> {{ gecko_minversion_inline("1.9.2") }}</td> - <td>{{ domxref("FileList") }}</td> - </tr> - <tr> - <td><code><a href="#mozCursor" title="En/DragDrop/DataTransfer#mozCursor">mozCursor</a></code> {{ non-standard_inline() }} {{ gecko_minversion_inline("1.9.1") }}</td> - <td><code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String" title="en/String">String</a></code></td> - </tr> - <tr> - <td><code><a href="#mozItemCount.28.29" title="En/DragDrop/DataTransfer#mozItemCount">mozItemCount</a></code> {{ non-standard_inline() }}</td> - <td><code>unsigned long</code></td> - </tr> - <tr> - <td><a href="#mozSourceNode" title="En/DragDrop/DataTransfer#mozSourceNode"><code>mozSourceNode</code></a> {{ non-standard_inline() }} {{ gecko_minversion_inline("2") }}</td> - <td>{{ domxref("Node") }}</td> - </tr> - <tr> - <td><a href="#mozUserCancelled" title="En/DragDrop/DataTransfer#mozUserCancelled"><code>mozUserCancelled</code></a></td> - <td><a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/Core JavaScript 1.5 Reference/Global Objects/Boolean"><code>Boolean</code></a></td> - </tr> - <tr> - <td><code><a href="#types.28.29" title="En/DragDrop/DataTransfer#types">types</a></code></td> - <td><code><a href="/en-US/docs/Web/API/DOMStringList" title="en-US/docs/Web/API/DOMStringList">DOMStringList</a></code></td> - </tr> - </tbody> -</table> - -<h2 id="Method_overview" name="Method_overview">Lista de métodos</h2> - -<table class="standard-table"> - <tbody> - <tr> - <td><code>void <a href="#addElement.28.29">addElement</a>(in <a href="/en/XPCOM_Interface_Reference/nsIDOMElement" title="en/nsIDOMElement">Element</a> element)</code></td> - </tr> - <tr> - <td><code>void <a href="#clearData.28.29">clearData</a>([in <a href="/en/String" title="en/String">String</a> type])</code></td> - </tr> - <tr> - <td><code><a href="/en/String" title="en/String">String</a> <a href="#getData.28.29">getData</a>(in <a href="/en/String" title="en/String">String</a> type)</code></td> - </tr> - <tr> - <td><code>void <a href="#setData.28.29">setData</a>(in <a href="/en/String" title="en/String">String</a> type, in <a href="/en/String" title="en/String">String</a> data)</code></td> - </tr> - <tr> - <td><code>void <a href="#setDragImage.28.29">setDragImage</a>(in <a href="/en/XPCOM_Interface_Reference/nsIDOMElement" title="en/nsIDOMElement">nsIDOMElement</a> image, in long x, in long y)</code></td> - </tr> - <tr> - <td><code>void <a href="#mozClearDataAt.28.29">mozClearDataAt</a>([in <a href="/en/String" title="en/String">String</a> type, in unsigned long index])</code></td> - </tr> - <tr> - <td><code><a href="/en/XPCOM_Interface_Reference/NsIVariant" title="en/nsIVariant">nsIVariant</a> <a href="#mozGetDataAt.28.29">mozGetDataAt</a>(in <a href="/en/String" title="en/String">String</a> type, in unsigned long index)</code></td> - </tr> - <tr> - <td><code>void <a href="#mozSetDataAt.28.29">mozSetDataAt</a>(in <a href="/en/String" title="en/String">String</a> type, in <a href="/en/XPCOM_Interface_Reference/NsIVariant" title="en/nsIVariant">nsIVariant</a> data, in unsigned long index)</code></td> - </tr> - <tr> - <td><code><a href="/en/StringList" title="en/StringList">StringList</a> <a href="#mozTypesAt.28.29">mozTypesAt</a>([in unsigned long index])</code></td> - </tr> - </tbody> -</table> - -<h2 id="Properties" name="Properties">Propiedades</h2> - -<h3 id="dropEffect.28.29" name="dropEffect.28.29">dropEffect</h3> - -<p>The actual effect that will be used, and should always be one of the possible values of <code>effectAllowed</code>.</p> - -<p>For the <code>dragenter</code> and <code>dragover</code> events, the <code>dropEffect</code> 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 <code>dragenter</code> and <code>dragover</code> events, the <code>dropEffect</code> should be modified if the action the user is requesting is not the one that is desired.</p> - -<p>For <code>dragstart</code>, <code>drag</code>, and <code>dragleave</code> events, the <code>dropEffect</code> is initialized to "none". Any value assigned to the <code>dropEffect</code> will be set, but the value isn't used for anything.</p> - -<p>For the <code>drop</code> and <code>dragend</code> events, the <code>dropEffect</code> will be initialized to the action that was desired, which will be the value that the <code>dropEffect</code> had after the last <code>dragenter</code> or <code>dragover</code> event.</p> - -<p>Possible values:</p> - -<ul> - <li><strong>copy</strong>: A copy of the source item is made at the new location.</li> - <li><strong>move</strong>: An item is moved to a new location.</li> - <li><strong>link</strong>: A link is established to the source at the new location.</li> - <li><strong>none</strong>: The item may not be dropped.</li> -</ul> - -<p>Assigning any other value has no effect and retains the old value.</p> - -<h3 id="effectAllowed.28.29" name="effectAllowed.28.29">effectAllowed</h3> - -<p>Specifies the effects that are allowed for this drag. You may set this in the <code>dragstart</code> event to set the desired effects for the source, and within the <code>dragenter</code> and <code>dragover</code> events to set the desired effects for the target. The value is not used for other events.</p> - -<p>Possible values:</p> - -<ul> - <li><strong>copy</strong>: A copy of the source item may be made at the new location.</li> - <li><strong>move</strong>: An item may be moved to a new location.</li> - <li><strong>link</strong>: A link may be established to the source at the new location.</li> - <li><strong>copyLink</strong>: A copy or link operation is permitted.</li> - <li><strong>copyMove</strong>: A copy or move operation is permitted.</li> - <li><strong>linkMove</strong>: A link or move operation is permitted.</li> - <li><strong>all</strong>: All operations are permitted.</li> - <li><strong>none</strong>: the item may not be dropped.</li> - <li><strong>uninitialized</strong>: the default value when the effect has not been set, equivalent to all.</li> -</ul> - -<p>Assigning any other value has no effect and retains the old value.</p> - -<h3 id="files.28.29" name="files.28.29">files</h3> - -<p>{{ gecko_minversion_header("1.9.2") }}</p> - -<p>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 <code>null</code>.</p> - -<h4 id="Example">Example</h4> - -<p>This example dumps the list of files dragged into the browser window: <a class="external" href="http://jsfiddle.net/9C2EF/" title="http://jsfiddle.net/9C2EF/">http://jsfiddle.net/9C2EF/</a></p> - -<h3 id="types.28.29" name="types.28.29">types</h3> - -<p>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.</p> - -<p>{{ h3_gecko_minversion("mozCursor", "1.9.1", "mozCursor") }}</p> - -<p>The drag cursor's state. This is primarily used to control the cursor during tab drags.</p> - -<div class="note"><strong>Note:</strong> This method is currently only implemented on Windows.</div> - -<h4 id="Possible_values">Possible values</h4> - -<dl> - <dt><code>auto</code></dt> - <dd>Uses the default system behavior.</dd> - <dt><code>default</code></dt> - <dd>Uses the default Gecko behavior, which is to set the cursor to an arrow during the drag operation.</dd> -</dl> - -<div class="note"><strong>Note:</strong> If you specify any value other than "default", "auto" is assumed.</div> - -<h3 id="mozItemCount.28.29" name="mozItemCount.28.29">mozItemCount</h3> - -<p>The number of items being dragged.</p> - -<div class="note"><strong>Note:</strong> This property is Gecko-specific.</div> - -<h3 id="mozSourceNode">mozSourceNode</h3> - -<p>{{ gecko_minversion_header("2") }}</p> - -<p>The {{ domxref("Node") }} over which the mouse cursor was located when the button was pressed to initiate the drag operation. This value is <code>null</code> for external drags or if the caller can't access the node.</p> - -<div class="note"><strong>Note:</strong> This property is Gecko-specific.</div> - -<h3 id="mozItemCount.28.29" name="mozItemCount.28.29">mozUserCancelled</h3> - -<p>This property applies only to the <code>dragend</code> event, and is <code>true</code> if the user canceled the drag operation by pressing escape. It will be <code>false</code> 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.</p> - -<div class="note"><strong>Note:</strong> This property is Gecko-specific.</div> - -<h2 id="Methods" name="Methods">Métodos</h2> - -<h3 id="addElement.28.29" name="addElement.28.29">addElement()</h3> - -<p>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.</p> - -<pre class="eval"> void addElement( - in Element element - ); -</pre> - -<h6 id="Parameters_addElement" name="Parameters_addElement">Parameters</h6> - -<dl> - <dt><code>element </code></dt> - <dd>The element to add.</dd> -</dl> - -<h3 id="clearData.28.29" name="clearData.28.29">clearData()</h3> - -<p>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.</p> - -<pre class="eval"> void clearData( - [optional] in String type - ); -</pre> - -<h6 id="Parameters_clearData" name="Parameters_clearData">Parameters</h6> - -<dl> - <dt><code>type </code></dt> - <dd>The type of data to remove.</dd> -</dl> - -<h3 id="getData.28.29" name="getData.28.29">getData()</h3> - -<p>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.</p> - -<p>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.</p> - -<pre class="eval"> String getData( - in String type - ); -</pre> - -<h6 id="Parameters_getData" name="Parameters_getData">Parameters</h6> - -<dl> - <dt><code>type </code></dt> - <dd>The type of data to retrieve.</dd> -</dl> - -<h3 id="setData.28.29" name="setData.28.29">setData()</h3> - -<p>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.</p> - -<pre class="eval"> void setData( - in String type, - in String data - ); -</pre> - -<h6 id="Parameters_setData" name="Parameters_setData">Parameters</h6> - -<dl> - <dt><code>type </code></dt> - <dd>The type of data to add.</dd> - <dt><code>data </code></dt> - <dd>The data to add.</dd> -</dl> - -<h3 id="setDragImage.28.29" name="setDragImage.28.29">setDragImage()</h3> - -<p>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.</p> - -<p>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.</p> - -<p>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.</p> - -<pre class="eval"> void setDragImage( - in Element image, - in long x, - in long y - ); -</pre> - -<h6 id="Parameters_setDragImage" name="Parameters_setDragImage">Parameters</h6> - -<dl> - <dt><code>image </code></dt> - <dd>An element to use as the drag feedback image</dd> - <dt><code>x </code></dt> - <dd>Horizontal offset within the image.</dd> - <dt><code>y </code></dt> - <dd>Vertical offset within the image.</dd> -</dl> - -<h3 id="mozClearDataAt.28.29" name="mozClearDataAt.28.29">mozClearDataAt()</h3> - -<p>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.</p> - -<p>If the last format for the item is removed, the entire item is removed, reducing <code>mozItemCount</code> by one.</p> - -<p>If the <code>format</code> list is empty, then the data associated with all formats is removed. If the format is not found, then this method has no effect.</p> - -<div class="note"><strong>Note:</strong> This method is Gecko-specific.</div> - -<pre class="eval"> void mozClearDataAt( - [optional] in String type, - in unsigned long index - ); -</pre> - -<h6 id="Parameters_mozClearDataAt" name="Parameters_mozClearDataAt">Parameters</h6> - -<dl> - <dt><code>type </code></dt> - <dd>The type of data to remove.</dd> - <dt><code>index </code></dt> - <dd>The index of the data to remove.</dd> -</dl> - -<h3 id="mozGetDataAt.28.29" name="mozGetDataAt.28.29">mozGetDataAt()</h3> - -<p>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.</p> - -<div class="note"><strong>Note:</strong> This method is Gecko-specific.</div> - -<pre class="eval"> nsIVariant mozGetDataAt( - [optional] in String type, - in unsigned long index - ); -</pre> - -<h6 id="Parameters_mozClearDataAt" name="Parameters_mozClearDataAt">Parameters</h6> - -<dl> - <dt><code>type </code></dt> - <dd>The type of data to retrieve.</dd> - <dt><code>index </code></dt> - <dd>The index of the data to retrieve.</dd> -</dl> - -<h3 id="mozSetDataAt.28.29" name="mozSetDataAt.28.29">mozSetDataAt()</h3> - -<p>A data transfer may store multiple items, each at a given zero-based index. <code>mozSetDataAt()</code> may only be called with an index argument less than <code>mozItemCount</code> in which case an existing item is modified, or equal to <code>mozItemCount</code> in which case a new item is added, and the <code>mozItemCount</code> is incremented by one.</p> - -<p>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.</p> - -<p>The data should be either a string, a primitive boolean or number type (which will be converted into a string) or an {{ interface("nsISupports") }}.</p> - -<div class="note"><strong>Note:</strong> This method is Gecko-specific.</div> - -<pre class="eval"> void mozSetDataAt( - [optional] in String type, - in nsIVariant data, - in unsigned long index - ); -</pre> - -<h6 id="Parameters_mozSetDataAt" name="Parameters_mozSetDataAt">Parameters</h6> - -<dl> - <dt><code>type </code></dt> - <dd>The type of data to add.</dd> - <dt><code>data </code></dt> - <dd>The data to add.</dd> - <dt><code>index </code></dt> - <dd>The index of the data to add.</dd> -</dl> - -<h3 id="mozTypesAt.28.29" name="mozTypesAt.28.29">mozTypesAt()</h3> - -<p>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.</p> - -<div class="note"><strong>Note:</strong> This method is Gecko-specific.</div> - -<pre class="eval"> nsIVariant mozTypesAt( - in unsigned long index - ); -</pre> - -<h6 id="Parameters_mozTypesAt" name="Parameters_mozTypesAt">Parameters</h6> - -<dl> - <dt><code>index </code></dt> - <dd>The index of the data for which to retrieve the types.</dd> -</dl> - -<h2 id="See_also" name="See_also">Mira también</h2> - -<p><a class="internal" href="/En/DragDrop/Drag_and_Drop" title="Drag and Drop">Drag and Drop</a></p> - -<p>{{ languages( { "ja": "Ja/DragDrop/DataTransfer" } ) }}</p> 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 ---- -<div>{{ ApiRef("DOM") }}</div> - -<p>Retorna <code><a href="/en-US/docs/XPathResult" title="XPathResult">XPathResult</a></code> basado en una expresión <a href="/en-US/docs/XPath" title="XPath">XPath</a> y otros parametros dados .</p> - -<h2 id="Syntax" name="Syntax">Sintaxis</h2> - -<pre class="syntaxbox">var xpathResult = document.evaluate( - xpathExpression, - contextNode, - namespaceResolver, - resultType, - result -);</pre> - -<ul> - <li><code>XpathExpression es una cadena que representa el XPath que se va a evaluar.</code></li> - <li><code>contextNode</code> specifies the <em>context node</em> for the query (see the [<a class="external" href="http://www.w3.org/TR/xpath" rel="freelink">http://www.w3.org/TR/xpath</a> XPath specification). It's common to pass <code>document</code> as the context node.</li> - <li><code>namespaceResolver</code> is a function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document. <code>null</code> is common for HTML documents or when no namespace prefixes are used.</li> - <li><code>resultType</code> is an integer that corresponds to the type of result <code>XPathResult</code> to return. Use <a href="#Result_types">named constant properties</a>, such as <code>XPathResult.ANY_TYPE</code>, of the XPathResult constructor, which correspond to integers from 0 to 9.</li> - <li><code>result</code> is an existing <code>XPathResult</code> to use for the results. <code>null</code> is the most common and will create a new <code>XPathResult</code></li> -</ul> - -<h2 id="Example" name="Example">Ejemplo</h2> - -<pre class="brush: js">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 -</pre> - -<p>Note, in the above example, a more verbose XPath is preferred over common shortcuts such as <code>//h2</code>. 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 <em>every</em> node from the root and all subnodes looking for possible matches.</p> - -<p>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:</p> - -<pre class="brush: js">document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null); -</pre> - -<p>Notice in the above <code>document.body</code> has been used as the context instead of <code>document</code> so the XPath starts from the body element. (In this example, the <code>"."</code> is important to indicate that the querying should start from the context node, document.body. If the "." was left out (leaving <code>//h2</code>) the query would start from the root node (<code>html</code>) which would be more wasteful.)</p> - -<p>See <a href="/en-US/docs/Introduction_to_using_XPath_in_JavaScript" title="Introduction to using XPath in JavaScript">Introduction to using XPath in JavaScript</a> for more information.</p> - -<h2 id="Notes" name="Notes">Nota</h2> - -<ul> - <li>XPath expressions can be evaluated on HTML and XML documents.</li> - <li>While using document.evaluate() works in FF2, in FF3 one must use someXMLDoc.evaluate() if evaluating against something other than the current document.</li> -</ul> - -<h2 id="Result_types" name="Result_types">Tipos de resultados</h2> - -<p>(Merge with <a href="/Template:XPathResultConstants" title="Template:XPathResultConstants">Template:XPathResultConstants</a>?</p> - -<p>These are supported values for the <code>resultType</code> parameter of the <code>evaluate</code> method:</p> - -<table class="standard-table"> - <tbody> - <tr> - <td class="header">Result Type</td> - <td class="header">Value</td> - <td class="header">Description</td> - </tr> - <tr> - <td><code>ANY_TYPE</code></td> - <td>0</td> - <td>Whatever type naturally results from the given expression.</td> - </tr> - <tr> - <td><code>NUMBER_TYPE</code></td> - <td>1</td> - <td>A result set containing a single number. Useful, for example, in an XPath expression using the <code>count()</code> function.</td> - </tr> - <tr> - <td><code>STRING_TYPE</code></td> - <td>2</td> - <td>A result set containing a single string.</td> - </tr> - <tr> - <td><code>BOOLEAN_TYPE</code></td> - <td>3</td> - <td>A result set containing a single boolean value. Useful, for example, an an XPath expression using the <code>not()</code> function.</td> - </tr> - <tr> - <td><code>UNORDERED_NODE_ITERATOR_TYPE</code></td> - <td>4</td> - <td>A 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.</td> - </tr> - <tr> - <td><code>ORDERED_NODE_ITERATOR_TYPE</code></td> - <td>5</td> - <td>A 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.</td> - </tr> - <tr> - <td><code>UNORDERED_NODE_SNAPSHOT_TYPE</code></td> - <td>6</td> - <td>A 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.</td> - </tr> - <tr> - <td><code>ORDERED_NODE_SNAPSHOT_TYPE</code></td> - <td>7</td> - <td>A 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.</td> - </tr> - <tr> - <td><code>ANY_UNORDERED_NODE_TYPE</code></td> - <td>8</td> - <td>A 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.</td> - </tr> - <tr> - <td><code>FIRST_ORDERED_NODE_TYPE</code></td> - <td>9</td> - <td>A result set containing the first node in the document that matches the expression.</td> - </tr> - </tbody> -</table> - -<p>Results of <code>NODE_ITERATOR</code> 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.</p> - -<p>Results of <code>NODE_SNAPSHOT</code> 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.</p> - -<h2 id="Specifications" name="Specifications">Especificaciones</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName("DOM3 XPath", "xpath.html#XPathEvaluator-evaluate", "Document.evaluate")}}</td> - <td>{{Spec2("DOM3 XPath")}}</td> - <td>Initial specification</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidad del navegador</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Edge</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>XPath 1.0</td> - <td>{{CompatChrome(1.0)}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop(1.8)}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatOpera(9.0)}}</td> - <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Edge</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>XPath 1.0</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] Implemented in WebKit 5.0 (531) or earlier.</p> - -<h2 id="See_also" name="See_also">Ver también</h2> - -<ul> - <li><a href="/en-US/docs/DOM/document.createExpression" title="DOM/document.createExpression">DOM:document.createExpression</a></li> - <li><a href="/en-US/docs/Code_snippets/XPath" title="Code_snippets/XPath">XPath Code Snippets</a></li> - <li><a href="http://codepen.io/johan/full/ckFgn">Check for browser support</a></li> -</ul> 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 ---- -<div>{{APIRef("Shadow DOM")}}</div> - - - -<p>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.</p> - -<h2 id="Syntax" name="Syntax">Syntax</h2> - -<pre class="syntaxbox">var <em>shadowroot =</em><em> element</em>.shadowRoot; -</pre> - -<h3 id="Value">Value</h3> - -<p>A {{DOMxRef("ShadowRoot")}} object instance, or <code>null</code> if the associated shadow root was attached with its {{DOMxRef("ShadowRoot.mode", "mode")}} set to <code>closed</code>. (See {{DOMxRef("Element.attachShadow()")}} for further details).</p> - -<h2 id="Examples">Examples</h2> - -<p>The following snippets are taken from our <a href="https://github.com/mdn/web-components-examples/tree/master/life-cycle-callbacks">life-cycle-callbacks</a> example (<a href="https://mdn.github.io/web-components-examples/life-cycle-callbacks">see it live also</a>), which creates an element that displays a square of a size and color specified in the element's attributes.</p> - -<p>Inside the <code><custom-square></code> element's class definition we include some life cycle callbacks that make a call to an external function, <code>updateStyle()</code>, which actually applies the size and color to the element. You'll see that we are passing it <code>this</code> (the custom element itself) as a parameter.</p> - -<pre class="brush: js">connectedCallback() { - console.log('Custom square element added to page.'); - updateStyle(this); -} - -attributeChangedCallback(name, oldValue, newValue) { - console.log('Custom square element attributes changed.'); - updateStyle(this); -}</pre> - -<p>In the <code>updateStyle()</code> 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:</p> - -<pre class="brush: js">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')}; - } - `; - } - }); -}</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('DOM WHATWG', '#dom-element-shadowroot', 'shadowRoot')}}</td> - <td>{{Spec2('DOM WHATWG')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("api.Element.shadowRoot")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{DOMxRef("Element.openOrClosedShadowRoot")}} {{non-standard_inline}}</li> -</ul> 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 ---- -<div>{{APIRef("File API")}}</div> - -<p>Retorna el tipo de media (<a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">MIME</a>) del archivo representado por un objeto {{domxref("File")}}.</p> - -<h2 id="Sintaxis">Sintaxis</h2> - -<pre class="brush: js">var tipo = <var>file</var>.type;</pre> - -<h2 id="Valor">Valor</h2> - -<p>Una cadena (<em>string</em>), conteniendo el tipo de media (MIME) indicando el tipo del archivo, por ejemplo "image/png" para imágenes PNG.</p> - -<h2 id="Ejemplo">Ejemplo</h2> - -<pre class="brush: html"><input type="file" multiple onchange="mostrarTipo(this)"> -</pre> - -<pre class="brush: js">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); - } -}</pre> - -<p><strong>Note:</strong> 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 "<em>text/plain</em>" and not "<em>image/png</em>". Moreover, <code>file.type</code> 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. <strong>Developers are advised not to rely on this property as a sole validation scheme.</strong></p> - -<h2 id="Especificaciones">Especificaciones</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Especificación</th> - <th scope="col">Estado</th> - <th scope="col">Comentario</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('File API', '#dfn-type', 'type')}}</td> - <td>{{Spec2('File API')}}</td> - <td>Definición inicial.</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilidad_de_los_navegadores">Compatibilidad de los navegadores</h2> - - - -<p>{{Compat("api.File.type")}}</p> - -<h2 id="Ver_también">Ver también</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/File/Using_files_from_web_applications">Usando archivos desde aplicaciones web (Using files from web applications)</a></li> - <li>Blog Post: <a href="https://textslashplain.com/2018/07/26/be-skeptical-of-client-reported-mime-content-types/">Se excéptico de tipos MIME reportados por el cliente (Be skeptical of client-reported MIME types)</a></li> -</ul> 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 ---- -<div>{{ ApiRef("HTML DOM") }}</div> - -<p>The <strong><code>onloadedmetadata</code></strong> property of the {{domxref("GlobalEventHandlers")}} mixin is the {{event("Event_handlers", "event handler")}} for processing {{event("loadedmetadata")}} events.</p> - -<p>The <code>loadedmetadata</code> event is fired when the metadata has been loaded.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox notranslate"><em><var>element</var></em>.onloadedmetadata = <em>handlerFunction</em>; -var <em>handlerFunction</em> = <em><var>element</var></em>.onloadedmetadata; -</pre> - -<p><code>handlerFunction</code> should be either <code>null</code> or a <a href="/en-US/docs/Web/JavaScript/Reference/Functions" title="/en-US/docs/JavaScript/Reference/Functions_and_function_scope">JavaScript function</a> specifying the handler for the event.</p> - -<h2 id="Specification">Specification</h2> - -<table class="spectable standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('HTML WHATWG','#handler-onloadedmetadata','onloadedmetadata')}}</td> - <td>{{Spec2('HTML WHATWG')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("api.GlobalEventHandlers.onloadedmetadata")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{event("loadedmetadata")}}</li> - <li><a href="/en-US/docs/Web/Guide/Events/Event_handlers" title="/en-US/docs/Web/Guide/DOM/Events/Event_handlers">DOM event handlers</a></li> -</ul> 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 ---- -<p>This is an example of an AJAX web site composed only of three pages (<em>first_page.php</em>, <em>second_page.php</em> and <em>third_page.php</em>). To see how it works, please, create the following files (or git clone <a href="https://github.com/giabao/mdn-ajax-nav-example" title="/en-US/docs/">https://github.com/giabao/mdn-ajax-nav-example.git</a> ):</p> - -<div class="note" id="const_compatibility"><strong>Note:</strong> For fully integrating the {{HTMLElement("form")}} elements within this <em>mechanism</em>, please take a look at the paragraph <a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files">Submitting forms and uploading files</a>.</div> - -<p><strong>first_page.php</strong>:</p> - -<div style="height: 400px; margin-bottom: 12px; overflow: auto;"> -<pre class="brush: 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>"; - } -?> -</pre> -</div> - -<p><strong>second_page.php</strong>:</p> - -<div style="height: 400px; margin-bottom: 12px; overflow: auto;"> -<pre class="brush: 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>"; - } -?> -</pre> -</div> - -<p><strong>third_page.php</strong>:</p> - -<div style="height: 400px; margin-bottom: 12px; overflow: auto;"> -<pre class="brush: 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>"; - } -?> -</pre> -</div> - -<p><strong>css/style.css</strong>:</p> - -<pre class="brush: 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; -} -</pre> - -<p><strong>include/after_content.php</strong>:</p> - -<pre class="brush: php"><p>This is the footer. It is shared between all ajax pages.</p> -</pre> - -<p><strong>include/before_content.php</strong>:</p> - -<pre class="brush: 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> - -</pre> - -<p><strong>include/header.php</strong>:</p> - -<pre class="brush: 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" /> -</pre> - -<p><strong>js/ajax_nav.js</strong>:</p> - -<p>(before implementing it in a working environment, <strong>please read <a href="#const_compatibility" title="Note about *const* compatibility">the note about the const statement compatibility</a></strong>)</p> - -<div style="height: 400px; margin-bottom: 12px; overflow: auto;"> -<pre class="brush: js">"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; - -})(); -</pre> -</div> - -<div class="note" id="const_compatibility"><strong>Note:</strong> The current implementation of <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> (constant statement) <strong>is not part of ECMAScript 5</strong>. It is supported in Firefox & Chrome (V8) and partially supported in Opera 9+ and Safari. <strong>It is not supported in Internet Explorer 6-9, or in the preview of Internet Explorer 10</strong>. <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the <a href="/en/JavaScript/Reference/Statements/let" title="en/JavaScript/Reference/Statements/let"><code>let</code></a> statement, constants declared with <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> will be block-scoped. <strong>We used it only for didactic purpose. If you want a full browser compatibility of this library, please replace all the <a href="/en/JavaScript/Reference/Statements/const" title="en/JavaScript/Reference/Statements/const"><code>const</code></a> statements with the <a href="/en/JavaScript/Reference/Statements/var" title="en/JavaScript/Reference/Statements/var"><code>var</code></a> statements.</strong></div> - -<p>For more information, please see: <a href="/en-US/docs/DOM/Manipulating_the_browser_history" title="/en-US/docs/DOM/Manipulating_the_browser_history">Manipulating the browser history</a>.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{ domxref("window.history") }}</li> - <li>{{ domxref("window.onpopstate") }}</li> -</ul> 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 ---- -<p>{{ APIRef("Web Components") }}</p> - -<p>The <code><strong>HTMLContentElement.getDistributedNodes()</strong></code> method returns a static {{domxref("NodeList")}} of the {{glossary("distributed nodes")}} associated with this <code><content></code> element.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox">var <em>nodeList</em> = <em>object</em>.getDistributedNodes() -</pre> - -<h2 id="Specifications" name="Specifications">Example</h2> - -<pre class="brush: js">// Get the distributed nodes -var nodes = myContentObject.getDistributedNodes();</pre> - -<h2 id="Specifications" name="Specifications">Specifications</h2> - -<table class="spec-table standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('Shadow DOM', '#the-content-element', 'content')}}</td> - <td>{{Spec2('Shadow DOM')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>Basic support</td> - <td>35</td> - <td><span style="font-size: 12px; line-height: 18px;">{{CompatGeckoDesktop("28")}}</span> [1]</td> - <td>{{CompatNo}}</td> - <td>26</td> - <td><span style="font-size: 12px; line-height: 18px;">{{CompatNo}}</span></td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Phone</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>37</td> - <td>{{CompatGeckoMobile("28")}} [1]</td> - <td>{{CompatNo}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] If Shadow DOM is not enabled in Firefox, <code><content></code> elements will behave like {{domxref("HTMLUnknownElement")}}. Shadow DOM was first implemented in Firefox 28 and is behind a preference, <code>dom.webcomponents.enabled</code>, which is disabled by default.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/HTMLContentElement">HTMLContentElement</a></li> -</ul> 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 ---- -<p>{{ APIRef("Web Components") }}</p> - -<p>{{Deprecated_header}}</p> - -<p>The <code><strong>HTMLContentElement</strong></code> interface represents a {{HTMLElement("content")}} HTML Element, which is used in <a href="/en-US/docs/Web/Web_Components/Shadow_DOM">Shadow DOM</a>. </p> - -<h2 id="Properties" name="Properties">Properties</h2> - -<p><em>This interface inherits the properties of {{domxref("HTMLElement")}}.</em></p> - -<dl> - <dt>{{domxref("HTMLContentElement.select")}}</dt> - <dd>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 <code><content></code> element.</dd> -</dl> - -<h2 id="Methods">Methods</h2> - -<p><em>This interface inherits the methods of {{domxref("HTMLElement")}}.</em></p> - -<dl> - <dt>{{domxref("HTMLContentElement.getDistributedNodes()")}}</dt> - <dd>Returns a static {{domxref("NodeList")}} of the {{glossary("distributed nodes")}} associated with this <code><content></code> element. </dd> -</dl> - -<h2 id="Specifications">Specifications</h2> - -<table class="spec-table standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('Shadow DOM', '#the-content-element', 'content')}}</td> - <td>{{Spec2('Shadow DOM')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>Basic support</td> - <td>35</td> - <td><span style="font-size: 12px; line-height: 18px;">{{CompatGeckoDesktop("28")}}</span> [1]</td> - <td>{{CompatNo}}</td> - <td>26</td> - <td><span style="font-size: 12px; line-height: 18px;">{{CompatNo}}</span></td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Phone</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>37</td> - <td>{{CompatGeckoMobile("28")}} [1]</td> - <td>{{CompatNo}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[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, <code>dom.webcomponents.enabled</code>, which is disabled by default.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>The {{HTMLElement("content")}} HTML element, implementing this interface.</li> - <li><a href="/en-US/docs/Web/Web_Components/Shadow_DOM">Shadow DOM</a></li> -</ul> - -<dl> - <dt> </dt> -</dl> 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 ---- -<p>{{ APIRef("Web Components") }}</p> - -<p>The <code><strong>HTMLContentElement.select</strong></code> property reflects the <code>select</code> 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.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox"><em>object</em>.select = "<em>CSSselector</em> <em>CSSselector</em> ..."; -</pre> - -<h2 id="Specifications" name="Specifications">Example</h2> - -<pre class="brush: js">// Select <h1> elements and elements with class="error" -myContentObject.select = "h1 .error";</pre> - -<h2 id="Specifications" name="Specifications">Specifications</h2> - -<table class="spec-table standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('Shadow DOM', '#the-content-element', 'content')}}</td> - <td>{{Spec2('Shadow DOM')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>Basic support</td> - <td>35</td> - <td><span style="font-size: 12px; line-height: 18px;">{{CompatGeckoDesktop("28")}}</span> [1]</td> - <td>{{CompatNo}}</td> - <td>26</td> - <td><span style="font-size: 12px; line-height: 18px;">{{CompatNo}}</span></td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Phone</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>37</td> - <td>{{CompatGeckoMobile("28")}} [1]</td> - <td>{{CompatNo}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[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, <code>dom.webcomponents.enabled</code>, which is disabled by default.</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/HTMLContentElement">HTMLContentElement</a></li> -</ul> 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 ---- -<div>{{APIRef("HTML DOM")}}</div> - -<p><span class="seoSummary">The <code><strong>innerText</strong></code> property of the {{domxref("HTMLElement")}} interface represents the "rendered" text content of a node and its descendants.</span> 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.</p> - -<div class="blockIndicator note"> -<p><strong>Note:</strong> <code>innerText</code> is easily confused with {{domxref("Node.textContent")}}, but there are important differences between the two. Basically, <code>innerText</code> is aware of the rendered appearance of text, while <code>textContent</code> is not.</p> -</div> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox notranslate">const <em>renderedText</em> = <em>htmlElement</em>.innerText -<em>htmlElement</em>.innerText = <em>string</em></pre> - -<h3 id="Value">Value</h3> - -<p>A {{domxref("DOMString")}} representing the rendered text content of an element. If the element itself is not <a href="https://html.spec.whatwg.org/multipage/rendering.html#being-rendered">being rendered</a> (e.g detached from the document or is hidden from view), the returned value is the same as the {{domxref("Node.textContent")}} property.</p> - -<h2 id="Example">Example</h2> - -<p>This example compares <code>innerText</code> with {{domxref("Node.textContent")}}. Note how <code>innerText</code> is aware of things like {{htmlElement("br")}} elements, and ignores hidden elements.</p> - -<h3 id="HTML">HTML</h3> - -<pre class="brush: html notranslate"><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></pre> - -<h3 id="JavaScript">JavaScript</h3> - -<pre class="brush: js notranslate">const source = document.getElementById('source'); -const textContentOutput = document.getElementById('textContentOutput'); -const innerTextOutput = document.getElementById('innerTextOutput'); - -textContentOutput.innerHTML = source.textContent; -innerTextOutput.innerHTML = source.innerText;</pre> - -<h3 id="Result">Result</h3> - -<p>{{EmbedLiveSample("Example", 700, 450)}}</p> - -<h2 id="Specification">Specification</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('HTML WHATWG', 'dom.html#the-innertext-idl-attribute', 'innerText')}}</td> - <td>{{Spec2('HTML WHATWG')}}</td> - <td>Introduced, based on the <a href="https://github.com/rocallahan/innerText-spec">draft of the innerText specification</a>. See <a href="https://github.com/whatwg/html/issues/465">whatwg/html#465</a> and <a href="https://github.com/whatwg/compat/issues/5">whatwg/compat#5</a> for history.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("api.HTMLElement.innerText")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{domxref("HTMLElement.outerText")}}</li> - <li>{{domxref("Element.innerHTML")}}</li> -</ul> 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 ---- -<div>{{ APIRef("HTML DOM") }}</div> - -<p>The <strong><code>HTMLHtmlElement</code></strong> interface serves as the root node for a given HTML document. This object inherits the properties and methods described in the {{domxref("HTMLElement")}} interface.</p> - -<p>You can retrieve the <code>HTMLHtmlElement</code> object for a given document by reading the value of the {{domxref("document.documentElement")}} property.</p> - -<h2 id="Properties">Properties</h2> - -<p><em>Inherits properties from its parent, {{domxref("HTMLElement")}}.</em></p> - -<dl> - <dt>{{domxref("HTMLHtmlElement.version")}} {{ obsolete_inline() }}</dt> - <dd>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.</dd> -</dl> - -<h2 id="Methods">Methods</h2> - -<p><em>No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}.</em></p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('HTML WHATWG', "semantics.html#the-html-element", "HTMLHtmlElement")}}</td> - <td>{{Spec2('HTML WHATWG')}}</td> - <td>Live specification, no change since last snapshot</td> - </tr> - <tr> - <td>{{SpecName('HTML5.1', "semantics.html#the-html-element", "HTMLHtmlElement")}}</td> - <td>{{Spec2('HTML5.1')}}</td> - <td>No change since the last snapshot</td> - </tr> - <tr> - <td>{{SpecName('HTML5 W3C', "semantics.html#the-html-element", "HTMLHtmlElement")}}</td> - <td>{{Spec2('HTML5 W3C')}}</td> - <td>The <code>version</code> element has been removed, as it is non-conforming.</td> - </tr> - <tr> - <td>{{SpecName('DOM2 HTML', 'html.html#ID-33759296', 'HTMLHtmlElement')}}</td> - <td>{{Spec2('DOM2 HTML')}}</td> - <td>Reflecting the element change in {{SpecName("HTML4.01")}}, the <code>version</code> property is now deprecated.</td> - </tr> - <tr> - <td>{{SpecName('DOM1', 'level-one-html.html#ID-33759296', 'HTMLHtmlElement')}}</td> - <td>{{Spec2('DOM1')}}</td> - <td>Initial definition</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoDesktop(1.0)}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Phone</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatGeckoMobile(1.0)}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>{{CompatVersionUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="See_also">See also</h2> - -<ul> - <li>HTML element implementing this interface: {{HTMLElement("html")}}.</li> -</ul> 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 ---- -<p>The <code>abort</code> event is fired when the loading of a resource has been aborted.</p> - -<h2 id="Información_general">Información general</h2> - -<dl> - <dt style="float: left; text-align: right; width: 120px;">Specification</dt> - <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-abort">DOM L3</a></dd> - <dt style="float: left; text-align: right; width: 120px;">Interface</dt> - <dd style="margin: 0 0 0 120px;">UIEvent if generated from a user interface, Event otherwise.</dd> - <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> - <dd style="margin: 0 0 0 120px;">No</dd> - <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> - <dd style="margin: 0 0 0 120px;">No</dd> - <dt style="float: left; text-align: right; width: 120px;">Target</dt> - <dd style="margin: 0 0 0 120px;">Element</dd> - <dt style="float: left; text-align: right; width: 120px;">Default Action</dt> - <dd style="margin: 0 0 0 120px;">None</dd> -</dl> - -<h2 id="Propiedades">Propiedades</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Property</th> - <th scope="col">Type</th> - <th scope="col">Description</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>target</code> {{readonlyInline}}</td> - <td><a href="/en-US/docs/Web/API/EventTarget" title="EventTarget is an interface implemented by objects that can receive events and may have listeners for them."><code>EventTarget</code></a></td> - <td>The event target (the topmost target in the DOM tree).</td> - </tr> - <tr> - <td><code>type</code> {{readonlyInline}}</td> - <td><a href="/en-US/docs/Web/API/DOMString" title="DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String."><code>DOMString</code></a></td> - <td>The type of event.</td> - </tr> - <tr> - <td><code>bubbles</code> {{readonlyInline}}</td> - <td><a href="/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a></td> - <td>Whether the event normally bubbles or not.</td> - </tr> - <tr> - <td><code>cancelable</code> {{readonlyInline}}</td> - <td><a href="/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a></td> - <td>Whether the event is cancellable or not.</td> - </tr> - <tr> - <td><code>view</code> {{readonlyInline}}</td> - <td><a class="new" href="/en-US/docs/Web/API/WindowProxy" rel="nofollow" title="The documentation about this has not yet been written; please consider contributing!"><code>WindowProxy</code></a></td> - <td><a href="/en-US/docs/Web/API/Document/defaultView" title="In browsers, document.defaultView returns the window object associated with a document, or null if none is available."><code>document.defaultView</code></a> (<code>window</code> of the document)</td> - </tr> - <tr> - <td><code>detail</code> {{readonlyInline}}</td> - <td><code>long</code> (<code>float</code>)</td> - <td>0.</td> - </tr> - </tbody> -</table> 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 ---- -<p>{{APIRef("DOM Events")}}</p> - -<p>El método <code><strong>KeyboardEvent.getModifierState()</strong></code> retorna <code>true</code> respecto al estado actual de la tecla modificadora especificada si la misma está presionada o bloqueada, en caso contrario devuelve <code>false</code>.</p> - -<h2 id="Sintaxis">Sintaxis</h2> - -<pre class="syntaxbox">var <code><em>active</em> = <em>event</em>.getModifierState(<em>keyArg</em>);</code></pre> - -<h3 id="Retorna">Retorna</h3> - -<p>A {{jsxref("Boolean")}}</p> - -<h3 id="Parámetros">Parámetros</h3> - -<dl> - <dt><em><code>keyArg</code></em></dt> - <dd>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 <code>"Accel"</code> {{deprecated_inline}}, el cual es case-sensitive.</dd> -</dl> - -<h2 id="Teclas_modificadoras_en_Internet_Explorer">Teclas modificadoras en Internet Explorer</h2> - -<p>IE9 usa <code>"Scroll"</code> para <code>"ScrollLock"</code> y <code>"Win"</code> para <code>"OS"</code>.</p> - -<h2 id="Teclas_modificadoras_en_Gecko">Teclas modificadoras en Gecko</h2> - -<table style="width: 100%;"> - <caption>When getModifierState() returns true on Gecko?</caption> - <thead> - <tr> - <th scope="row"> </th> - <th scope="col">Windows</th> - <th scope="col">Linux (GTK)</th> - <th scope="col">Mac</th> - <th scope="col">Android 2.3</th> - <th scope="col">Android 3.0 or latter</th> - </tr> - </thead> - <tbody> - <tr> - <th scope="row"><code>"Alt"</code></th> - <td>Either <kbd>Alt</kbd> key or <kbd>AltGr</kbd> key pressed</td> - <td><kbd>Alt</kbd> key pressed</td> - <td><kbd>⌥ Option</kbd> key pressed</td> - <td colspan="2" rowspan="1"><kbd>Alt</kbd> key or <kbd>option</kbd> key pressed</td> - </tr> - <tr> - <th scope="row"><code>"AltGraph"</code></th> - <td> - <p>Both <kbd>Alt</kbd> and <kbd>Ctrl</kbd> keys are pressed, or <kbd>AltGr</kbd> key is pressed</p> - </td> - <td><kbd>Level 3 Shift</kbd> key (or <kbd>Level 5 Shift</kbd> key {{gecko_minversion_inline("20.0")}}) pressed</td> - <td><kbd>⌥ Option</kbd> key pressed</td> - <td colspan="2" rowspan="1" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> - </tr> - <tr> - <th scope="row"><code>"CapsLock"</code></th> - <td colspan="3" style="text-align: center;">During LED for <kbd>⇪ Caps Lock</kbd> turned on</td> - <td style="text-align: center; background-color: rgb(204, 204, 204);"><em>Not supported</em></td> - <td>While <kbd>CapsLock</kbd> is locked {{gecko_minversion_inline("29.0")}}</td> - </tr> - <tr> - <th scope="row"><code>"Control"</code></th> - <td>Either <kbd>Ctrl</kbd> key or <kbd>AltGr</kbd> key pressed</td> - <td><kbd>Ctrl</kbd> key pressed</td> - <td><kbd>control</kbd> key pressed</td> - <td><kbd>menu</kbd> key pressed.</td> - <td><kbd>Ctrl</kbd> key, <kbd>control</kbd> key or <kbd>menu</kbd> key pressed.</td> - </tr> - <tr> - <th scope="row"><code>"Fn"</code></th> - <td colspan="4" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> - <td><kbd>Function</kbd> key is pressed, but we're not sure what key makes the modifier state active. <kbd>Fn</kbd> key on Mac keyboard doesn't cause this active. {{gecko_minversion_inline("29.0")}}</td> - </tr> - <tr> - <th scope="row"><code>"FnLock"</code></th> - <td colspan="5" rowspan="1" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> - </tr> - <tr> - <th scope="row"><code>"Hyper"</code></th> - <td colspan="5" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> - </tr> - <tr> - <th scope="row"><code>"Meta"</code></th> - <td style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> - <td style="text-align: center;"><kbd>Meta</kbd> key pressed {{gecko_minversion_inline("17.0")}}</td> - <td><kbd>⌘ Command</kbd> key pressed</td> - <td style="text-align: center; background-color: rgb(204, 204, 204);"><em>Not supported</em></td> - <td><kbd>⊞ Windows Logo</kbd> key or <kbd>command</kbd> key pressed</td> - </tr> - <tr> - <th scope="row"><code>"NumLock"</code></th> - <td colspan="2" style="text-align: center;">During LED for <kbd>Num Lock</kbd> turned on</td> - <td>A key on numpad pressed</td> - <td style="text-align: center; background-color: rgb(204, 204, 204);"><em>Not supported</em></td> - <td>While <kbd>NumLock</kbd> is locked {{gecko_minversion_inline("29.0")}}</td> - </tr> - <tr> - <th scope="row"><code>"OS"</code></th> - <td><kbd>⊞ Windows Logo</kbd> key pressed</td> - <td><kbd>Super</kbd> key or <kbd>Hyper</kbd> key pressed (typically, mapped to <kbd>⊞ Windows Logo</kbd> key)</td> - <td colspan="3" rowspan="1" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> - </tr> - <tr> - <th scope="row"><code>"ScrollLock"</code></th> - <td>During LED for <kbd>Scroll Lock</kbd> turned on</td> - <td>During LED for <kbd>Scroll Lock</kbd> turned on, but typically this isn't supported by platform</td> - <td colspan="2" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> - <td>While <kbd>ScrollLock</kbd> is locked {{gecko_minversion_inline("29.0")}}</td> - </tr> - <tr> - <th scope="row"><code>"Shift"</code></th> - <td colspan="5" rowspan="1" style="text-align: center;"><kbd>⇧ Shift</kbd> key pressed</td> - </tr> - <tr> - <th scope="row"><code>"Super"</code></th> - <td colspan="5" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> - </tr> - <tr> - <th scope="row"><code>"Symbol"</code></th> - <td colspan="5" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> - </tr> - <tr> - <th scope="row"><code>"SymbolLock"</code></th> - <td colspan="5" style="background-color: rgb(204, 204, 204); text-align: center;"><em>Not supported</em></td> - </tr> - </tbody> -</table> - -<ul> - <li>On the other platforms, "Alt", "Control" and "Shift" may be supported.</li> - <li>All modifiers (except <code>"FnLock"</code>, <code>"Hyper"</code>, <code>"Super"</code> and <code>"Symbol"</code> which are defined after Gecko implements this) are always supported for untrusted events on Gecko. This doesn't depend on the platform.</li> -</ul> - -<h2 id="El_modificador_virtual_Accel"> El modificador virtual <code>"Accel"</code></h2> - -<div class="note"><strong>Note:</strong> The <code>"Accel"</code> virtual modifier has been effectively <strong>deprecated</strong> in current drafts of the DOM3 Events specification.</div> - -<p><code>getModifierState()</code> also accepts a deprecated virtual modifier named <code>"Accel"</code>. <code>event.getModifierState("Accel")</code> returns <code>true</code> when at least one of {{domxref("KeyboardEvent.ctrlKey")}} or {{domxref("KeyboardEvent.metaKey")}} is <code>true</code>.</p> - -<p>In old implementations and outdated specifications, it returned <code>true</code> when a modifier which is the typical modifier key for the shortcut key is pressed. For example, on Windows, pressing <kbd>Ctrl</kbd> key may make it return <code>true</code>. However, on Mac, pressing <kbd>⌘ Command</kbd> key may make it return <code>true</code>. 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, <code>"ui.key.accelKey"</code>.</p> - -<h2 id="Ejemplo">Ejemplo</h2> - -<pre class="brush: js">// 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; - } -} -</pre> - -<div class="note"> -<p>Although, this example uses<code> .getModifierState()</code> with <code>"Alt"</code>, <code>"Control"</code>, <code>"Meta"</code> and <code>"Shift"</code>, perhaps it's better for you to use <code>altKey</code>, <code>ctrlKey</code>, <code>metaKey</code> and <code>shiftKey</code> because they are shorter and may be faster.</p> -</div> - -<h2 id="Especificaciones">Especificaciones</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Especificaciones</th> - <th scope="col">Estado</th> - <th scope="col">Comentario</th> - </tr> - <tr> - <td>{{SpecName('DOM3 Events', '#widl-KeyboardEvent-getModifierState', 'getModifierState()')}}</td> - <td>{{Spec2('DOM3 Events')}}</td> - <td>Initial definition (<a href="https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3Events-key.html#keys-modifier">Modifier Keys spec</a>)</td> - </tr> - </tbody> -</table> - -<h2 id="Compatibilidad_con_Browsers">Compatibilidad con Browsers</h2> - - - -<p>{{Compat("api.KeyboardEvent.getModifierState")}}</p> - -<h2 id="Ver_también">Ver también</h2> - -<ul> - <li>The {{domxref("KeyboardEvent")}} this method belongs to.</li> - <li>{{domxref("MouseEvent.getModifierState")}}</li> -</ul> 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 ---- -<p>{{APIRef("DOM Events")}}</p> - -<p><span class="seoSummary">La propiedad de solo lectura<strong> </strong><code><strong>KeyboardEvent.key</strong></code> retorna el valor de la tecla presionada por el usuario while taking into considerations the state of modifier keys such as the <code>shiftKey</code> as well as the keyboard locale/layout.</span> Its value is determined as follows:</p> - -<div class="pull-aside"> -<p class="moreinfo">See a full list of <a href="/docs/Web/API/KeyboardEvent/key/Key_Values">key values</a>.</p> -</div> - -<ul> - <li>Si la tecla presionada tiene una representación impresa, el valor devuelto es una cadena de caracteres Unicode no-vacía que contiene la representación imprimible de la tecla.</li> - <li>Si la tecla presionada es un control o un carácter especial, el valor devuelto es uno de los <a href="/docs/Web/API/KeyboardEvent/key/Key_Values">valores clave definidos</a>.</li> - <li>If the <code>KeyboardEvent</code> represents the press of a dead key, the key value must be "<code>Dead</code>".</li> - <li>Some specialty keyboard keys (such as the extended keys for controlling media on multimedia keyboards) don't generate key codes on Windows; instead, they trigger <code>WM_APPCOMMAND</code> events. These events get mapped to DOM keyboard events, and are listed among the "Virtual key codes" for Windows, even though they aren't actually key codes.</li> - <li>If the key cannot be identified, the returned value is <code>"Unidentified"</code>.</li> -</ul> - -<h2 id="KeyboardEvent_Sequence">KeyboardEvent Sequence</h2> - -<p><code>KeyboardEvent</code>s are fired in a pre-determined sequence and understanding this will go a long way into understanding the <code>key</code> property value for a particular <code>KeyboardEvent</code>. For a given key press, the sequence of <code>KeyboardEvent</code>s fired is as follows assuming that {{domxref("Event.preventDefault")}} is not called:</p> - -<ol> - <li>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 <code>true</code>.</li> - <li>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.</li> - <li>A {{event("keyup")}} event is fired once the key is released. This completes the process.</li> -</ol> - -<p>In sequence 1 & 3, the <code>KeyboardEvent.key</code> attribute is defined and is set appropriately to a value according to the rules defined ealier.</p> - -<h2 id="KeyboardEvent_Sequence_Sample">KeyboardEvent Sequence Sample</h2> - -<p>Consider the event sequence generated when we interact with the <code>ShiftKey</code> and the legend <code>key 2</code> using a U.S keyboard layout and a UK keyboard layout.</p> - -<p>Try experimenting using the following two test cases:</p> - -<ol> - <li>Press and hold the <code>shift</code> key, then press <code>key 2</code> and release it. Next, release the <code>shift</code> key.</li> - <li>Press and hold the <code>shift</code> key, then press and hold <code>key 2</code>. Release the <code>shift</code> key. Finally, release <code>key 2</code>.</li> -</ol> - -<h3 id="HTML">HTML</h3> - -<pre class="brush: 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> -</pre> - -<h3 id="CSS">CSS</h3> - -<pre class="brush: 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; -}</pre> - -<h3 id="JavaScript">JavaScript</h3> - -<pre class="brush: js">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; - } -});</pre> - -<h3 id="Result">Result</h3> - -<p>{{EmbedLiveSample('KeyboardEvent_Sequence_Sample')}}</p> - -<h3 id="Case_1">Case 1</h3> - -<p>When the shift key is pressed, a {{event("keydown")}} event is first fired, and the <code>key</code> property value is set to the string <code>"Shift"</code>. As we keep holding this key, the {{event("keydown")}} event does not continue to fire repeatedly because it does not produce a character key.</p> - -<p>When <code>key 2</code> is pressed, another {{event("keydown")}} event is fired for this new key press, and the <code>key</code> property value for the event is set to the string <code>"@"</code> for the U.S keyboard type and <code>"""</code> for the UK keyboard type, because of the active modifier <code>shift</code> key. The {{event("beforeinput")}} and {{event("input")}} events are fired next because a character key has been produced.</p> - -<p>As we release the <code>key 2</code>, a {{event("keyup")}} event is fired and the <code>key</code> property will maintain the string values <code>"@"</code> and <code>"""</code> for the different keyboard layouts respectively.</p> - -<p>As we finally release the <code>shift</code> key, another {{event("keyup")}} event is fired for it, and the key attribute value remains <code>"Shift"</code>.</p> - -<h3 id="Case_2">Case 2</h3> - -<p>When the shift key is pressed, a {{event("keydown")}} event is first fired, and the <code>key</code> property value is set to be the string <code>"Shift"</code>. As we keep holding this key, the keydown event does not continue to fire repeatedly because it produced no character key.</p> - -<p>When <code>key 2</code> is pressed, another {{event("keydown")}} event is fired for this new key press, and the <code>key</code> property value for the event is set to be the string <code>"@"</code> for the U.S keyboard type and <code>"""</code> for the UK keyboard type, because of the active modifier <code>shift</code> 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 <code>true</code>. The {{event("beforeinput")}} and {{event("input")}} events are fired repeatedly as well.</p> - -<p>As we release the <code>shift</code> key, a {{event("keyup")}} event is fired for it, and the key attribute value remains <code>"Shift"</code>. At this point, notice that the <code>key</code> property value for the repeating keydown event of the <code>key 2</code> key press is now "2" because the modifier <code>shift</code> key is no longer active. The same goes for the {{domxref("InputEvent.data")}} property of the {{event("beforeinput")}} and {{event("input")}} events.</p> - -<p>As we finally release the <code>key 2</code>, a {{event("keyup")}} event is fired but the <code>key</code> property will be set to the string value <code>"2"</code> for both keyboard layouts because the modifier <code>shift</code> key is no longer active.</p> - -<h2 id="Example">Example</h2> - -<p>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).</p> - -<pre class="brush: js">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); -</pre> - -<h2 id="Specification">Specification</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('DOM3 Events', '#widl-KeyboardEvent-key', 'KeyboardEvent.key')}}</td> - <td>{{Spec2('DOM3 Events')}}</td> - <td>Initial definition, included key values.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("api.KeyboardEvent.key")}}</p> 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 ---- -<div>{{APIRef("Media Capture and Streams")}}</div> - -<p>The <strong><code>Navigator.mediaDevices</code></strong> 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.</p> - -<h2 id="Syntax">Syntax</h2> - -<pre class="syntaxbox notranslate">var <em>mediaDevices</em> = navigator.mediaDevices; -</pre> - -<h3 id="Return_value">Return value</h3> - -<p>The {{domxref("MediaDevices")}} singleton object. Usually, you just use this object's members directly, such as by calling {{domxref("navigator.mediaDevices.getUserMedia()")}}.</p> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('Media Capture', '#mediadevices', 'NavigatorUserMedia.mediaDevices')}}</td> - <td>{{Spec2('Media Capture')}}</td> - <td>Initial definition.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("api.Navigator.mediaDevices")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/Media_Streams_API">Media Capture and Streams API</a>: The entry point to the documentation about the entire media stream API.</li> - <li><a href="/en-US/docs/Web/API/WebRTC_API"><font><font>API de WebRTC</font></font></a><font><font> : documentación sobre la API de WebRTC, que está estrechamente relacionada.</font></font></li> -</ul> 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 ---- -<p>{{SeeCompatTable}}{{ApiRef("Push API")}}</p> - -<p>El metodo <strong><code>permissionState()</code></strong> 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 <code>'prompt'</code>, <code>'denied'</code>, or <code>'granted'</code>.</p> - -<div class="note"> -<p><strong>Note</strong>: As of Firefox 44, the permissions for <a href="/en-US/docs/Web/API/Notifications_API">Notifications</a> and <a href="/en-US/docs/Web/API/Push_API">Push</a> have been merged. If permission is granted for notifications, push will also be enabled.</p> -</div> - -<h2 id="Sintaxis"><span>Sintaxis</span></h2> - -<pre class="syntaxbox">PushManager.permissionState(options).then(function(PushMessagingState) { ... }); -</pre> - -<h3 id="Parámetros">Parámetros</h3> - -<dl> - <dt><code>opciones {{optional_inline}}</code></dt> - <dd>An object containing optional configuration parameters. It can have the following properties: - <ul> - <li><code>userVisibleOnly</code>: A boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user.</li> - </ul> - </dd> -</dl> - -<h3 id="Retorna">Retorna</h3> - -<p>Un {{jsxref("Promise")}} que resuelve a un {{domxref("DOMString")}} con un valor de <code>'prompt'</code>, <code>'denied'</code>, o <code>'granted'</code>.</p> - -<h2 id="Especificaciones">Especificaciones</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Especificación</th> - <th scope="col">Estado</th> - <th scope="col">Comentario</th> - </tr> - <tr> - <td>{{SpecName('Push API','#widl-PushManager-permissionState-Promise-PushPermissionState--PushSubscriptionOptions-options','permissionState()')}}</td> - <td>{{Spec2('Push API')}}</td> - <td>Initial definition.</td> - </tr> - </tbody> -</table> - -<h2 id="Compactibilidad_del_Navegador">Compactibilidad del Navegador</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Característica</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatChrome(42.0)}}</td> - <td>{{CompatGeckoDesktop(44.0)}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatNo}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Característica</th> - <th>Android</th> - <th>Android Webview</th> - <th>Firefox Mobile (Gecko)</th> - <th>Firefox OS</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - <th>Chrome for Android</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(42.0)}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Ver_también">Ver también</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/Push_API/Using_the_Push_API">Using the Push API</a></li> -</ul> 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 ---- -<p>{{ ApiRef() }}</p> -<h3 id="Summary" name="Summary">Summary</h3> -<p>{{ Obsolete_header() }} Returns a boolean indicating whether the given node intersects the range.</p> -<h3 id="Syntax" name="Syntax">Syntax</h3> -<pre class="eval">bool = range.intersectsNode( referenceNode ) -</pre> -<h3 id="Parameters" name="Parameters">Parameters</h3> -<dl> - <dt> - referenceNode </dt> - <dd> - The <code>Node</code> to compare with the <code>Range</code>.</dd> -</dl> -<h3 id="Example" name="Example">Example</h3> -<pre class="eval">range = document.createRange(); -range.selectNode(document.getElementsByTagName("div").item(0)); -bool = range.intersectsNode(document.getElementsByTagName("p").item(0)); -</pre> -<h3 id="Notes" name="Notes">Notes</h3> -<p>This method is obsolete; you should instead use the W3C DOM Range methods (see <code><a href="es/DOM/range.compareBoundaryPoints">compareBoundaryPoints()</a></code>).</p> -<div class="warning"> - <b>Warning:</b> This method <a href="es/Gecko_1.9_Changes_affecting_websites">has been removed</a> from <a href="es/Gecko">Gecko</a> 1.9 and will not exist in future versions of Firefox; you should switch to <code>compareBoundaryPoints()</code> as soon as possible.</div> -<p>The following function can be used as replacement:</p> -<pre class="eval">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; -} -</pre> -<h3 id="Specification" name="Specification">Specification</h3> -<p>This method is not part of a specification.</p> -<div class="noinclude"> - </div> -<p>{{ languages( { "en": "en/DOM/range.intersectsNode", "pl": "pl/DOM/range.intersectsNode" } ) }}</p> 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 ---- -<p>{{ServiceWorkerSidebar}}</p> - -<p>{{ SeeCompatTable() }}</p> - -<div class="summary"> -<p>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).</p> -</div> - -<h2 id="La_premisa_de_los_service_workers">La premisa de los service workers</h2> - -<p>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 <a href="https://developer.mozilla.org/en-US/Apps/Build/Offline">offline</a>, 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.</p> - -<p>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 <a href="http://alistapart.com/article/application-cache-is-a-douchebag">Application Cache is a Douchebag</a> para más información.</p> - -<div class="note"> -<p><strong>Nota</strong>: A partir de Firefox 44, cuando se usa <a href="/en-US/docs/Web/HTML/Using_the_application_cache">AppCache</a> para proveer soporte offline a una página se muestra un mensaje de advertencia en la consola aconsejandole al desarrollador para que use <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service workers</a> en su lugar ({{bug("1204581")}}.)</p> -</div> - -<p>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.</p> - -<p>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 <a href="/es/docs/">Offline First</a>) 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.</p> - -<h2 id="Setting_up_to_play_with_service_workers">Setting up to play with service workers</h2> - -<p>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:</p> - -<ul> - <li><strong>Firefox Nightly</strong>: Go to <code>about:config</code> and set <code>dom.serviceWorkers.enabled</code> to true; restart browser.</li> - <li><strong>Chrome Canary</strong>: Go to <code>chrome://flags</code> and turn on <code>experimental-web-platform-features</code>; restart browser (note that some features are now enabled by default in Chrome.)</li> - <li><strong>Opera</strong>: Go to <code>opera://flags</code> and enable <code>Support for ServiceWorker</code>; restart browser.</li> -</ul> - -<p>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, <code>localhost</code> is considered a secure origin by browsers as well.</p> - -<h2 id="Basic_architecture">Basic architecture</h2> - -<p>With service workers, the following steps are generally observed for basic set up:</p> - -<ol> - <li>The service worker URL is fetched and registered via {{domxref("serviceWorkerContainer.register()")}}.</li> - <li>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.</li> - <li>The service worker is now ready to process events.</li> - <li>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.</li> - <li>When the <code>oninstall</code> handler completes, the service worker is considered installed.</li> - <li>Next is activation. When the service worker is installed, it then receives an activate event. The primary use of <code>onactivate</code> is for cleanup of resources used in previous versions of a Service worker script.</li> - <li>The Service worker will now control pages, but only those opened after the <code>register()</code> 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.</li> -</ol> - -<p><img alt="" src="https://mdn.mozillademos.org/files/12636/sw-lifecycle.png" style="display: block; height: 867px; margin: 0px auto; width: 579px;"></p> - -<p>The below graphic shows a summary of the available service worker events:</p> - -<p><img alt="install, activate, message, fetch, sync, push" src="https://mdn.mozillademos.org/files/12632/sw-events.png" style="display: block; margin: 0px auto;"></p> - -<h3 id="Promises">Promises</h3> - -<p>Las promesas (<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a>) 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.<br> - <br> - 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 <code>.then()</code> to the end and include callbacks inside it for success, failure, etc., or you can insert <code>.catch()</code> on the end if you want to include a failure callback.</p> - -<p>Let’s compare a traditional synchronous callback structure to its asynchronous promise equivalent.</p> - -<h4 id="sync">sync</h4> - -<pre class="brush: js">try { - var value = myFunction(); - console.log(value); -} catch(err) { - console.log(err); -}</pre> - -<h4 id="async">async</h4> - -<pre class="brush: js">myFunction().then(function(value) { - console.log(value); -}).catch(function(err) { - console.log(err); -});</pre> - -<p>In the first example, we have to wait for <code>myFunction()</code> to run and return <code>value</code> before any more of the code can execute. In the second example, <code>myFunction()</code> returns a promise for <code>value</code>, then the rest of the code can carry on running. When the promise resolves, the code inside <code>then</code> will be run, asynchronously.<br> - <br> - 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 <code>.onload</code> 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 <code>.complete</code>, but it’s still not foolproof, and what about multiple images? And, ummm, it’s still synchronous, so blocks the main thread.<br> - <br> - Instead, we could build our own promise to handle this kind of case. (See our <a href="https://github.com/mdn/promises-test">Promises test</a> example for the source code, or <a href="https://mdn.github.io/promises-test/">look at it running live</a>.)</p> - -<p>{{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.")}}</p> - -<pre class="brush: js">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(); - }); -}</pre> - -<p>We return a new promise using the <code>Promise()</code> constructor, which takes as an argument a callback function with <code>resolve</code> and <code>reject</code> 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 <code>resolve</code> on success, or <code>reject</code> on failure. The rest of the contents of this function is fairly standard XHR stuff, so we won’t worry about that for now.</p> - -<p>When we come to call the <code>imgLoad()</code> 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:</p> - -<pre class="brush: js">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); -});</pre> - -<p>On to the end of the function call, we chain the promise <code>then()</code> 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 <code>myImage</code> and append it to the body (it’s argument is the <code>request.response</code> contained inside the promise’s <code>resolve</code> method); in the rejected case we return an error to the console.</p> - -<p>This all happens asynchronously.</p> - -<div class="note"> -<p><strong>Note</strong>: You can also chain promise calls together, for example:<br> - <code>myPromise().then(success, failure).then(success).catch(failure);</code></p> -</div> - -<div class="note"> -<p><strong>Note</strong>: You can find a lot more out about promises by reading Jake Archibald’s excellent <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">JavaScript Promises: there and back again</a>.</p> -</div> - -<h2 id="Service_workers_demo">Service workers demo</h2> - -<p>To demonstrate just the very basics of registering and installing a service worker, we have created a simple demo called <a href="https://github.com/mdn/sw-test">sw-test</a>, 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!</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/8243/demo-screenshot.png" style="display: block; height: 410px; margin: 0px auto; width: 480px;"><br> - <br> - <br> - You can see the <a href="https://github.com/mdn/sw-test/">source code on GitHub</a>, and <a href="https://mdn.github.io/sw-test/">view the example live</a>. The one bit we’ll call out here is the promise (see <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L22-L47">app.js lines 22-47</a>), which is a modified version of what you read about above, in the <a href="https://github.com/mdn/promises-test">Promises test demo</a>. It is different in the following ways:</p> - -<ol> - <li>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 <a href="https://github.com/mdn/sw-test/blob/gh-pages/image-list.js">image-list.js</a>). 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 <code>for()</code> 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.)</li> - <li>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 <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L31-L34">app.js lines 31-34</a>). Promises will only resolve with a single argument, so if you want to resolve with multiple values, you need to use an array/object.</li> - <li>To access the resolved promise values, we then access this function as you’d then expect (see <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L60-L64">app.js lines 60-64</a>). This may seem a bit odd at first, but this is the way promises work.</li> -</ol> - -<h2 id="Enter_service_workers">Enter service workers</h2> - -<p>Now let’s get on to service workers!</p> - -<h3 id="Registering_your_worker">Registering your worker</h3> - -<p>The first block of code in our app’s JavaScript file — <code>app.js</code> — is as follows. This is our entry point into using service workers.</p> - -<pre class="brush: js">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); - }); -}</pre> - -<ol> - <li>The outer block performs a feature detection test to make sure service workers are supported before trying to register one.</li> - <li>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.)</li> - <li>The <code>scope</code> 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 '<code>/sw-test/'</code>, 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.</li> - <li>The <code>.then()</code> promise function is used to chain a success case onto our promise structure. When the promise resolves successfully, the code inside it executes.</li> - <li>Finally, we chain a <code>.catch()</code> function onto the end that will run if the promise is rejected.</li> -</ol> - -<p>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.<br> - <br> - 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.</p> - -<div class="note"> -<p><strong>Note</strong>: 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.</p> -</div> - -<div class="note"> -<p><strong>Note</strong>: 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.</p> -</div> - -<h4 id="Why_is_my_service_worker_failing_to_register">Why is my service worker failing to register?</h4> - -<p>This could be for the following reasons:</p> - -<ol> - <li>You are not running your application through HTTPS.</li> - <li>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 <code>https://mdn.github.io/sw-test/sw.js</code>, and the app’s root is <code>https://mdn.github.io/sw-test/</code>. But the path needs to be written as <code>/sw-test/sw.js</code>, not <code>/sw.js</code>.</li> - <li>The service worker being pointed to is on a different origin to that of your app. This is also not allowed.</li> -</ol> - -<p><img alt="" src="https://mdn.mozillademos.org/files/12630/important-notes.png" style="display: block; height: 277px; margin: 0px auto; width: 574px;"></p> - -<p>Also note:</p> - -<ul> - <li>The service worker will only catch requests from clients under the service worker's scope.</li> - <li>The max scope for a service worker is the location of the worker.</li> - <li>If your server worker is active on a client being served with the <code>Service-Worker-Allowed</code> header, you can specify a list of max scopes for that worker.</li> - <li>In Firefox, Service Worker APIs are hidden and cannot be used when the user is in <a href="https://support.mozilla.org/en-US/kb/private-browsing-use-firefox-without-history">private browsing mode</a>.</li> -</ul> - -<h3 id="Install_and_activate_populating_your_cache">Install and activate: populating your cache</h3> - -<p>After your service worker is registered, the browser will attempt to install then activate the service worker for your page/site.<br> - <br> - 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.</p> - -<div class="note"> -<p><strong>Note</strong>: 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 <a href="https://github.com/Polymer/topeka/blob/master/sw.js">Google's Topeka demo</a>, or perhaps store your assets in <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a>.</p> -</div> - -<p>Let’s start this section by looking at a code sample — this is the <a href="https://github.com/mdn/sw-test/blob/gh-pages/sw.js#L1-L18">first block you’ll find in our service worker</a>:</p> - -<pre class="brush: js">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' - ]); - }) - ); -});</pre> - -<ol> - <li>Here we add an <code>install</code> event listener to the service worker (hence <code>this</code>), and then chain a {{domxref("ExtendableEvent.waitUntil()") }} method onto the event — this ensures that the service worker will not install until the code inside <code>waitUntil()</code> has successfully occurred.</li> - <li>Inside <code>waitUntil()</code> we use the <a href="/en-US/docs/Web/API/CacheStorage/open"><code>caches.open()</code></a> method to create a new cache called <code>v1</code>, 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 <code>addAll()</code> on the created cache, which for its parameter takes an array of origin-relative URLs to all the resources you want to cache.</li> - <li>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.</li> - <li>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.)</li> -</ol> - -<div class="note"> -<p><strong>Note</strong>: <a href="/en-US/docs/Web/Guide/API/DOM/Storage">localStorage</a> works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.</p> -</div> - -<div class="note"> -<p><strong>Note</strong>: <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> can be used inside a service worker for data storage if you require it.</p> -</div> - -<h3 id="Custom_responses_to_requests">Custom responses to requests</h3> - -<p>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 <code>fetch</code> event.</p> - -<p><img alt="" src="https://mdn.mozillademos.org/files/12634/sw-fetch.png" style="display: block; margin: 0 auto;"></p> - -<p>A <code>fetch</code> 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 <code>index.html</code> makes a cross origin request to embed an image, that still goes through its service worker.)</p> - -<p>You can attach a <code>fetch</code> event listener to the service worker, then call the <code>respondWith()</code> method on the event to hijack our HTTP responses and update them with your own magic.</p> - -<pre class="brush: js">this.addEventListener('fetch', function(event) { - event.respondWith( - // magic goes here - ); -});</pre> - -<p>We could start by simply responding with the resource whose url matches that of the network request, in each case:</p> - -<pre class="brush: js">this.addEventListener('fetch', function(event) { - event.respondWith( - caches.match(event.request) - ); -});</pre> - -<p><code>caches.match(event.request)</code> 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.</p> - -<p>Let’s look at a few other options we have when defining our magic (see our <a href="/en-US/docs/Web/API/Fetch_API">Fetch API documentation</a> for more information about {{domxref("Request")}} and {{domxref("Response")}} objects.)</p> - -<ol> - <li> - <p>The <code>{{domxref("Response.Response","Response()")}}</code> constructor allows you to create a custom response. In this case, we are just returning a simple text string:</p> - - <pre class="brush: js">new Response('Hello from your friendly neighbourhood service worker!');</pre> - </li> - <li> - <p>This more complex <code>Response</code> 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:</p> - - <pre class="brush: js">new Response('<p>Hello from your friendly neighbourhood service worker!</p>', { - headers: { 'Content-Type': 'text/html' } -});</pre> - </li> - <li> - <p>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:</p> - - <pre class="brush: js">fetch(event.request);</pre> - </li> - <li> - <p>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:</p> - - <pre class="brush: js">caches.match('/fallback.html');</pre> - </li> - <li> - <p>You can retrieve a lot of information about each request by calling parameters of the {{domxref("Request")}} object returned by the {{domxref("FetchEvent")}}:</p> - - <pre class="brush: js">event.request.url -event.request.method -event.request.headers -event.request.body</pre> - </li> -</ol> - -<h2 id="Recovering_failed_requests">Recovering failed requests</h2> - -<p>So <code>caches.match(event.request)</code> 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 <code>undefined</code> and we wouldn't get anything returned.</p> - -<p>Fortunately service workers’ promise-based structure makes it trivial to provide further options towards success. We could do this:</p> - -<pre class="brush: js">this.addEventListener('fetch', function(event) { - event.respondWith( - caches.match(event.request).then(function(response) { - return response || fetch(event.request); - }) - ); -});</pre> - -<p>If the resources isn't in the cache, it is requested from the network.</p> - -<p>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:</p> - -<pre class="brush: js">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; - }); - }); - }) - ); -});</pre> - -<p>Here we return the default network request with <code>return fetch(event.request)</code>, which returns a promise. When this promise is resolved, we respond by running a function that grabs our cache using <code>caches.open('v1')</code>; this also returns a promise. When that promise resolves, <code>cache.put()</code> is used to add the resource to the cache. The resource is grabbed from <code>event.request</code>, and the response is then cloned with <code>response.clone()</code> 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.</p> - -<p>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.</p> - -<p>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:</p> - -<pre class="brush: js">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'); - }) - ); -});</pre> - -<p>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 <code>install</code> event listener we saw earlier.</p> - -<h2 id="Updating_your_service_worker"><a id="Updating your service worker" name="Updating your service worker">Updating your service worker</a></h2> - -<p>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.</p> - -<p>You’ll want to update your <code>install</code> event listener in the new service worker to something like this (notice the new version number):</p> - -<pre class="brush: js">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... - ]); - }) - ); -});</pre> - -<p>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 <code>v2</code>, so the previous <code>v1</code> cache isn't disturbed.</p> - -<p>When no pages are using the current version, the new worker activates and becomes responsible for fetches.</p> - -<h3 id="Deleting_old_caches">Deleting old caches</h3> - -<p>You also get an <code>activate</code> 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.</p> - -<p>Promises passed into <code>waitUntil()</code> 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 <code>fetch</code> event on the new cache.</p> - -<pre class="brush: js">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); - } - })); - }) - ); -});</pre> - -<h2 id="Developer_tools">Developer tools</h2> - -<p>Chrome has <code>chrome://inspect/#service-workers</code>, which shows current service worker activity and storage on a device, and <code>chrome://serviceworker-internals</code>, 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.</p> - -<p>Firefox has also started to implement some useful tools related to service workers:</p> - -<ul> - <li>You can navigate to <code><a href="/en-US/docs/Tools/about:debugging">about:debugging</a></code> to see what SWs are registered and update/remove them.</li> - <li>When testing you can get around the HTTPS restriction by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the <a href="/en-US/docs/Tools/Settings">Firefox Developer Tools settings</a>.</li> -</ul> - -<div class="note"> -<p><strong>Note</strong>: You may serve your app from <code>http://localhost</code> (e.g. using <code>me@localhost:/my/app$ <strong>python -m SimpleHTTPServer</strong></code>) for local development. See <a href="https://www.w3.org/TR/service-workers/#security-considerations">Security considerations</a></p> -</div> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('Service Workers', '')}}</td> - <td>{{Spec2('Service Workers')}}</td> - <td>Initial definition.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatChrome(40.0)}}</td> - <td>{{ CompatGeckoDesktop("33.0") }}<sup>[1]</sup></td> - <td>{{CompatNo}}</td> - <td>24</td> - <td>{{CompatNo}}</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android Webview</th> - <th>Chrome for Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>Firefox OS</th> - <th>IE Phone</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatNo}}</td> - <td>{{CompatChrome(40.0)}}</td> - <td>{{ CompatVersionUnknown }}</td> - <td>{{ CompatVersionUnknown }}</td> - <td>{{CompatNo}}</td> - <td>{{ CompatVersionUnknown() }}</td> - <td>{{CompatNo}}</td> - </tr> - </tbody> -</table> -</div> - -<p>[1] Service workers (and <a href="/en-US/docs/Web/API/Push_API">Push</a>) have been disabled in the <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 Extended Support Release</a> (ESR.)</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="https://serviceworke.rs/">The Service Worker Cookbook</a></li> - <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> - <li>Download the <a href="https://mdn.mozillademos.org/files/12638/sw101.png">Service Workers 101 cheatsheet</a>.</li> - <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a></li> - <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li> -</ul> 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 ---- -<div> -<div>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</div> -</div> - -<p><span class="seoSummary">The <code>ServiceWorkerRegistration</code> interface of the <a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a> represents the service worker registration. You register a service worker to control one or more pages that share the same origin.</span></p> - -<p>The lifetime of a service worker registration is beyond that of the <code>ServiceWorkerRegistration</code> objects that represent them within the lifetime of their corresponding service worker clients. The browser maintains a persistent list of active <code>ServiceWorkerRegistration</code> objects.</p> - -<div class="note"> -<p><strong>Note</strong>: This feature is available in <a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers</a>.</p> -</div> - -<h2 id="Properties">Properties</h2> - -<p><em>Also implements properties from its parent interface, </em>{{domxref("EventTarget")}}.</p> - -<dl> - <dt>{{domxref("ServiceWorkerRegistration.scope")}} {{readonlyinline}}</dt> - <dd>Returns a unique identifier for a service worker registration. This must be on the same origin as the document that registers the {{domxref("ServiceWorker")}}.</dd> - <dt>{{domxref("ServiceWorkerRegistration.installing")}} <strong style="font-weight: bold;">{{readonlyinline}}</strong></dt> - <dd>Returns a service worker whose state is <code>installing</code>. This is initially set to <code>null</code>.</dd> - <dt>{{domxref("ServiceWorkerRegistration.waiting")}} <strong style="font-weight: bold;">{{readonlyinline}}</strong></dt> - <dd>Returns a service worker whose state is <code>waiting</code>. This is initially set to <code>null</code>.</dd> - <dt>{{domxref("ServiceWorkerRegistration.active")}} <strong style="font-weight: bold;">{{readonlyinline}}</strong></dt> - <dd>Returns a service worker whose state is either <code>activating</code> or <code>activated</code>. This is initially set to <code>null</code>. An active worker will control a {{domxref("ServiceWorkerClient")}} if the client's URL falls within the scope of the registration (the <code>scope</code> option set when {{domxref("ServiceWorkerContainer.register")}} is first called.)</dd> - <dt>{{domxref("ServiceWorkerRegistration.navigationPreload")}} {{readonlyinline}}</dt> - <dd>Returns the instance of {{domxref("NavigationPreloadManager")}} associated with the current service worker registration.</dd> - <dt>{{domxref("serviceWorkerRegistration.periodicSync")}} {{non-standard_inline}} {{readonlyinline}}</dt> - <dd>Returns a reference to the {{domxref("PeriodicSyncManager")}} interface, which manages periodic background synchronization processes.</dd> - <dt>{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}</dt> - <dd>Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status.</dd> - <dt>{{domxref("ServiceWorkerRegistration.sync")}} <strong style="font-weight: bold; line-height: 19.0909080505371px;">{{non-standard_inline}} </strong>{{readonlyinline}} </dt> - <dd>Returns a reference to the {{domxref("SyncManager")}} interface, which manages background synchronization processes.</dd> -</dl> - -<h3 id="Event_handlers">Event handlers</h3> - -<dl> - <dt>{{domxref("ServiceWorkerRegistration.onupdatefound")}} {{readonlyinline}}</dt> - <dd>An <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventListener" title="This method is called whenever an event occurs of the type for which the EventListener interface was registered."><code>EventListener</code></a> property called whenever an event of type <code>updatefound</code> is fired; it is fired any time the {{domxref("ServiceWorkerRegistration.installing")}} property acquires a new service worker.</dd> -</dl> - -<h2 id="Methods">Methods</h2> - -<p><em>Also implements methods from its parent interface, </em>{{domxref("EventTarget")}}.</p> - -<dl> - <dt>{{domxref("ServiceWorkerRegistration.getNotifications()")}}</dt> - <dd>Returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("Notification")}} objects.</dd> - <dt>{{domxref("ServiceWorkerRegistration.showNotification()")}}</dt> - <dd>Displays the notification with the requested title.</dd> - <dt>{{domxref("ServiceWorkerRegistration.update()")}}</dt> - <dd>Checks the server for an updated version of the service worker without consulting caches.</dd> - <dt>{{domxref("ServiceWorkerRegistration.unregister()")}}</dt> - <dd>Unregisters the service worker registration and returns a {{jsxref("Promise")}}. The service worker will finish any ongoing operations before it is unregistered.</dd> -</dl> - -<h2 id="Examples">Examples</h2> - -<p>In this example, the code first checks whether the browser supports service workers and if so registers one. Next, it adds and <code>updatefound</code> 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 <code>updatefound</code> event will not be fired.</p> - -<pre class="brush: js">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.'); -}</pre> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('Service Workers', '#service-worker-registration-obj', 'ServiceWorkerRegistration')}}</td> - <td>{{Spec2('Service Workers')}}</td> - <td>Initial definition.</td> - </tr> - <tr> - <td>{{SpecName('Push API', '#widl-ServiceWorkerRegistration-pushManager', 'PushManager')}}</td> - <td>{{Spec2('Push API')}}</td> - <td>Adds the {{domxref("PushManager","pushManager")}} property.</td> - </tr> - <tr> - <td>{{SpecName('Web Notifications')}}</td> - <td>{{Spec2('Web Notifications')}}</td> - <td>Adds the {{domxref("ServiceWorkerRegistration.showNotification()","showNotification()")}} method and the {{domxref("ServiceWorkerRegistration.getNotifications()","getNotifications()")}} method.</td> - </tr> - <tr> - <td>{{SpecName('Background Sync')}}</td> - <td>{{Spec2('Background Sync')}}</td> - <td>Adds the {{domxref("ServiceWorkerRegistration.sync","sync")}} property.</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("api.ServiceWorkerRegistration")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li><a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> - <li><a href="https://github.com/mdn/sw-test">Service workers basic code example</a></li> - <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> - <li>{{jsxref("Promise")}}</li> - <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li> -</ul> 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 ---- -<p>{{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") }}</p> - -<p>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.</p> - -<p>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.</p> - -<h2 id="Making_the_square_rotate">Making the square rotate</h2> - -<p>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:</p> - -<pre class="brush: js">var squareRotation = 0.0; -</pre> - -<p>Now we need to update the <code>drawScene()</code> 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:</p> - -<pre class="brush: js">mvPushMatrix(); -mvRotate(squareRotation, [1, 0, 1]); -</pre> - -<p>This saves the current model-view matrix, then rotates the matrix by the current value of <code>squareRotation</code>, around the X and Z axes.</p> - -<p>After drawing, we need to restore the original matrix:</p> - -<pre class="brush: js"> mvPopMatrix(); -</pre> - -<p>We save and restore the original matrix to avoid having this rotation applied to other objects we might draw.</p> - -<p>To actually animate, we need to add code that changes the value of <code>squareRotation</code> over time. We can do that by creating a new variable to track the time at which we last animated (let's call it <code>lastSquareUpdateTime</code>), then adding the following code to the end of the <code>drawScene()</code> function:</p> - -<pre class="brush: js"> var currentTime = (new Date).getTime(); - if (lastSquareUpdateTime) { - var delta = currentTime - lastSquareUpdateTime; - - squareRotation += (30 * delta) / 1000.0; - } - - lastSquareUpdateTime = currentTime; -</pre> - -<p>This code uses the amount of time that's passed since the last time we updated the value of <code>squareRotation</code> to determine how far to rotate the square.</p> - -<h2 id="Making_the_square_move">Making the square move</h2> - -<p>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.</p> - -<p>Let's track offsets to each axis for our translation in new variables:</p> - -<pre class="brush: js">var squareXOffset = 0.0; -var squareYOffset = 0.0; -var squareZOffset = 0.0; -</pre> - -<p>And the amount by which to change our position on each axis in these variables:</p> - -<pre class="brush: js">var xIncValue = 0.2; -var yIncValue = -0.4; -var zIncValue = 0.3; -</pre> - -<p>Now we can simply add this code to the previous code that updates the rotation:</p> - -<pre class="brush: js"> 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; - } -</pre> - -<p>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.</p> - -<p>If your browser supports WebGL, <a href="/samples/webgl/sample4/index.html" title="https://developer.mozilla.org/samples/webgl/sample4/index.html">click here to take a look at this example</a> in action.</p> - -<h2 id="More_matrix_operations">More matrix operations</h2> - -<p>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:</p> - -<pre class="brush: js">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); -} -</pre> - -<p>These routines were borrowed from a sample previously written by Vlad Vukićević.</p> - -<p>{{PreviousNext("Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL", "Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL") }}</p> 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 ---- -<div>{{APIRef}} {{Non-standard_header}}</div> - -<p>Returns a sidebar object, which contains several methods for registering add-ons with the browser.</p> - -<h2 id="Notes" name="Notes">Notes</h2> - -<p>The sidebar object returned has the following methods:</p> - -<table class="fullwidth-table"> - <tbody> - <tr> - <th>Method</th> - <th>Description (SeaMonkey)</th> - <th>Description (Firefox)</th> - </tr> - <tr> - <td><code>addPanel(<var>title</var>, <var>contentURL</var>, "")</code></td> - <td>Adds a sidebar panel.</td> - <td rowspan="2">Obsolete since Firefox 23 (only present in SeaMonkey).<br> - End users can use the "load this bookmark in the sidebar" option instead. Also see <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Creating_a_Firefox_sidebar">Creating a Firefox sidebar.</a></td> - </tr> - <tr> - <td><code>addPersistentPanel(<var>title</var>, <var>contentURL</var>, "")</code></td> - <td>Adds a sidebar panel, which is able to work in the background.</td> - </tr> - <tr> - <td><code>AddSearchProvider(<em>descriptionURL)</em></code></td> - <td colspan="2">Installs a search provider (OpenSearch). <a href="/en-US/docs/Web/API/Window/sidebar/Adding_search_engines_from_Web_pages#Installing_OpenSearch_plugins" title="Adding_search_engines_from_web_pages">Adding OpenSearch search engines </a>contains more details. Added in Firefox 2.</td> - </tr> - <tr> - <td><code>addSearchEngine(<var>engineURL</var>, <var>iconURL</var>, <var>suggestedTitle</var>, <var>suggestedCategory</var>)</code> {{Obsolete_inline(44)}}</td> - <td colspan="2">Installs a search engine (Sherlock). <a href="/en-US/docs/Web/API/Window/sidebar/Adding_search_engines_from_Web_pages#Installing_Sherlock_plugins" title="Adding_search_engines_from_web_pages">Adding Sherlock search engines </a>contains more details.</td> - </tr> - <tr> - <td><code>IsSearchProviderInstalled(<em>descriptionURL)</em></code></td> - <td colspan="2">Indicates if a specific search provider (OpenSearch) is installed.</td> - </tr> - </tbody> -</table> - -<h2 id="Specification" name="Specification">Specification</h2> - -<p>Mozilla-specific. Not part of any standard.</p> 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 ---- -<p>{{ ApiRef() }}</p> -<h3 id="Summary" name="Summary">Test Summary</h3> -<p>The unload event is raised when the document is unloaded.</p> -<h3 id="Syntax" name="Syntax">Syntax</h3> -<pre class="eval">window.onunload = <em>funcRef</em>; -</pre> -<ul> - <li><code>funcRef</code> is a reference to a function.</li> -</ul> -<h3 id="Example" name="Example">Example</h3> -<pre><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> -</pre> -<h3 id="Notes" name="Notes">Notes</h3> -<p>Note that using this event handler in your page prevents Firefox 1.5 from caching the page in the in-memory bfcache. See <a href="/En/Using_Firefox_1.5_caching" title="En/Using_Firefox_1.5_caching">Using Firefox 1.5 caching</a> for details.</p> -<p>Browsers equipped with pop-up window blockers will ignore all window.open() method calls in onunload event handler functions.</p> -<h3 id="Specification" name="Specification">Specification</h3> -<p>{{ DOM0() }}</p> -<p>{{ languages( {"zh-cn": "zh-cn/DOM/window.onunload" } ) }}</p> 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 ---- -<p>{{APIRef("XMLHttpRequest")}}</p> - -<p><code>XMLHttpRequestEventTarget</code> is the interface that describes the event handlers you can implement in an object that will handle events for an {{ domxref("XMLHttpRequest") }}.</p> - -<p>{{InheritanceDiagram}}</p> - -<h2 id="Properties">Properties</h2> - -<dl> - <dt>{{ domxref("XMLHttpRequestEventTarget.onabort") }}</dt> - <dd>Contains the function to call when a request is aborted and the {{event('abort')}} event is received by this object.</dd> - <dt>{{ domxref("XMLHttpRequestEventTarget.onerror") }}</dt> - <dd>Contains the function to call when a request encounters an error and the {{event('error')}} event is received by this object.</dd> - <dt>{{ domxref("XMLHttpRequestEventTarget.onload") }}</dt> - <dd>Contains the function to call when an HTTP request returns after successfully fetching content and the {{event('load')}} event is received by this object.</dd> - <dt>{{ domxref("XMLHttpRequestEventTarget.onloadstart") }}</dt> - <dd>Contains the function that gets called when the HTTP request first begins loading data and the {{event('loadstart')}} event is received by this object.</dd> - <dt>{{ domxref("XMLHttpRequestEventTarget.onprogress") }}</dt> - <dd>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.</dd> - <dt>{{ domxref("XMLHttpRequestEventTarget.ontimeout") }}</dt> - <dd>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 <code>XMLHttpRequest</code> object's <code>timeout</code> attribute.</dd> - <dt>{{ domxref("XMLHttpRequestEventTarget.onloadend") }}</dt> - <dd>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.</dd> -</dl> - -<h2 id="Specifications">Specifications</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('XMLHttpRequest')}}</td> - <td>{{Spec2('XMLHttpRequest')}}</td> - <td>WHATWG living standard</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("api.XMLHttpRequestEventTarget")}}</p> - -<h2 id="See_also">See also</h2> - -<ul> - <li>{{ domxref("XMLHttpRequest") }}</li> - <li><a href="/en/DOM/XMLHttpRequest/Using_XMLHttpRequest" title="Using XMLHttpRequest">Using XMLHttpRequest</a></li> -</ul> 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 ---- -<div>{{APIRef("XMLHttpRequest")}}</div> - -<p>El evento <strong><code>XMLHttpRequestEventTarget.onload</code> </strong>es la función que se llama cuando una transacción del {{domxref("XMLHttpRequest")}} es ejecutada correctamente.</p> - -<h2 id="Syntax" name="Syntax">Sintaxis</h2> - -<pre class="syntaxbox"><em>XMLHttpRequest</em>.onload = <em>callback</em>;</pre> - -<h3 id="Valores"> Valores</h3> - -<ul> - <li><code><em>callback</em></code> is the function to be executed when the request completes successfully. It receives a {{domxref("ProgressEvent")}} object as its first argument. The value of <em>this</em> (i.e. the context) is the same {{domxref("XMLHttpRequest")}} this callback is related to.</li> - <li><code><em>callback</em></code> es la función a ser ejecutada cuando la petición se complete. Ésta recive un objeto {{domxref("ProgressEvent")}} como su primer argumento. El valor de esto (ej: el contexto) es el mismo {{domxref("XMLHttpRequest")}} al que el callback está relacionado.</li> -</ul> - -<h2 id="Example" name="Example">Ejemplo</h2> - -<pre class="brush: js">var xmlhttp = new XMLHttpRequest(), - method = 'GET', - url = 'https://developer.mozilla.org/'; - -xmlhttp.open(<em>method</em>, <em>url</em>, true); -xmlhttp.onload = function () { - // Hacer algo con la información recivida ( found in xmlhttp.response ) -}; -xmlhttp.send(); -</pre> - -<h2 id="Especificaciones">Especificaciones</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('XMLHttpRequest', '#handler-xhr-onload')}}</td> - <td>{{Spec2('XMLHttpRequest')}}</td> - <td>WHATWG living standard</td> - </tr> - </tbody> -</table> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("api.XMLHttpRequestEventTarget.onload")}}</p> |