From 3601b7bb982e958927e069715cfe07430bce7196 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Thu, 15 Jul 2021 12:59:34 -0400 Subject: delete pages that were never translated from en-US (es, part 1) (#1547) --- files/es/_redirects.txt | 20 - files/es/_wikihistory.json | 349 ----- files/es/games/techniques/3d_on_the_web/index.html | 113 -- .../es/learn/css/css_layout/positioning/index.html | 469 ------- .../client-side_web_apis/fetching_data/index.html | 373 ------ .../server-side/express_nodejs/mongoose/index.html | 801 ------------ .../vue_getting_started/index.html | 295 ----- .../howto/document_a_css_property/index.html | 82 -- .../webextensions/api/webnavigation/index.html | 144 --- .../extending_the_developer_tools/index.html | 159 --- .../webextensions/internationalization/index.html | 405 ------ files/es/mozilla/firefox/releases/62/index.html | 235 ---- files/es/mozilla/firefox/releases/67/index.html | 198 --- files/es/mozilla/firefox/releases/68/index.html | 233 ---- .../tutorial/applying_styles_and_colors/index.html | 727 ----------- files/es/web/api/constraint_validation/index.html | 154 --- .../es/web/api/cssrule/parentstylesheet/index.html | 27 - files/es/web/api/datatransfer/index.html | 376 ------ files/es/web/api/document/evaluate/index.html | 211 ---- files/es/web/api/element/shadowroot/index.html | 83 -- files/es/web/api/file/type/index.html | 72 -- .../onloadedmetadata/index.html | 48 - files/es/web/api/history_api/example/index.html | 416 ------ .../getdistributednodes/index.html | 95 -- files/es/web/api/htmlcontentelement/index.html | 110 -- .../web/api/htmlcontentelement/select/index.html | 95 -- files/es/web/api/htmlelement/innertext/index.html | 84 -- files/es/web/api/htmlhtmlelement/index.html | 121 -- .../api/htmlmediaelement/abort_event/index.html | 69 - .../api/keyboardevent/getmodifierstate/index.html | 253 ---- files/es/web/api/keyboardevent/key/index.html | 212 ---- files/es/web/api/navigator/mediadevices/index.html | 49 - .../web/api/pushmanager/permissionstate/index.html | 111 -- files/es/web/api/range/intersectsnode/index.html | 48 - .../using_service_workers/index.html | 526 -------- .../web/api/serviceworkerregistration/index.html | 145 --- .../animating_objects_with_webgl/index.html | 119 -- files/es/web/api/window/sidebar/index.html | 56 - .../api/windoweventhandlers/onunload/index.html | 46 - .../web/api/xmlhttprequesteventtarget/index.html | 68 - .../xmlhttprequesteventtarget/onload/index.html | 55 - files/es/web/css/@viewport/index.html | 159 --- .../css_grid_layout_and_accessibility/index.html | 169 --- files/es/web/css/max-width/index.html | 158 --- .../errors/corsnotsupportingcredentials/index.html | 34 - .../es/web/http/headers/accept-charset/index.html | 85 -- files/es/web/http/status/301/index.html | 54 - .../the_legacy_iterator_protocol/index.html | 74 -- .../reference/errors/precision_range/index.html | 96 -- .../global_objects/date/getutchours/index.html | 118 -- .../global_objects/math/fround/index.html | 198 --- .../object/__lookupgetter__/index.html | 85 -- files/es/web/media/formats/containers/index.html | 1329 -------------------- .../web/performance/how_browsers_work/index.html | 208 --- .../tutorial/svg_in_html_introduction/index.html | 95 -- 55 files changed, 11114 deletions(-) delete mode 100644 files/es/games/techniques/3d_on_the_web/index.html delete mode 100644 files/es/learn/css/css_layout/positioning/index.html delete mode 100644 files/es/learn/javascript/client-side_web_apis/fetching_data/index.html delete mode 100644 files/es/learn/server-side/express_nodejs/mongoose/index.html delete mode 100644 files/es/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.html delete mode 100644 files/es/mdn/contribute/howto/document_a_css_property/index.html delete mode 100644 files/es/mozilla/add-ons/webextensions/api/webnavigation/index.html delete mode 100644 files/es/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html delete mode 100644 files/es/mozilla/add-ons/webextensions/internationalization/index.html delete mode 100644 files/es/mozilla/firefox/releases/62/index.html delete mode 100644 files/es/mozilla/firefox/releases/67/index.html delete mode 100644 files/es/mozilla/firefox/releases/68/index.html delete mode 100644 files/es/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html delete mode 100644 files/es/web/api/constraint_validation/index.html delete mode 100644 files/es/web/api/cssrule/parentstylesheet/index.html delete mode 100644 files/es/web/api/datatransfer/index.html delete mode 100644 files/es/web/api/document/evaluate/index.html delete mode 100644 files/es/web/api/element/shadowroot/index.html delete mode 100644 files/es/web/api/file/type/index.html delete mode 100644 files/es/web/api/globaleventhandlers/onloadedmetadata/index.html delete mode 100644 files/es/web/api/history_api/example/index.html delete mode 100644 files/es/web/api/htmlcontentelement/getdistributednodes/index.html delete mode 100644 files/es/web/api/htmlcontentelement/index.html delete mode 100644 files/es/web/api/htmlcontentelement/select/index.html delete mode 100644 files/es/web/api/htmlelement/innertext/index.html delete mode 100644 files/es/web/api/htmlhtmlelement/index.html delete mode 100644 files/es/web/api/htmlmediaelement/abort_event/index.html delete mode 100644 files/es/web/api/keyboardevent/getmodifierstate/index.html delete mode 100644 files/es/web/api/keyboardevent/key/index.html delete mode 100644 files/es/web/api/navigator/mediadevices/index.html delete mode 100644 files/es/web/api/pushmanager/permissionstate/index.html delete mode 100644 files/es/web/api/range/intersectsnode/index.html delete mode 100644 files/es/web/api/service_worker_api/using_service_workers/index.html delete mode 100644 files/es/web/api/serviceworkerregistration/index.html delete mode 100644 files/es/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html delete mode 100644 files/es/web/api/window/sidebar/index.html delete mode 100644 files/es/web/api/windoweventhandlers/onunload/index.html delete mode 100644 files/es/web/api/xmlhttprequesteventtarget/index.html delete mode 100644 files/es/web/api/xmlhttprequesteventtarget/onload/index.html delete mode 100644 files/es/web/css/@viewport/index.html delete mode 100644 files/es/web/css/css_grid_layout/css_grid_layout_and_accessibility/index.html delete mode 100644 files/es/web/css/max-width/index.html delete mode 100644 files/es/web/http/cors/errors/corsnotsupportingcredentials/index.html delete mode 100644 files/es/web/http/headers/accept-charset/index.html delete mode 100644 files/es/web/http/status/301/index.html delete mode 100644 files/es/web/javascript/reference/deprecated_and_obsolete_features/the_legacy_iterator_protocol/index.html delete mode 100644 files/es/web/javascript/reference/errors/precision_range/index.html delete mode 100644 files/es/web/javascript/reference/global_objects/date/getutchours/index.html delete mode 100644 files/es/web/javascript/reference/global_objects/math/fround/index.html delete mode 100644 files/es/web/javascript/reference/global_objects/object/__lookupgetter__/index.html delete mode 100644 files/es/web/media/formats/containers/index.html delete mode 100644 files/es/web/performance/how_browsers_work/index.html delete mode 100644 files/es/web/svg/tutorial/svg_in_html_introduction/index.html (limited to 'files/es') diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index 6973e1efe2..8783b96121 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -111,7 +111,6 @@ /es/docs/CSS/list-style-type /es/docs/Web/CSS/list-style-type /es/docs/CSS/margin-right /es/docs/Web/CSS/margin-right /es/docs/CSS/max-height /es/docs/Web/CSS/max-height -/es/docs/CSS/max-width /es/docs/Web/CSS/max-width /es/docs/CSS/min-height /es/docs/Web/CSS/min-height /es/docs/CSS/min-width /es/docs/Web/CSS/min-width /es/docs/CSS/none /es/docs/Web/CSS/float @@ -185,7 +184,6 @@ /es/docs/CSS:list-style-type /es/docs/Web/CSS/list-style-type /es/docs/CSS:margin-right /es/docs/Web/CSS/margin-right /es/docs/CSS:max-height /es/docs/Web/CSS/max-height -/es/docs/CSS:max-width /es/docs/Web/CSS/max-width /es/docs/CSS:min-height /es/docs/Web/CSS/min-height /es/docs/CSS:min-width /es/docs/Web/CSS/min-width /es/docs/CSS:none /es/docs/Web/CSS/float @@ -231,14 +229,12 @@ /es/docs/DOM/CameraCapabilities.flashModes /es/docs/Web/API/CameraCapabilities/flashModes /es/docs/DOM/CssRule /es/docs/Web/API/CSSRule /es/docs/DOM/CssRule.cssText /es/docs/Web/API/CSSRule/cssText -/es/docs/DOM/CssRule.parentStyleSheet /es/docs/Web/API/CSSRule/parentStyleSheet /es/docs/DOM/CssRule.selectorText /es/docs/Web/API/CSSStyleRule/selectorText /es/docs/DOM/Document.styleSheets /es/docs/Web/API/Document/styleSheets /es/docs/DOM/Element.setAttribute /es/docs/Web/API/Element/setAttribute /es/docs/DOM/HTMLAudioElement /es/docs/Web/API/HTMLAudioElement /es/docs/DOM/HTMLTableElement /es/docs/Web/API/HTMLTableElement /es/docs/DOM/Manipulando_el_historial_del_navegador /es/docs/Web/API/History_API -/es/docs/DOM/Manipulando_el_historial_del_navegador/Ejemplo /es/docs/Web/API/History_API/Example /es/docs/DOM/Manipulating_the_browser_history /es/docs/Web/API/History_API /es/docs/DOM/MozSocial.closePanel /es/docs/Web/API/MozSocial/closePanel /es/docs/DOM/MozSocial.getAttention /es/docs/Web/API/MozSocial/getAttention @@ -327,7 +323,6 @@ /es/docs/DOM/range /es/docs/Web/API/Range /es/docs/DOM/range.collapsed /es/docs/Web/API/Range/collapsed /es/docs/DOM/range.commonAncestorContainer /es/docs/Web/API/Range/commonAncestorContainer -/es/docs/DOM/range.intersectsNode /es/docs/Web/API/Range/intersectsNode /es/docs/DOM/style /es/docs/Web/API/HTMLStyleElement /es/docs/DOM/table /es/docs/Web/API/HTMLTableElement /es/docs/DOM/window /es/docs/Web/API/Window @@ -338,7 +333,6 @@ /es/docs/DOM/window.navigator.registerProtocolHandler /es/docs/Web/API/Navigator/registerProtocolHandler /es/docs/DOM/window.navigator.vibrate /es/docs/Web/API/Navigator/vibrate /es/docs/DOM/window.onload /es/docs/Web/API/GlobalEventHandlers/onload -/es/docs/DOM/window.onunload /es/docs/Web/API/WindowEventHandlers/onunload /es/docs/DOM/window.requestAnimationFrame /es/docs/Web/API/Window/requestAnimationFrame /es/docs/DOM:Selection:addRange /es/docs/Web/API/Selection/addRange /es/docs/DOM:Selection:anchorNode /es/docs/Web/API/Selection/anchorNode @@ -395,7 +389,6 @@ /es/docs/DOM:range /es/docs/Web/API/Range /es/docs/DOM:range.collapsed /es/docs/Web/API/Range/collapsed /es/docs/DOM:range.commonAncestorContainer /es/docs/Web/API/Range/commonAncestorContainer -/es/docs/DOM:range.intersectsNode /es/docs/Web/API/Range/intersectsNode /es/docs/DOM:selection /es/docs/Web/API/Selection /es/docs/DOM:style /es/docs/Web/API/HTMLStyleElement /es/docs/DOM:table /es/docs/Web/API/HTMLTableElement @@ -1243,7 +1236,6 @@ /es/docs/Learn/Herramientas_y_pruebas/GitHub /es/docs/Learn/Tools_and_testing/GitHub /es/docs/Learn/Herramientas_y_pruebas/Lado-del-cliente_JavaScript_frameworks /es/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks /es/docs/Learn/Herramientas_y_pruebas/Lado-del-cliente_JavaScript_frameworks/React_getting_started /es/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started -/es/docs/Learn/Herramientas_y_pruebas/Lado-del-cliente_JavaScript_frameworks/Vue_primeros_pasos /es/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started /es/docs/Learn/Herramientas_y_pruebas/Understanding_client-side_tools /es/docs/Learn/Tools_and_testing/Understanding_client-side_tools /es/docs/Learn/JavaScript/Building_blocks/Bucle_codigo /es/docs/Learn/JavaScript/Building_blocks/Looping_code /es/docs/Learn/JavaScript/Building_blocks/Construyendo_tu_propia_funcion /es/docs/Learn/JavaScript/Building_blocks/Build_your_own_function @@ -1554,7 +1546,6 @@ /es/docs/SVG /es/docs/Web/SVG /es/docs/SVG/Tutorial /es/docs/Web/SVG/Tutorial /es/docs/SVG/Tutorial/Getting_Started /es/docs/Web/SVG/Tutorial/Getting_Started -/es/docs/SVG_In_HTML_Introduction /es/docs/Web/SVG/Tutorial/SVG_In_HTML_Introduction /es/docs/SVG_en_Firefox /es/docs/Web/SVG/SVG_1.1_Support_in_Firefox /es/docs/Screening_duplicate_bugs /es/docs/QA/Screening_duplicate_bugs /es/docs/Seguridad_en_Firefox_2 /es/docs/Mozilla/Firefox/Releases/2/Security_changes @@ -1637,7 +1628,6 @@ /es/docs/Web/API/Geolocation.clearWatch /es/docs/Web/API/Geolocation/clearWatch /es/docs/Web/API/Geolocation.getCurrentPosition /es/docs/Web/API/Geolocation/getCurrentPosition /es/docs/Web/API/Geolocation.watchPosition /es/docs/Web/API/Geolocation/watchPosition -/es/docs/Web/API/GlobalEventHandlers/onunload /es/docs/Web/API/WindowEventHandlers/onunload /es/docs/Web/API/HTMLElement/focus /es/docs/orphaned/Web/API/HTMLOrForeignElement/focus /es/docs/Web/API/HTMLElement/invalid_event /es/docs/Web/API/HTMLInputElement/invalid_event /es/docs/Web/API/HTMLOrForeignElement/focus /es/docs/orphaned/Web/API/HTMLOrForeignElement/focus @@ -1663,7 +1653,6 @@ /es/docs/Web/API/Position /es/docs/Web/API/GeolocationPosition /es/docs/Web/API/RandomSource/Obtenervaloresaleatorios /es/docs/Web/API/Crypto/getRandomValues /es/docs/Web/API/SubtleCrypto/encrypt /es/docs/Web/HTTP/Headers/Digest -/es/docs/Web/API/WebGL_API/Animating_objects_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL /es/docs/Web/API/WebGL_API/Getting_started_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Objetos_3D_utilizando_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Wtilizando_texturas_en_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL @@ -1803,7 +1792,6 @@ /es/docs/Web/CSS/transform-function/translateZ /es/docs/Web/CSS/transform-function/translateZ() /es/docs/Web/CSS/var /es/docs/Web/CSS/var() /es/docs/Web/Events/DOMContentLoaded /es/docs/Web/API/Window/DOMContentLoaded_event -/es/docs/Web/Events/abort /es/docs/Web/API/HTMLMediaElement/abort_event /es/docs/Web/Events/animationend /es/docs/Web/API/HTMLElement/animationend_event /es/docs/Web/Events/beforeunload /es/docs/Web/API/Window/beforeunload_event /es/docs/Web/Events/blur /es/docs/Web/API/Element/blur_event @@ -1832,7 +1820,6 @@ /es/docs/Web/Guide/HTML /es/docs/Learn/HTML /es/docs/Web/Guide/HTML/Canvas_tutorial /es/docs/Web/API/Canvas_API/Tutorial /es/docs/Web/Guide/HTML/Canvas_tutorial/Advanced_animations /es/docs/Web/API/Canvas_API/Tutorial/Advanced_animations -/es/docs/Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors /es/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors /es/docs/Web/Guide/HTML/Canvas_tutorial/Basic_animations /es/docs/Web/API/Canvas_API/Tutorial/Basic_animations /es/docs/Web/Guide/HTML/Canvas_tutorial/Basic_usage /es/docs/Web/API/Canvas_API/Tutorial/Basic_usage /es/docs/Web/Guide/HTML/Canvas_tutorial/Dibujando_formas /es/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes @@ -2160,7 +2147,6 @@ /es/docs/Web/JavaScript/Referencia /es/docs/Web/JavaScript/Reference /es/docs/Web/JavaScript/Referencia/Acerca_de /es/docs/Web/JavaScript/Reference/About /es/docs/Web/JavaScript/Referencia/Características_Desaprobadas /es/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features -/es/docs/Web/JavaScript/Referencia/Características_Desaprobadas/The_legacy_Iterator_protocol /es/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol /es/docs/Web/JavaScript/Referencia/Características_Despreciadas /es/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features /es/docs/Web/JavaScript/Referencia/Classes /es/docs/Web/JavaScript/Reference/Classes /es/docs/Web/JavaScript/Referencia/Classes/Class_fields /es/docs/Web/JavaScript/Reference/Classes/Public_class_fields @@ -2256,7 +2242,6 @@ /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/getSeconds /es/docs/Web/JavaScript/Reference/Global_Objects/Date/getSeconds /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/getTime /es/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/getUTCFullYear /es/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear -/es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/getUTCHours /es/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/now /es/docs/Web/JavaScript/Reference/Global_Objects/Date/now /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/parse /es/docs/Web/JavaScript/Reference/Global_Objects/Date/parse /es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/setFullYear /es/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear @@ -2327,7 +2312,6 @@ /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/exp /es/docs/Web/JavaScript/Reference/Global_Objects/Math/exp /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/expm1 /es/docs/Web/JavaScript/Reference/Global_Objects/Math/expm1 /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/floor /es/docs/Web/JavaScript/Reference/Global_Objects/Math/floor -/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/fround /es/docs/Web/JavaScript/Reference/Global_Objects/Math/fround /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/hypot /es/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/log /es/docs/Web/JavaScript/Reference/Global_Objects/Math/log /es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/log10 /es/docs/Web/JavaScript/Reference/Global_Objects/Math/log10 @@ -2366,7 +2350,6 @@ /es/docs/Web/JavaScript/Referencia/Objetos_globales/NumberFormat/format /es/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/format /es/docs/Web/JavaScript/Referencia/Objetos_globales/Object /es/docs/Web/JavaScript/Reference/Global_Objects/Object /es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/__defineGetter__ /es/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__ -/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/__lookupGetter__ /es/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__ /es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/assign /es/docs/Web/JavaScript/Reference/Global_Objects/Object/assign /es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/constructor /es/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor /es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/create /es/docs/Web/JavaScript/Reference/Global_Objects/Object/create @@ -2593,7 +2576,6 @@ /es/docs/Web/Reference/Events /es/docs/Web/Events /es/docs/Web/Reference/Events/DOMContentLoaded /es/docs/Web/API/Window/DOMContentLoaded_event /es/docs/Web/Reference/Events/DOMSubtreeModified /es/docs/Web/Events/DOMSubtreeModified -/es/docs/Web/Reference/Events/abort /es/docs/Web/API/HTMLMediaElement/abort_event /es/docs/Web/Reference/Events/animationend /es/docs/Web/API/HTMLElement/animationend_event /es/docs/Web/Reference/Events/beforeunload /es/docs/Web/API/Window/beforeunload_event /es/docs/Web/Reference/Events/blur /es/docs/Web/API/Element/blur_event @@ -2619,7 +2601,6 @@ /es/docs/Web/Security/Securing_your_site/desactivar_autocompletado_formulario /es/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion /es/docs/Web/Tutoriales /es/docs/Web/Tutorials /es/docs/Web/WebGL /es/docs/Web/API/WebGL_API -/es/docs/Web/WebGL/Animating_objects_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL /es/docs/Web/WebGL/Getting_started_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL /es/docs/Web/XML/Introducción_a_XML /es/docs/Web/XML/XML_introduction /es/docs/Web/XPath/Ejes /es/docs/Web/XPath/Axes @@ -2668,7 +2649,6 @@ /es/docs/WebAPI/Pointer_Lock /es/docs/Web/API/Pointer_Lock_API /es/docs/WebAPI/Using_geolocation /es/docs/Web/API/Geolocation_API /es/docs/WebGL /es/docs/Web/API/WebGL_API -/es/docs/WebGL/Animating_objects_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL /es/docs/WebRTC/Introduction /es/docs/Web/API/WebRTC_API/Session_lifetime /es/docs/WebRTC/MediaStream_API /es/docs/Web/API/Media_Streams_API /es/docs/WebRTC/Peer-to-peer_communications_with_WebRTC /es/docs/Web/Guide/API/WebRTC/Peer-to-peer_communications_with_WebRTC diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index 0b33de87c6..e87c40ab52 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -76,12 +76,6 @@ "SuperHostile" ] }, - "Games/Techniques/3D_on_the_web": { - "modified": "2019-03-18T21:23:46.780Z", - "contributors": [ - "wbamberg" - ] - }, "Games/Techniques/WebRTC_data_channels": { "modified": "2019-03-23T22:04:08.435Z", "contributors": [ @@ -2067,12 +2061,6 @@ "editorUOC" ] }, - "Learn/CSS/CSS_layout/Positioning": { - "modified": "2020-07-16T22:26:42.380Z", - "contributors": [ - "fr3dth" - ] - }, "Learn/CSS/CSS_layout/Responsive_Design": { "modified": "2020-07-16T22:27:27.257Z", "contributors": [ @@ -3080,12 +3068,6 @@ "Enesimus" ] }, - "Learn/JavaScript/Client-side_web_APIs/Fetching_data": { - "modified": "2020-07-16T22:32:57.121Z", - "contributors": [ - "Dsabillon" - ] - }, "Learn/JavaScript/Client-side_web_APIs/Introduction": { "modified": "2020-07-16T22:32:44.249Z", "contributors": [ @@ -3632,13 +3614,6 @@ "maringenio" ] }, - "Learn/Server-side/Express_Nodejs/mongoose": { - "modified": "2020-07-16T22:38:20.335Z", - "contributors": [ - "danimrprofe", - "rmon_vfer" - ] - }, "Learn/Server-side/Express_Nodejs/skeleton_website": { "modified": "2020-07-16T22:38:03.936Z", "contributors": [ @@ -3712,12 +3687,6 @@ "spaceinvadev" ] }, - "Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started": { - "modified": "2020-09-17T18:53:24.146Z", - "contributors": [ - "Faem0220" - ] - }, "Learn/Tools_and_testing/Cross_browser_testing": { "modified": "2020-07-16T22:38:59.665Z", "contributors": [ @@ -3857,17 +3826,6 @@ "LeoHirsch" ] }, - "MDN/Contribute/Howto/Document_a_CSS_property": { - "modified": "2020-02-19T19:43:18.253Z", - "contributors": [ - "jswisher", - "SphinxKnight", - "wbamberg", - "teoli", - "stephaniehobson", - "MauricioGil" - ] - }, "MDN/Contribute/Howto/Tag": { "modified": "2019-03-23T23:15:01.953Z", "contributors": [ @@ -4096,13 +4054,6 @@ "grxdipgra" ] }, - "Mozilla/Add-ons/WebExtensions/API/webNavigation": { - "modified": "2020-10-15T21:52:47.862Z", - "contributors": [ - "wbamberg", - "tanclony" - ] - }, "Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar": { "modified": "2019-03-18T21:05:11.701Z", "contributors": [ @@ -4138,12 +4089,6 @@ "hecaxmmx" ] }, - "Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools": { - "modified": "2020-09-27T05:32:44.293Z", - "contributors": [ - "omaralonsog" - ] - }, "Mozilla/Add-ons/WebExtensions/Implement_a_settings_page": { "modified": "2019-03-18T21:06:46.901Z", "contributors": [ @@ -4158,12 +4103,6 @@ "hecaxmmx" ] }, - "Mozilla/Add-ons/WebExtensions/Internationalization": { - "modified": "2020-06-29T22:25:32.104Z", - "contributors": [ - "hugojavierduran9" - ] - }, "Mozilla/Add-ons/WebExtensions/Modify_a_web_page": { "modified": "2019-03-18T21:02:55.354Z", "contributors": [ @@ -4490,12 +4429,6 @@ "JoaLop" ] }, - "Mozilla/Firefox/Releases/62": { - "modified": "2019-03-18T21:26:40.295Z", - "contributors": [ - "laptou" - ] - }, "Mozilla/Firefox/Releases/63": { "modified": "2019-03-18T21:22:18.650Z", "contributors": [ @@ -4509,19 +4442,6 @@ "Smartloony" ] }, - "Mozilla/Firefox/Releases/67": { - "modified": "2019-06-27T23:25:44.498Z", - "contributors": [ - "erickton", - "marcorichetta" - ] - }, - "Mozilla/Firefox/Releases/68": { - "modified": "2019-07-14T03:15:02.367Z", - "contributors": [ - "Gummox" - ] - }, "Mozilla/Firefox/Releases/9": { "modified": "2019-12-13T20:33:17.732Z", "contributors": [ @@ -5209,15 +5129,6 @@ "HenryGR" ] }, - "Web/API/CSSRule/parentStyleSheet": { - "modified": "2019-03-23T23:58:10.522Z", - "contributors": [ - "fscholz", - "arunpandianp", - "teoli", - "HenryGR" - ] - }, "Web/API/CSSStyleDeclaration": { "modified": "2019-03-23T22:44:46.721Z", "contributors": [ @@ -5410,12 +5321,6 @@ "elagat" ] }, - "Web/API/Canvas_API/Tutorial/Applying_styles_and_colors": { - "modified": "2020-05-15T18:35:37.655Z", - "contributors": [ - "dimaio77" - ] - }, "Web/API/Canvas_API/Tutorial/Basic_animations": { "modified": "2019-10-10T16:52:52.102Z", "contributors": [ @@ -5603,9 +5508,6 @@ "oderflaj" ] }, - "Web/API/Constraint_validation": { - "modified": "2019-04-22T15:33:44.796Z" - }, "Web/API/Crypto": { "modified": "2020-10-15T22:27:12.417Z", "contributors": [ @@ -5671,16 +5573,6 @@ "Nachec" ] }, - "Web/API/DataTransfer": { - "modified": "2019-03-23T23:17:03.398Z", - "contributors": [ - "wbamberg", - "nmarmon", - "vmv", - "fscholz", - "yonatanalexis22" - ] - }, "Web/API/DeviceMotionEvent": { "modified": "2020-10-15T22:22:26.832Z", "contributors": [ @@ -5919,12 +5811,6 @@ "iarah" ] }, - "Web/API/Document/evaluate": { - "modified": "2019-03-23T22:10:41.891Z", - "contributors": [ - "bryan3561" - ] - }, "Web/API/Document/execCommand": { "modified": "2019-03-23T22:59:11.227Z", "contributors": [ @@ -6586,12 +6472,6 @@ "SoftwareRVG" ] }, - "Web/API/Element/shadowRoot": { - "modified": "2020-10-15T22:21:04.049Z", - "contributors": [ - "quintero_japon" - ] - }, "Web/API/Element/tagName": { "modified": "2019-03-23T23:53:26.081Z", "contributors": [ @@ -6867,12 +6747,6 @@ "BrodaNoel" ] }, - "Web/API/File/type": { - "modified": "2020-10-15T22:26:46.640Z", - "contributors": [ - "IsraelFloresDGA" - ] - }, "Web/API/File/webkitRelativePath": { "modified": "2019-03-23T22:06:35.128Z", "contributors": [ @@ -7123,12 +6997,6 @@ "ehecatl" ] }, - "Web/API/GlobalEventHandlers/onloadedmetadata": { - "modified": "2020-10-15T22:34:40.071Z", - "contributors": [ - "winxde" - ] - }, "Web/API/GlobalEventHandlers/onlostpointercapture": { "modified": "2019-03-23T22:25:49.190Z", "contributors": [ @@ -7242,24 +7110,6 @@ "djrm" ] }, - "Web/API/HTMLContentElement": { - "modified": "2019-03-23T22:10:28.345Z", - "contributors": [ - "dkocho4" - ] - }, - "Web/API/HTMLContentElement/getDistributedNodes": { - "modified": "2019-03-23T22:10:26.488Z", - "contributors": [ - "dkocho4" - ] - }, - "Web/API/HTMLContentElement/select": { - "modified": "2019-03-23T22:10:36.116Z", - "contributors": [ - "dkocho4" - ] - }, "Web/API/HTMLDivElement": { "modified": "2019-03-23T22:03:41.348Z", "contributors": [ @@ -7307,12 +7157,6 @@ "lauramacdaleno" ] }, - "Web/API/HTMLElement/innerText": { - "modified": "2020-10-15T22:31:46.481Z", - "contributors": [ - "hugojavierduran9" - ] - }, "Web/API/HTMLElement/input_event": { "modified": "2020-10-15T22:17:41.989Z", "contributors": [ @@ -7395,12 +7239,6 @@ "jhonarielgj" ] }, - "Web/API/HTMLHtmlElement": { - "modified": "2019-03-23T22:27:47.579Z", - "contributors": [ - "raecillacastellana" - ] - }, "Web/API/HTMLImageElement": { "modified": "2019-03-23T22:42:00.195Z", "contributors": [ @@ -7456,15 +7294,6 @@ "mannypinillo" ] }, - "Web/API/HTMLMediaElement/abort_event": { - "modified": "2019-04-30T13:47:43.431Z", - "contributors": [ - "wbamberg", - "ExE-Boss", - "fscholz", - "balboag" - ] - }, "Web/API/HTMLMediaElement/canplay_event": { "modified": "2019-03-18T20:49:26.430Z", "contributors": [ @@ -7650,12 +7479,6 @@ "translatoon" ] }, - "Web/API/History_API/Example": { - "modified": "2019-03-23T22:29:32.414Z", - "contributors": [ - "maitret" - ] - }, "Web/API/IDBCursor": { "modified": "2019-09-04T06:41:50.466Z", "contributors": [ @@ -7759,19 +7582,6 @@ "pablodonoso" ] }, - "Web/API/KeyboardEvent/getModifierState": { - "modified": "2020-10-15T22:04:42.428Z", - "contributors": [ - "leoderja" - ] - }, - "Web/API/KeyboardEvent/key": { - "modified": "2020-10-15T22:10:09.653Z", - "contributors": [ - "isaacanet", - "aleju92" - ] - }, "Web/API/KeyboardEvent/metaKey": { "modified": "2019-03-23T22:47:47.329Z", "contributors": [ @@ -7970,12 +7780,6 @@ "maedca" ] }, - "Web/API/Navigator/mediaDevices": { - "modified": "2020-12-11T22:18:56.380Z", - "contributors": [ - "daniellimabel" - ] - }, "Web/API/Navigator/registerProtocolHandler": { "modified": "2019-03-23T23:53:04.318Z", "contributors": [ @@ -8271,12 +8075,6 @@ "chrisdavidmills" ] }, - "Web/API/PushManager/permissionState": { - "modified": "2019-03-23T22:39:59.979Z", - "contributors": [ - "maedca" - ] - }, "Web/API/PushManager/supportedContentEncodings": { "modified": "2020-10-15T22:03:55.545Z", "contributors": [ @@ -8344,15 +8142,6 @@ "edhzsz" ] }, - "Web/API/Range/intersectsNode": { - "modified": "2019-03-23T23:53:59.214Z", - "contributors": [ - "fscholz", - "khalid32", - "Mgjbot", - "DR" - ] - }, "Web/API/Range/setStart": { "modified": "2019-03-23T22:13:01.685Z", "contributors": [ @@ -8595,12 +8384,6 @@ "marc2684" ] }, - "Web/API/ServiceWorkerRegistration": { - "modified": "2020-10-15T22:05:45.607Z", - "contributors": [ - "ExE-Boss" - ] - }, "Web/API/Service_Worker_API": { "modified": "2019-03-23T22:09:38.478Z", "contributors": [ @@ -8611,16 +8394,6 @@ "chrisdavidmills" ] }, - "Web/API/Service_Worker_API/Using_Service_Workers": { - "modified": "2019-03-23T22:09:43.848Z", - "contributors": [ - "JasonGlez", - "Vergara", - "GabrielSchlomo", - "Anibalismo", - "darioperez" - ] - }, "Web/API/Storage": { "modified": "2019-03-23T22:37:04.835Z", "contributors": [ @@ -8891,14 +8664,6 @@ "COBRILL4" ] }, - "Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL": { - "modified": "2019-03-23T23:20:38.388Z", - "contributors": [ - "fscholz", - "teoli", - "luziiann" - ] - }, "Web/API/WebGL_API/Tutorial/Animating_textures_in_WebGL": { "modified": "2019-03-23T22:34:48.400Z", "contributors": [ @@ -9480,12 +9245,6 @@ "Grijander81" ] }, - "Web/API/Window/sidebar": { - "modified": "2019-03-23T22:02:56.395Z", - "contributors": [ - "IsaacSchemm" - ] - }, "Web/API/Window/statusbar": { "modified": "2019-03-23T22:14:36.556Z", "contributors": [ @@ -9520,14 +9279,6 @@ "jccuevas" ] }, - "Web/API/WindowEventHandlers/onunload": { - "modified": "2019-03-23T23:39:28.498Z", - "contributors": [ - "fscholz", - "khalid32", - "Sheppy" - ] - }, "Web/API/WindowOrWorkerGlobalScope": { "modified": "2019-03-23T22:16:40.400Z", "contributors": [ @@ -9706,15 +9457,6 @@ "mmednik" ] }, - "Web/API/XMLHttpRequestEventTarget": { - "modified": "2020-10-15T22:26:08.879Z" - }, - "Web/API/XMLHttpRequestEventTarget/onload": { - "modified": "2020-10-15T22:26:03.172Z", - "contributors": [ - "Akafadam" - ] - }, "Web/API/console/assert": { "modified": "2019-03-23T22:47:53.587Z", "contributors": [ @@ -11035,12 +10777,6 @@ "MilkSnake" ] }, - "Web/CSS/@viewport": { - "modified": "2019-03-18T21:16:54.012Z", - "contributors": [ - "cvrebert" - ] - }, "Web/CSS/Adjacent_sibling_combinator": { "modified": "2019-03-23T22:39:30.908Z", "contributors": [ @@ -11283,12 +11019,6 @@ "ocamachor" ] }, - "Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility": { - "modified": "2019-06-05T03:51:45.202Z", - "contributors": [ - "blanchart" - ] - }, "Web/CSS/CSS_Grid_Layout/Realizing_common_layouts_using_CSS_Grid_Layout": { "modified": "2019-03-18T21:34:10.349Z", "contributors": [ @@ -13173,15 +12903,6 @@ "teffcode" ] }, - "Web/CSS/max-width": { - "modified": "2020-10-15T21:16:38.209Z", - "contributors": [ - "SphinxKnight", - "teoli", - "HenryGR", - "Mgjbot" - ] - }, "Web/CSS/min()": { "modified": "2020-12-03T10:19:50.144Z", "contributors": [ @@ -15813,12 +15534,6 @@ "rewin23" ] }, - "Web/HTTP/CORS/Errors/CORSNotSupportingCredentials": { - "modified": "2020-03-25T19:41:08.379Z", - "contributors": [ - "pablogalvezfotografiadeportiva" - ] - }, "Web/HTTP/CORS/Errors/CORSPreflightDidNotSucceed": { "modified": "2019-10-08T04:58:57.176Z", "contributors": [ @@ -15900,12 +15615,6 @@ "gabriel-ar" ] }, - "Web/HTTP/Headers/Accept-Charset": { - "modified": "2020-10-15T22:13:56.858Z", - "contributors": [ - "ArnoldFZ" - ] - }, "Web/HTTP/Headers/Accept-Ranges": { "modified": "2020-10-15T21:52:24.088Z", "contributors": [ @@ -16358,12 +16067,6 @@ "qpdian" ] }, - "Web/HTTP/Status/301": { - "modified": "2020-10-15T22:24:06.781Z", - "contributors": [ - "nullxx" - ] - }, "Web/HTTP/Status/302": { "modified": "2020-10-15T21:59:00.277Z", "contributors": [ @@ -17158,12 +16861,6 @@ "DSN XP" ] }, - "Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol": { - "modified": "2020-03-12T19:42:42.667Z", - "contributors": [ - "clystian" - ] - }, "Web/JavaScript/Reference/Errors": { "modified": "2020-03-12T19:45:01.208Z", "contributors": [ @@ -17280,12 +16977,6 @@ "Luis_Armando" ] }, - "Web/JavaScript/Reference/Errors/Precision_range": { - "modified": "2020-08-10T12:14:52.122Z", - "contributors": [ - "Sgewux" - ] - }, "Web/JavaScript/Reference/Errors/Property_access_denied": { "modified": "2020-03-12T19:46:35.795Z", "contributors": [ @@ -18087,12 +17778,6 @@ "e.g.m.g." ] }, - "Web/JavaScript/Reference/Global_Objects/Date/getUTCHours": { - "modified": "2019-03-23T22:23:56.170Z", - "contributors": [ - "eltrikiman" - ] - }, "Web/JavaScript/Reference/Global_Objects/Date/now": { "modified": "2019-03-23T23:48:17.746Z", "contributors": [ @@ -18632,12 +18317,6 @@ "harleshinn" ] }, - "Web/JavaScript/Reference/Global_Objects/Math/fround": { - "modified": "2020-10-15T22:21:30.568Z", - "contributors": [ - "Itaiu" - ] - }, "Web/JavaScript/Reference/Global_Objects/Math/hypot": { "modified": "2020-10-15T22:01:35.023Z", "contributors": [ @@ -18925,13 +18604,6 @@ "p1errot" ] }, - "Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__": { - "modified": "2020-10-15T21:59:55.328Z", - "contributors": [ - "al-shmlan", - "jerssonjgar" - ] - }, "Web/JavaScript/Reference/Global_Objects/Object/assign": { "modified": "2020-10-15T21:34:18.548Z", "contributors": [ @@ -20904,12 +20576,6 @@ "Sheppy" ] }, - "Web/Media/Formats/Containers": { - "modified": "2020-07-15T09:47:51.166Z", - "contributors": [ - "hugojavierduran9" - ] - }, "Web/OpenSearch": { "modified": "2019-03-24T00:00:08.096Z", "contributors": [ @@ -20936,12 +20602,6 @@ "c-torres" ] }, - "Web/Performance/How_browsers_work": { - "modified": "2020-09-10T10:11:23.592Z", - "contributors": [ - "sancarbar" - ] - }, "Web/Performance/Optimizing_startup_performance": { "modified": "2019-04-04T17:42:18.542Z", "contributors": [ @@ -21197,15 +20857,6 @@ "d-go" ] }, - "Web/SVG/Tutorial/SVG_In_HTML_Introduction": { - "modified": "2019-03-23T23:21:05.945Z", - "contributors": [ - "chrisdavidmills", - "matrimonio", - "verma21", - "marelin" - ] - }, "Web/SVG/Tutorial/Tools_for_SVG": { "modified": "2019-03-20T13:46:46.393Z", "contributors": [ diff --git a/files/es/games/techniques/3d_on_the_web/index.html b/files/es/games/techniques/3d_on_the_web/index.html deleted file mode 100644 index 3944c617c6..0000000000 --- a/files/es/games/techniques/3d_on_the_web/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: 3D games on the Web -slug: Games/Techniques/3D_on_the_web -tags: - - Games - - Graphics - - NeedsContent - - NeedsExample - - NeedsTranslation - - TopicStub - - WebGL - - WebVR - - three.js -translation_of: Games/Techniques/3D_on_the_web ---- -
{{GamesSidebar}}

For rich gaming experiences on the Web the weapon of choice is WebGL, which is rendered on HTML {{htmlelement("canvas")}}. WebGL is basically an OpenGL ES 2.0 for the Web — it's a JavaScript API providing tools to build rich interactive animations and of course also games. You can generate and render dynamic 3D graphics with JavaScript that is hardware accelerated.

- -

Documentation and browser support

- -

The WebGL project documentation and specification is maintained by the Khronos Group, not the W3C as with most of the Web APIs. Support on modern browsers is very good, even on mobile, so you don't have to worry about that too much. The main browsers are all supporting WebGL and all you need to focus on is optimizing the performance on the devices you use.

- -

There's an ongoing effort on releasing WebGL 2.0 (based on OpenGL ES 3.0) in the near future, which will bring many improvements and will help developers build games for the modern Web using current, powerful hardware.

- -

Explaining basic 3D theory

- -

The basics of 3D theory centers around shapes represented in a 3D space, with a coordinate system being used to calculate their positions. See our Explaining basic 3D theory article for all the information you need.

- -

Advanced concepts

- -

You can do a lot more with WebGL. There are some advanced concepts which you should dive into and learn more about — like shaders, collision detection, or the latest hot topic — virtual reality on the web.

- -

Shaders

- -

It's worth mentioning shaders, which are a separate story on their own. Shaders use GLSL, a special OpenGL Shading Language with syntax similar to C that is executed directly by the graphics pipeline. They can be split into Vertex Shaders and Fragment Shaders (or Pixel Shaders) — the former transforms shape positions to real 3D drawing coordinates, while the latter computes rendering colors and other attributes. You should definitely check out GLSL Shaders article to learn more about them.

- -

Collision Detection

- -

It's hard to imagine a game without the collision detection — we always need to work out when something is hitting something else. We have information available for your to learn from:

- - - -

WebVR

- -

The concept of virtual reality is not new, but it's storming onto the web thanks to hardware advancements such as the Oculus Rift, and the (currently experimental) WebVR API for capturing information form VR hardware and making it available for use in JavaScript applications. For more, read WebVR — Virtual Reality for the Web.

- -

There's also the Building up a basic demo with A-Frame article showing you how easy it is to build 3D environments for virtual reality using the A-Frame framework.

- -

The rise of libraries and frameworks

- -

Coding raw WebGL is fairly complex, but you'll want to get to grips with it in the long run, as your projects get more advanced (see our WebGL documentation to get started.) For real world projects you'll probably also make use of a framework to speed up development and help you manage the project you're working on. Using a framework for 3D games also helps optimize the performance as a lot is taken care of by the tools you use, so you can focus on building the game itself.

- -

The most popular JavaScript 3D library is Three.js, a multi-purpose tool that makes common 3D techniques simpler to implement. There are other popular game development libraries and frameworks worth checking too; A-FramePlayCanvas and Babylon.js are among the most recognizable ones with rich documentation, online editors and active communities.

- -

Building up a basic demo with A-Frame

- -

A-Frame is a web framework for building 3D and VR experiences. Under the hood, it is a three.js framework with a declarative entity-component pattern, meaning we can build scenes with just HTML. See the Building up a basic demo with A-Frame subpage for the step-by-step process of creating the demo.

- -

Building up a basic demo with Babylon.js

- -

Babylon.js is one of the most popular 3D game engines used by developers. As with any other 3D library it provides built-in functions to help you implement common 3D functionality more quickly. See the Building up a basic demo with Babylon.js subpage for the basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code.

- -

Building up a basic demo with PlayCanvas

- -

PlayCanvas is a popular 3D WebGL game engine open sourced on GitHub, with an editor available online and good documentation. See the Building up a basic demo with PlayCanvas subpage for high level details, and further articles showing how to create demos using the PlayCanvas library, and the online editor.

- -

Building up a basic demo with Three.js

- -

Three.js, as any other library, gives you a huge advantage: instead of writing hundreds of lines of WebGL code to build anything interesting you can use built-in helper functions to do it a lot easier and faster. See the Building up a basic demo with Three.js subpage for the step-by-step process of creating the demo.

- -

Other tools

- -

Both Unity and Unreal can export your game to WebGL with asm.js, so you're free to use their tools and techniques to build games that will be exported to the web.

- -

- -

Where to go next

- -

With this article we just scratched the surface of what's possible with currently available technologies. You can build immersive, beautiful and fast 3D games on the Web using WebGL, and the libraries and frameworks build on top of it.

- -

Source code

- -

You can find all the source code for this series demos on GitHub.

- -

APIs

- - - -

Frameworks

- - - -

Tutorials

- - diff --git a/files/es/learn/css/css_layout/positioning/index.html b/files/es/learn/css/css_layout/positioning/index.html deleted file mode 100644 index 3deb33b91f..0000000000 --- a/files/es/learn/css/css_layout/positioning/index.html +++ /dev/null @@ -1,469 +0,0 @@ ---- -title: Positioning -slug: Learn/CSS/CSS_layout/Positioning -translation_of: Learn/CSS/CSS_layout/Positioning ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout/Practical_positioning_examples", "Learn/CSS/CSS_layout")}}
- -

El posicionamiento permite sacar elementos del flujo normal del diseño del documento, y hacer que se comporten de manera distinta, por ejemplo sentarse encima de otro o permanecer en el mismo lugar dentro de la ventana navegador. Este artículo explica los diferentes valores {{cssxref("position")}}, y como usarlos.

- - - - - - - - - - - - -
Requisitos:HTML básico (Aprende  Introducción a HTML), y una idea de cómo trabaja CSS (Aprende  Introducción a CSS.)
Objetivos:Entender como trabajar con posicionamiento CSS.
- -

Flujo del Documento

- -

El posicionamiento es un tema bastante complejo, así que antes de profundizar en el código volvamos a examinar y ampliar un poco la teoría del diseño para darnos una idea de cómo funciona esto.

- -

First of all, individual element boxes are laid out by taking the elements' content, then adding any padding, border and margin around them — it's that box model thing again, which we looked at earlier. By default, a block level element's content is 100% of the width of its parent element, and as tall as its content. Inline elements are all tall as their content, and as wide as their content. You can't set width or height on inline elements — they just sit inside the content of block level elements. If you want to control the size of an inline element in this manner, you need to set it to behave like a block level element with display: block;.

- -

That explains individual elements, but what about how elements interact with one another? The normal layout flow (mentioned in the layout introduction article) is the system by which elements are placed inside the browser's viewport. By default, block level elements are laid out vertically in the viewport — each one will appear on a new line below the last one, and they will be separated by any margin that is set on them.

- -

Inline elements behave differently — they don't appear on new lines; instead, they sit on the same line as one another and any adjacent (or wrapped) text content, as long as there is space for them to do so inside the width of the parent block level element. If there isn't space, then the overflowing text or elements will move down to a new line.

- -

If two adjacent elements both have margin set on them and the two margins touch, the larger of the two remains, and the smaller one disappears — this is called margin collapsing, and we have met this before too.

- -

Let's look at a simple example that explains all this:

- -
<h1>Basic document flow</h1>
-
-<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p>
-
-<p>By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p>
-
-<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p>
-
-<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements will <span>wrap onto a new line if possible (like this one containing text)</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p>
- -
body {
-  width: 500px;
-  margin: 0 auto;
-}
-
-p {
-  background: aqua;
-  border: 3px solid blue;
-  padding: 10px;
-  margin: 10px;
-}
-
-span {
-  background: red;
-  border: 1px solid black;
-}
- -

{{ EmbedLiveSample('Document_flow', '100%', 500) }}

- -

We will be revisiting this example a number of times as we go through this article, as we show the effects of the different positioning options available to us.

- -

We'd like you to follow along with the exercises on your local computer, if possible — grab a copy of 0_basic-flow.html from our Github repo (source code here) and use that as a starting point.

- -

Introducing positioning

- -

The whole idea of positioning is to allow us to override the basic document flow behaviour described above, to produce interesting effects. What if you want to slightly alter the position of some boxes inside a layout from their default layout flow position, to give a slightly quirky, distressed feel? Positioning is your tool. Or if you want to create a UI element that floats over the top of other parts of the page, and/or always sits in the same place inside the browser window no matter how much the page is scrolled? Positioning makes such layout work possible.

- -

There are a number of different types of positioning that you can put into effect on HTML elements. To make a specific type of positioning active on an element, we use the {{cssxref("position")}} property.

- -

Static positioning

- -

Static positioning is the default that every element gets — it just means "put the element into its normal position in the document layout flow — nothing special to see here."

- -

To demonstrate this, and get your example set up for future sections, first add a class of positioned to the second {{htmlelement("p")}} in the HTML:

- -
<p class="positioned"> ... </p>
- -

Now add the following rule to the bottom of your CSS:

- -
.positioned {
-  position: static;
-  background: yellow;
-}
- -

If you now save and refresh, you'll see no difference at all, except for the updated background color of the 2nd paragraph. This is fine — as we said before, static positioning is the default behaviour!

- -
-

Note: You can see the example at this point live at 1_static-positioning.html (see source code).

-
- -

Relative positioning

- -

Relative positioning is the first position type we'll take a look at. This is very similar to static positioning, except that once the positioned element has taken its place in the normal layout flow, you can then modify its final position, including making it overlap other elements on the page. Go ahead and update the position declaration in your code:

- -
position: relative;
- -

If you save and refresh at this stage, you won't see a change in the result at all — so how do you modify the element's position? You need to use the {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} properties, which we'll explain in the next section.

- -

Introducing top, bottom, left, and right

- -

{{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} are used alongside {{cssxref("position")}} to specify exactly where to move the positioned element to. To try this out, add the following declarations to the .positioned rule in your CSS:

- -
top: 30px;
-left: 30px;
- -
-

Note: The values of these properties can take any units you'd logically expect — pixels, mm, rems, %, etc.

-
- -

If you now save and refresh, you'll get a result something like this:

- - - -

{{ EmbedLiveSample('Introducing_top_bottom_left_and_right', '100%', 500) }}

- -

Cool, huh? Ok, so this probably wasn't what you were expecting — why has it moved to the bottom and right if we specified top and left? Illogical as it may initially sound, this is just the way that relative positioning works — you need to think of an invisible force that pushes the side of the positioned box, moving it in the opposite direction. So for example, if you specify top: 30px;, a force pushes the top of the box, causing it to move downwards by 30px.

- -
-

Note: You can see the example at this point live at 2_relative-positioning.html (see source code).

-
- -

Absolute positioning

- -

Absolute positioning brings very different results. Let's try changing the position declaration in your code as follows:

- -
position: absolute;
- -

If you now save and refresh, you should see something like so:

- - - -

{{ EmbedLiveSample('Absolute_positioning', '100%', 420) }}

- -

First of all, note that the gap where the positioned element should be in the document flow is no longer there — the first and third elements have closed together like it no longer exists! Well, in a way, this is true. An absolutely positioned element no longer exists in the normal document layout flow. Instead, it sits on its own layer separate from everything else. This is very useful — it means that we can create isolated UI features that don't interfere with the position of other elements on the page — for example popup information boxes and control menus, rollover panels, UI features that can be dragged and dropped anywhere on the page, and so on.

- -

Second, notice that the position of the element has changed — this is because {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} behave in a different way with absolute positioning. Instead of specifying the direction the element should move in, they specify the distance the element should be from each containing element's sides. So in this case, we are saying that the absolutely positioned element should sit 30px from the top of the "containing element", and 30px from the left.

- -
-

Note: You can use {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} to resize elements if you need to. Try setting top: 0; bottom: 0; left: 0; right: 0; and margin: 0; on your positioned elements and see what happens! Put it back again afterwards...

-
- -
-

Note: Yes, margins still affect positioned elements. Margin collapsing doesn't, however.

-
- -
-

Note: You can see the example at this point live at 3_absolute-positioning.html (see source code).

-
- -

Positioning contexts

- -

Which element is the "containing element" of an absolutely positioned element? By default, it is the {{htmlelement("html")}} element — the positioned element is nested inside the {{htmlelement("body")}} in the HTML source, but in the final layout, it is 30px away from the top and left of the edge of the page, which is the {{htmlelement("html")}} element. This is more accurately called the element's positioning context.

- -

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's other ancestors — one of the elements it is nested inside (you can't position it relative to an element it is not nested inside). To demonstrate this, add the following declaration to your body rule:

- -
position: relative;
- -

This should give the following result:

- - - -

{{ EmbedLiveSample('Positioning_contexts', '100%', 420) }}

- -

The positioned element now sits relative to the {{htmlelement("body")}} element.

- -
-

Note: You can see the example at this point live at 4_positioning-context.html (see source code).

-
- -

Introducing z-index

- -

All this absolute positioning is good fun, but there is another thing we haven't considered yet — when elements start to overlap, what determines which elements appear on top of which other elements? In the example we've seen so far, we only have one positioned element in the positioning context, and it appears on the top, since positioned elements win over non-positioned elements. What about when we have more than one?

- -

Try adding the following to your CSS, to make the first paragraph absolutely positioned too:

- -
p:nth-of-type(1) {
-  position: absolute;
-  background: lime;
-  top: 10px;
-  right: 30px;
-}
- -

At this point you'll see the first paragraph colored green, moved out of the document flow, and positioned a bit above from where it originally was. It is also stacked below the original .positioned paragraph, where the two overlap. This is because the .positioned paragraph is the second paragraph in the source order, and positioned elements later in the source order win over positioned elements earlier in the source order.

- -

Can you change the stacking order? Yes, you can, by using the {{cssxref("z-index")}} property. "z-index" is a reference to the z-axis. You may recall from previous points in the source where we discussed web pages using horizontal (x-axis) and vertical (y-axis) coordinates to work out positioning for things like background images and drop shadow offsets. (0,0) is at the top left of the page (or element), and the x- and y-axes run across to the right and down the page (for left to right languages, anyway.)

- -

Web pages also have a z-axis — an imaginary line that runs from the surface of your screen, towards your face (or whatever else you like to have in front of the screen). {{cssxref("z-index")}} values affect where positioned elements sit on that axis — positive values move them higher up the stack, and negative values move them lower down the stack. By default, positioned elements all have a z-index of auto, which is effectively 0.

- -

To change the stacking order, try adding the following declaration to your p:nth-of-type(1) rule:

- -
z-index: 1;
- -

You should now see the finished example:

- - - -

{{ EmbedLiveSample('Introducing_z-index', '100%', 400) }}

- -

Note that z-index only accepts unitless index values; you can't specify that you want one element to be 23 pixels up the Z-axis — it doesn't work like that. Higher values will go above lower values, and it is up to you what values you use. Using 2 and 3 would give the same effect as 300 and 40000.

- -
-

Note: You can see the example at this point live at 5_z-index.html (see source code).

-
- -

Fixed positioning

- -

There is one more type of positioning to cover — fixed. This works in exactly the same way as absolute positioning, with one key difference — whereas absolute positioning fixes an element in place relative to the {{htmlelement("html")}} element or its nearest positioned ancestor, fixed positioning fixes an element in place relative to the browser viewport itself. This means that you can create useful UI items that are fixed in place, like persisting navigation menus.

- -

Let's put together a simple example to show what we mean. First of all, delete the existing p:nth-of-type(1) and .positioned rules from your CSS.

- -

Now, update the body rule to remove the position: relative; declaration and add a fixed height, like so:

- -
body {
-  width: 500px;
-  height: 1400px;
-  margin: 0 auto;
-}
- -

Now we're going to give the {{htmlelement("h1")}} element position: fixed;, and get it to sit at the top center of the viewport. Add the following rule to your CSS:

- -
h1 {
-  position: fixed;
-  top: 0;
-  width: 500px;
-  margin: 0 auto;
-  background: white;
-  padding: 10px;
-}
- -

The top: 0; is required to make it stick to the top of the screen; we then give the heading the same width as the content column and use the faithful old margin: 0 auto; trick to center it. We then give it a white background and some padding, so the content won't be visible underneath it.

- -

If you save and refresh now, you'll see a fun little effect whereby the heading stays fixed, and the content appears to scroll up and disappear underneath it. But we could improve this more — at the moment some of the content starts off underneath the heading. This is because the positioned heading no longer appears in the document flow, so the rest of the content moves up to the top. We need to move it all down a bit; we can do this by setting some top margin on the first paragraph. Add this now:

- -
p:nth-of-type(1) {
-  margin-top: 60px;
-}
- -

You should now see the finished example:

- - - -

{{ EmbedLiveSample('Fixed_positioning', '100%', 400) }}

- -
-

Note: You can see the example at this point live at 6_fixed-positioning.html (see source code).

-
- -

Experimental: position sticky

- -

There is a new positioning value available called position: sticky, support for which is not very widespread yet. This is basically a hybrid between relative and fixed position, which allows a positioned element to act like it is relatively positioned until it is scrolled to a certain threshold point (e.g. 10px from the top of the viewport), after which it becomes fixed.  See our position: sticky reference entry for more details and an example.

- -

Summary

- -

I'm sure you had fun playing with basic positioning — it is one of the essential tools behind creating complex CSS layouts and UI features. With that in mind, in the next article we'll have even more fun with positioning — there we'll go a step further and start to build up some real world useful things with it.

- -

{{PreviousMenuNext("Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout/Practical_positioning_examples", "Learn/CSS/CSS_layout")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/es/learn/javascript/client-side_web_apis/fetching_data/index.html b/files/es/learn/javascript/client-side_web_apis/fetching_data/index.html deleted file mode 100644 index ab34b8c319..0000000000 --- a/files/es/learn/javascript/client-side_web_apis/fetching_data/index.html +++ /dev/null @@ -1,373 +0,0 @@ ---- -title: Fetching data from the server -slug: Learn/JavaScript/Client-side_web_APIs/Fetching_data -translation_of: Learn/JavaScript/Client-side_web_APIs/Fetching_data ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/Client-side_web_APIs/Manipulating_documents", "Learn/JavaScript/Client-side_web_APIs/Third_party_APIs", "Learn/JavaScript/Client-side_web_APIs")}}
- -

Otra tarea muy común en páginas web y en aplicaciones es tomar elementos individuales de datos desde el servidor para actualizar secciones de la página web sin tener que cargar toda una nueva página. Este aparentemente pequeño detalle tiene un gran impacto en el desempeño y comportamiento de los sitios, por eso en este artículo, explicaremos el concepto y veremos las tecnologías que hacen esto posible, como ser XHLHttpRequest y FetchAPI. 

- - - - - - - - - - - - -
Prerequisitos:JavaScript básico (ver first steps, building blocks, JavaScript objects),  basics of Client-side APIs
Objetivo:Aprender como extraer datos desde el servidor y usarlo para cargar contenido en la página web. 
- -

Cúal es el problema aquí?

- -

Originalmente cargar páginas en la web era simple  — tu enviabas una solicitud de la página web al servidor, y si no había ningún problema, los servicios encargados de la página web la descargaban y mostraban en tu computadora.

- -

A basic representation of a web site architecture

- -

El problema con este modelo es que si tu quieres actualizar cualquier parte de la página, por ejemplo, mostrar el nuevo set de productos o cargar una nueva página, tu tenías que cargar toda la página de nuevo. Esto es extremadamente un desperdicio y resultaba ser una experiencia pobre al usuario, especialmente cuando la página es más grande y más compleja. 

- -

Introduciendo Ajax

- -

This led to the creation of technologies that allow web pages to request small chunks of data (such as HTML, {{glossary("XML")}}, JSON, or plain text) and display them only when needed, helping to solve the problem described above.

- -

This is achieved by using APIs like {{domxref("XMLHttpRequest")}} or — more recently — the Fetch API. These technologies allow web pages to directly handle making HTTP requests for specific resources available on a server and formatting the resulting data as needed before it is displayed.

- -
-

Note: In the early days, this general technique was known as Asynchronous JavaScript and XML (Ajax), because it tended to use {{domxref("XMLHttpRequest")}} to request XML data. This is normally not the case these days (you'd be more likely to use XMLHttpRequest or Fetch to request JSON), but the result is still the same, and the term "Ajax" is still often used to describe the technique.

-
- -

A simple modern architecture for web sites

- -

The Ajax model involves using a web API as a proxy to more intelligently request data rather than just having the browser reload the entire page. Let's think about the significance of this:

- -
    -
  1. Go to one of your favorite information-rich sites, like Amazon, YouTube, CNN, etc., and load it.
  2. -
  3. Now search for something, like a new product. The main content will change, but most of the surrounding information, like the header, footer, navigation menu, etc., will stay the same.
  4. -
- -

This is a really good thing because:

- - - -

To speed things up even further, some sites also store assets and data on the user's computer when they are first requested, meaning that on subsequent visits they use the local versions instead of downloading fresh copies when the page is first loaded. The content is only reloaded from the server when it has been updated.

- -

A basic web app data flow architecture

- -

A basic Ajax request

- -

Let's look at how such a request is handled, using both {{domxref("XMLHttpRequest")}} and Fetch. For these examples, we'll request data out of a few different text files and use them to populate a content area.

- -

This series of files will act as our fake database; in a real application, we'd be more likely to use a server-side language like PHP, Python, or Node to request our data from a database. Here, however, we want to keep it simple and concentrate on the client-side part of this.

- -

XMLHttpRequest

- -

XMLHttpRequest (which is frequently abbreviated to XHR) is a fairly old technology now — it was invented by Microsoft in the late '90s, and has been standardized across browsers for quite a long time.

- -
    -
  1. -

    To begin this example, make a local copy of ajax-start.html and the four text files — verse1.txt, verse2.txt, verse3.txt, and verse4.txt — in a new directory on your computer. In this example, we will load a different verse of the poem (which you may well recognize) via XHR when it's selected in the drop-down menu.

    -
  2. -
  3. -

    Just inside the {{htmlelement("script")}} element, add the following code. This stores a reference to the {{htmlelement("select")}} and {{htmlelement("pre")}} elements in variables and defines an {{domxref("GlobalEventHandlers.onchange","onchange")}} event handler function so that when the select's value is changed, its value is passed to an invoked function updateDisplay() as a parameter.

    - -
    var verseChoose = document.querySelector('select');
    -var poemDisplay = document.querySelector('pre');
    -
    -verseChoose.onchange = function() {
    -  var verse = verseChoose.value;
    -  updateDisplay(verse);
    -};
    -
  4. -
  5. -

    Let's define our updateDisplay() function. First of all, put the following beneath your previous code block — this is the empty shell of the function:

    - -
    function updateDisplay(verse) {
    -
    -};
    -
  6. -
  7. -

    We'll start our function by constructing a relative URL pointing to the text file we want to load, as we'll need it later. The value of the {{htmlelement("select")}} element at any time is the same as the text inside the selected {{htmlelement("option")}} (unless you specify a different value in a value attribute) — so for example "Verse 1". The corresponding verse text file is "verse1.txt", and is in the same directory as the HTML file, therefore just the file name will do.

    - -

    However, web servers tend to be case sensitive, and the file name doesn't have a space in it. To convert "Verse 1" to "verse1.txt" we need to convert the V to lower case, remove the space, and add .txt on the end. This can be done with {{jsxref("String.replace", "replace()")}}, {{jsxref("String.toLowerCase", "toLowerCase()")}}, and simple string concatenation. Add the following lines inside your updateDisplay() function:

    - -
    verse = verse.replace(" ", "");
    -verse = verse.toLowerCase();
    -var url = verse + '.txt';
    -
  8. -
  9. -

    To begin creating an XHR request, you need to create a new request object using the {{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}} constructor. You can call this object anything you like, but we'll call it request to keep things simple. Add the following below your previous lines:

    - -
    var request = new XMLHttpRequest();
    -
  10. -
  11. -

    Next, you need to use the {{domxref("XMLHttpRequest.open","open()")}} method to specify what HTTP request method to use to request the resource from the network, and what its URL is. We'll just use the GET method here and set the URL as our url variable. Add this below your previous line:

    - -
    request.open('GET', url);
    -
  12. -
  13. -

    Next, we'll set the type of response we are expecting — which is defined by the request's {{domxref("XMLHttpRequest.responseType", "responseType")}} property — as text. This isn't strictly necessary here — XHR returns text by default — but it is a good idea to get into the habit of setting this in case you want to fetch other types of data in the future. Add this next:

    - -
    request.responseType = 'text';
    -
  14. -
  15. -

    Fetching a resource from the network is an {{glossary("asynchronous")}} operation, meaning that you have to wait for that operation to complete (e.g., the resource is returned from the network) before you can do anything with that response, otherwise, an error will be thrown. XHR allows you to handle this using its {{domxref("XMLHttpRequest.onload", "onload")}} event handler — this is run when the {{event("load")}} event fires (when the response has returned). When this has occurred, the response data will be available in the response property of the XHR request object.

    - -

    Add the following below your last addition. You'll see that inside the onload event handler we are setting the textContent of the poemDisplay (the {{htmlelement("pre")}} element) to the value of the {{domxref("XMLHttpRequest.response", "request.response")}} property.

    - -
    request.onload = function() {
    -  poemDisplay.textContent = request.response;
    -};
    -
  16. -
  17. -

    The above is all set up for the XHR request — it won't actually run until we tell it to, which is done using the {{domxref("XMLHttpRequest.send","send()")}} method. Add the following below your previous addition to complete the function:

    - -
    request.send();
    -
  18. -
  19. -

    One problem with the example as it stands is that it won't show any of the poem when it first loads. To fix this, add the following two lines at the bottom of your code (just above the closing </script> tag) to load verse 1 by default, and make sure the {{htmlelement("select")}} element always shows the correct value:

    - -
    updateDisplay('Verse 1');
    -verseChoose.value = 'Verse 1';
    -
  20. -
- -

Serving your example from a server

- -

Some browsers (including Chrome) will not run XHR requests if you just run the example from a local file. This is because of security restrictions (for more on web security, read Website security).

- -

To get around this, we need to test the example by running it through a local web server. To find out how to do this, read How do you set up a local testing server?

- -

Fetch

- -

The Fetch API is basically a modern replacement for XHR; it was introduced in browsers recently to make asynchronous HTTP requests easier to do in JavaScript, both for developers and other APIs that build on top of Fetch.

- -

Let's convert the last example to use Fetch instead.

- -
    -
  1. -

    Make a copy of your previous finished example directory. (If you didn't work through the previous exercise, create a new directory and inside it make copies of xhr-basic.html and the four text files — verse1.txt, verse2.txt, verse3.txt, and verse4.txt.)

    -
  2. -
  3. -

    Inside the updateDisplay() function, find the XHR code:

    - -
    var request = new XMLHttpRequest();
    -request.open('GET', url);
    -request.responseType = 'text';
    -
    -request.onload = function() {
    -  poemDisplay.textContent = request.response;
    -};
    -
    -request.send();
    -
  4. -
  5. -

    Replace all the XHR code with this:

    - -
    fetch(url).then(function(response) {
    -  response.text().then(function(text) {
    -    poemDisplay.textContent = text;
    -  });
    -});
    -
  6. -
  7. -

    Load the example in your browser (running it through a web server) and it should work just the same as the XHR version, provided you are running a modern browser.

    -
  8. -
- -

So what is going on in the Fetch code?

- -

First of all, we invoke the {{domxref("WorkerOrWindowGlobalScope.fetch()","fetch()")}} method, passing it the URL of the resource we want to fetch. This is the modern equivalent of {{domxref("XMLHttpRequest.open","request.open()")}} in XHR, plus you don't need any equivalent to .send().

- -

After that, you can see the {{jsxref("Promise.then",".then()")}} method chained onto the end of fetch() — this method is a part of {{jsxref("Promise","Promises")}}, a modern JavaScript feature for performing asynchronous operations. fetch() returns a promise, which resolves to the response sent back from the server — we use .then() to run some follow-up code after the promise resolves, which is the function we've defined inside it. This is the equivalent of the onload event handler in the XHR version.

- -

This function is automatically given the response from the server as a parameter when the fetch() promise resolves. Inside the function we grab the response and run its {{domxref("Body.text","text()")}} method, which basically returns the response as raw text. This is the equivalent of request.responseType = 'text' in the XHR version.

- -

You'll see that text() also returns a promise, so we chain another .then() onto it, inside of which we define a function to receive the raw text that the text() promise resolves to.

- -

Inside the inner promise's function, we do much the same as we did in the XHR version — set the {{htmlelement("pre")}} element's text content to the text value.

- -

Aside on promises

- -

Promises are a bit confusing the first time you meet them, but don't worry too much about this for now. You'll get used to them after a while, especially as you learn more about modern JavaScript APIs — most of the newer ones are heavily based on promises.

- -

Let's look at the promise structure from above again to see if we can make some more sense of it:

- -
fetch(url).then(function(response) {
-  response.text().then(function(text) {
-    poemDisplay.textContent = text;
-  });
-});
- -

The first line is saying "fetch the resource located at URL" (fetch(url)) and "then run the specified function when the promise resolves" (.then(function() { ... })). "Resolve" means "finish performing the specified operation at some point in the future". The specified operation, in this case, is to fetch a resource from a specified URL (using an HTTP request), and return the response for us to do something with.

- -

Effectively, the function passed into then() is a chunk of code that won't run immediately. Instead, it will run at some point in the future when the response has been returned. Note that you could also choose to store your promise in a variable and chain {{jsxref("Promise.then",".then()")}} onto that instead. The code below would do the same thing:

- -
var myFetch = fetch(url);
-
-myFetch.then(function(response) {
-  response.text().then(function(text) {
-    poemDisplay.textContent = text;
-  });
-});
- -

Because the fetch() method returns a promise that resolves to the HTTP response, any function you define inside a .then() chained onto the end of it will automatically be given the response as a parameter. You can call the parameter anything you like — the below example would still work:

- -
fetch(url).then(function(dogBiscuits) {
-  dogBiscuits.text().then(function(text) {
-    poemDisplay.textContent = text;
-  });
-});
- -

But it makes more sense to call the parameter something that describes its contents.

- -

Now let's focus just on the function:

- -
function(response) {
-  response.text().then(function(text) {
-    poemDisplay.textContent = text;
-  });
-}
- -

The response object has a method {{domxref("Body.text","text()")}} that takes the raw data contained in the response body and turns it into plain text — the format we want it in. It also returns a promise (which resolves to the resulting text string), so here we use another {{jsxref("Promise.then",".then()")}}, inside of which we define another function that dictates what we want to do with that text string. We are just setting the textContent property of our poem's {{htmlelement("pre")}} element to equal the text string, so this works out pretty simple.

- -

It is also worth noting that you can directly chain multiple promise blocks (.then() blocks, but there are other types too) onto the end of one another, passing the result of each block to the next block as you travel down the chain. This makes promises very powerful.

- -

The following block does the same thing as our original example, but is written in a different style:

- -
fetch(url).then(function(response) {
-  return response.text()
-}).then(function(text) {
-  poemDisplay.textContent = text;
-});
- -

Many developers like this style better, as it is flatter and arguably easier to read for longer promise chains — each subsequent promise comes after the previous one, rather than being inside the previous one (which can get unwieldy). The only other difference is that we've had to include a return statement in front of response.text(), to get it to pass its result on to the next link in the chain.

- -

Which mechanism should you use?

- -

This really depends on what project you are working on. XHR has been around for a long time now and has very good cross-browser support. Fetch and Promises, on the other hand, are a more recent addition to the web platform, although they're supported well across the browser landscape, with the exception of Internet Explorer.

- -

If you need to support older browsers, then an XHR solution might be preferable. If however you are working on a more progressive project and aren't as worried about older browsers, then Fetch could be a good choice.

- -

You should really learn both — Fetch will become more popular as Internet Explorer declines in usage (IE is no longer being developed, in favor of Microsoft's new Edge browser), but you might need XHR for a while yet.

- -

A more complex example

- -

To round off the article, we'll look at a slightly more complex example that shows some more interesting uses of Fetch. We have created a sample site called The Can Store — it's a fictional supermarket that only sells canned goods. You can find this example live on GitHub, and see the source code.

- -

A fake ecommerce site showing search options in the left hand column, and product search results in the right hand column.

- -

By default, the site displays all the products, but you can use the form controls in the left hand column to filter them by category, or search term, or both.

- -

There is quite a lot of complex code that deals with filtering the products by category and search terms, manipulating strings so the data displays correctly in the UI, etc. We won't discuss all of it in the article, but you can find extensive comments in the code (see can-script.js).

- -

We will however explain the Fetch code.

- -

The first block that uses Fetch can be found at the start of the JavaScript:

- -
fetch('products.json').then(function(response) {
-  return response.json();
-}).then(function(json) {
-  products = json;
-  initialize();
-}).catch(function(err) {
-  console.log('Fetch problem: ' + err.message);
-});
- -

The fetch() function returns a promise. If this completes successfully, the function inside the first .then() block contains the response returned from the network.

- -

Inside this function we run {{domxref("Body.json","json()")}} on the response, not {{domxref("Body.text","text()")}}, as we want to return our response as structured JSON data, not plain text.

- -

Next, we chain another .then() onto the end of our first one, the success function that contains the json returned from the response.json() promise. We set this to be the value of the products global object, then run initialize(), which starts the process of displaying all the products in the user interface.

- -

To handle errors, we chain a .catch() block onto the end of the chain. This runs if the promise fails for some reason. Inside it, we include a function that is passed as a parameter, an error object. This error object can be used to report the nature of the error that has occurred, in this case we do it with a simple console.log().

- -

However, a complete website would handle this error more gracefully by displaying a message on the user's screen and perhaps offering options to remedy the situation, but we don't need anything more than a simple console.log().

- -

You can test the fail case yourself:

- -
    -
  1. Make a local copy of the example files (download and unpack the can-store ZIP file).
  2. -
  3. Run the code through a web server (as described above, in {{anch("Serving your example from a server")}}).
  4. -
  5. Modify the path to the file being fetched, to something like 'produc.json' (make sure it is misspelled).
  6. -
  7. Now load the index file in your browser (via localhost:8000) and look in your browser developer console. You'll see a message similar to "Network request for products.json failed with response 404: File not found".
  8. -
- -

The second Fetch block can be found inside the fetchBlob() function:

- -
fetch(url).then(function(response) {
-    return response.blob();
-}).then(function(blob) {
-  // Convert the blob to an object URL — this is basically an temporary internal URL
-  // that points to an object stored inside the browser
-  var objectURL = URL.createObjectURL(blob);
-  // invoke showProduct
-  showProduct(objectURL, product);
-});
- -

This works in much the same way as the previous one, except that instead of using {{domxref("Body.json","json()")}}, we use {{domxref("Body.blob","blob()")}}. In this case we want to return our response as an image file, and the data format we use for that is Blob (the term is an abbreviation of "Binary Large Object" and can basically be used to represent large file-like objects, such as images or video files).

- -

Once we've successfully received our blob, we create an object URL out of it using {{domxref("URL.createObjectURL()", "createObjectURL()")}}. This returns a temporary internal URL that points to an object referenced inside the browser. These are not very readable, but you can see what one looks like by opening up the Can Store app, Ctrl-/Right-clicking on an image, and selecting the "View image" option (which might vary slightly depending on what browser you are using). The object URL will be visible inside the address bar, and should be something like this:

- -
blob:http://localhost:7800/9b75250e-5279-e249-884f-d03eb1fd84f4
- -

Challenge: An XHR version of the Can Store

- -

We'd like you to try converting the Fetch version of the app to use XHR as a useful bit of practice. Take a copy of the ZIP file, and try modifying the JavaScript as appropriate.

- -

Some helpful hints:

- - - -
-

Note: If you have trouble with this, feel free to check your code against the finished version on GitHub (see the source here, and also see it running live).

-
- -

Summary

- -

This article shows how to start working with both XHR and Fetch to fetch data from the server.

- -

See also

- -

There are however a lot of different subjects discussed in this article, which has only really scratched the surface. For a lot more detail on these subjects, try the following articles:

- - - -
{{PreviousMenuNext("Learn/JavaScript/Client-side_web_APIs/Manipulating_documents", "Learn/JavaScript/Client-side_web_APIs/Third_party_APIs", "Learn/JavaScript/Client-side_web_APIs")}}
- -
-

In this module

- - -
diff --git a/files/es/learn/server-side/express_nodejs/mongoose/index.html b/files/es/learn/server-side/express_nodejs/mongoose/index.html deleted file mode 100644 index f5701c468a..0000000000 --- a/files/es/learn/server-side/express_nodejs/mongoose/index.html +++ /dev/null @@ -1,801 +0,0 @@ ---- -title: 'Express Tutorial 3: Utilizando bases de datos (con Mongoose)' -slug: Learn/Server-side/Express_Nodejs/mongoose -translation_of: Learn/Server-side/Express_Nodejs/mongoose ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}
- -

Este artículo introduce brevemente las bases de datos así como su uso en aplicaciones Node/Express. Despues, profundiza en el uso específico de Mongoose en el proyecto LocalLibrary. Explica como se declaran y utilizan los esquemas modelo-objeto, los principales campos de datos y su validación básica. También muestra brevemente algunas de las muchas formas para acceder y modificar los datos.

- - - - - - - - - - - - -
PrerequisitosExpress Tutorial 2: Creando un esqueleto web
Objetivo:Ser capaz de crear, diseñar y utilizar bases de datos en Node/Express utilizando Mongoose
- -

Overview

- -

Library staff will use the Local Library website to store information about books and borrowers, while library members will use it to browse and search for books, find out whether there are any copies available, and then reserve or borrow them. In order to store and retrieve information efficiently, we will store it in a database.

- -

Las aplicaciones Express pueden utilizar diferentes bases de datos, y existen diferentes aproximaciones que se pueden utilizar para realizar operaciones CRUD (Create, Read, Update and Delete). Este tutorial proporciona una vista general sobre algunas de las opciones disponibles, para a continuación mostrar en detalle los mecanismos elegidos en particular.

- -

What databases can I use?

- -

Express apps can use any database supported by Node (Express itself doesn't define any specific additional behaviour/requirements for database management). There are many popular options, including PostgreSQL, MySQL, Redis, SQLite, and MongoDB.

- -

When choosing a database, you should consider things like time-to-productivity/learning curve, performance, ease of replication/backup, cost, community support, etc. While there is no single "best" database, almost any of the popular solutions should be more than acceptable for a small-to-medium-sized site like our Local Library.

- -

For more information on the options see: Database integration (Express docs).

- -

What is the best way to interact with a database?

- -

There are two approaches for interacting with a database: 

- - - -

The very best performance can be gained by using SQL, or whatever query language is supported by the database. ODM's are often slower because they use translation code to map between objects and the database format, which may not use the most efficient database queries (this is particularly true if the ODM supports different database backends, and must make greater compromises in terms of what database features are supported).

- -

The benefit of using an ORM is that programmers can continue to think in terms of JavaScript objects rather than database semantics — this is particularly true if you need to work with different databases (on either the same or different websites). They also provide an obvious place to perform validation and checking of data.

- -
-

Tip:  Using ODM/ORMs often results in lower costs for development and maintenance! Unless you're very familiar with the native query language or performance is paramount, you should strongly consider using an ODM.

-
- -

What ORM/ODM should I use?

- -

There are many ODM/ORM solutions available on the NPM package manager site (check out the odm and orm tags for a subset!).

- -

A few solutions that were popular at the time of writing are:

- - - -

As a general rule you should consider both the features provided and the "community activity" (downloads, contributions, bug reports, quality of documentation, etc.) when selecting a solution. At time of writing Mongoose is by far the most popular ORM, and is a reasonable choice if you're using MongoDB for your database.

- -

Using Mongoose and MongoDb for the LocalLibrary

- -

For the Local Library example (and the rest of this topic) we're going to use the Mongoose ODM to access our library data. Mongoose acts as a front end to MongoDB, an open source NoSQL database that uses a document-oriented data model. A “collection” of “documents”, in a MongoDB database, is analogous to a “table” of “rows” in a relational database.

- -

This ODM and database combination is extremely popular in the Node community, partially because the document storage and query system looks very much like JSON, and is hence familiar to JavaScript developers.

- -
-

Tip: You don't need to know MongoDB in order to use Mongoose, although parts of the Mongoose documentation are easier to use and understand if you are already familiar with MongoDB.

-
- -

The rest of this tutorial shows how to define and access the Mongoose schema and models for the LocalLibrary website example.

- -

Designing the LocalLibrary models

- -

Before you jump in and start coding the models, it's worth taking a few minutes to think about what data we need to store and the relationships between the different objects.

- -

We know that we need to store information about books (title, summary, author, genre, ISBN) and that we might have multiple copies available (with globally unique ids, availability statuses, etc.). We might need to store more information about the author than just their name, and there might be multiple authors with the same or similar names. We want to be able to sort information based on book title, author, genre, and category.

- -

When designing your models it makes sense to have separate models for every "object" (group of related information). In this case the obvious objects are books, book instances, and authors.

- -

You might also want to use models to represent selection-list options (e.g. like a drop down list of choices), rather than hard coding the choices into the website itself — this is recommended when all the options aren't known up front or may change. The obvious candidate for a model of this type is the book genre (e.g. Science Fiction, French Poetry, etc.)

- -

Once we've decided on our models and fields, we need to think about the relationships between them.

- -

With that in mind, the UML association diagram below shows the models we'll define in this case (as boxes). As discussed above, we've created models for book (the generic details of the book), book instance (status of specific physical copies of the book available in the system), and author. We have also decided to have a model for genre, so that values can be created dynamically. We've decided not to have a model for the BookInstance:status — we will hard code the acceptable values because we don't expect these to change. Within each of the boxes you can see the model name, the field names and types, and also the methods and their return types.

- -

The diagram also shows the relationships between the models, including their multiplicities. The multiplicities are the numbers on the diagram showing the numbers (maximum and minimum) of each model that may be present in the relationship. For example, the connecting line between the boxes shows that Book and a Genre are related. The numbers close to the Book model show that a Genre must have zero or more Book (as many as you like), while the numbers on the other end of the line next to the Genre show that it can have zero or more associated genre.

- -
-

Note: As discussed in our Mongoose primer below it is often better to have the field that defines the relationship between the documents/models in just one model (you can still find the reverse relationship by searching for the associated _id in the other model). Below we have chosen to define the relationship between Book/Genre and Book/Author in the Book schema, and the relationship between the Book/BookInstance in the BookInstance Schema. This choice was somewhat arbitrary — we could equally well have had the field in the other schema.

-
- -

Mongoose Library Model  with correct cardinality

- -
-

Note: The next section provides a basic primer explaining how models are defined and used. As you read it, consider how we will construct each of the models in the diagram above.

-
- -

Mongoose primer

- -

This section provides an overview of how to connect Mongoose to a MongoDB database, how to define a schema and a model, and how to make basic queries. 

- -
-

Note: This primer is "heavily influenced" by the Mongoose quick start on npm and the official documentation.

-
- -

Installing Mongoose and MongoDB

- -

Mongoose is installed in your project (package.json) like any other dependency — using NPM. To install it, use the following command inside your project folder:

- -
npm install mongoose
-
- -

Installing Mongoose adds all its dependencies, including the MongoDB database driver, but it does not install MongoDB itself. If you want to install a MongoDB server then you can download installers from here for various operating systems and install it locally. You can also use cloud-based MongoDB instances.

- -
-

Note: For this tutorial we'll be using the mLab cloud-based database as a service sandbox tier to provide the database. This is suitable for development, and makes sense for the tutorial because it makes "installation" operating system independent (database-as-a-service is also one approach you might well use for your production database).

-
- -

Connecting to MongoDB

- -

Mongoose requires a connection to a MongoDB database. You can require() and connect to a locally hosted database with mongoose.connect(), as shown below.

- -
//Import the mongoose module
-var mongoose = require('mongoose');
-
-//Set up default mongoose connection
-var mongoDB = 'mongodb://127.0.0.1/my_database';
-mongoose.connect(mongoDB);
-// Get Mongoose to use the global promise library
-mongoose.Promise = global.Promise;
-//Get the default connection
-var db = mongoose.connection;
-
-//Bind connection to error event (to get notification of connection errors)
-db.on('error', console.error.bind(console, 'MongoDB connection error:'));
- -

You can get the default Connection object with mongoose.connection. Once connected, the open event is fired on the Connection instance.

- -
-

Tip: If you need to create additional connections you can use mongoose.createConnection(). This takes the same form of database URI (with host, database, port, options etc.) as connect() and returns a Connection object).

-
- -

Defining and creating models

- -

Models are defined using the Schema interface. The Schema allows you to define the fields stored in each document along with their validation requirements and default values. In addition, you can define static and instance helper methods to make it easier to work with your data types, and also virtual properties that you can use like any other field, but which aren't actually stored in the database (we'll discuss a bit further below).

- -

Schemas are then "compiled" into models using the mongoose.model() method. Once you have a model you can use it to find, create, update, and delete objects of the given type.

- -
-

Note: Each model maps to a collection of documents in the MongoDB database. The documents will contain the fields/schema types defined in the model Schema.

-
- -

Defining schemas

- -

The code fragment below shows how you might define a simple schema. First you require() mongoose, then use the Schema constructor to create a new schema instance, defining the various fields inside it in the constructor's object parameter.

- -
//Require Mongoose
-var mongoose = require('mongoose');
-
-//Define a schema
-var Schema = mongoose.Schema;
-
-var SomeModelSchema = new Schema({
-    a_string: String,
-    a_date: Date
-});
-
- -

In the case above we just have two fields, a string and a date. In the next sections we will show some of the other field types, validation, and other methods.

- -

Creating a model

- -

Models are created from schemas using the mongoose.model() method:

- -
// Define schema
-var Schema = mongoose.Schema;
-
-var SomeModelSchema = new Schema({
-    a_string: String,
-    a_date: Date
-});
-
-// Compile model from schema
-var SomeModel = mongoose.model('SomeModel', SomeModelSchema );
- -

The first argument is the singular name of the collection that will be created for your model (Mongoose will create the database collection for the above model SomeModel above), and the second argument is the schema you want to use in creating the model.

- -
-

Note: Once you've defined your model classes you can use them to create, update, or delete records, and to run queries to get all records or particular subsets of records. We'll show you how to do this in the Using models section, and when we create our views.

-
- -

Tipos de esquema (campos)

- -

Un esquema puede tener un número de campos arbitrario  — cada uno representa un campo en los documentos almacenados en MongoDB. A continuación se muestra un ejemplo de esquema con varios de los tipos de campos más comunes y cómo se declaran.

- -
var schema = new Schema(
-{
-  name: String,
-  binary: Buffer,
-  living: Boolean,
-  updated: { type: Date, default: Date.now },
-  age: { type: Number, min: 18, max: 65, required: true },
-  mixed: Schema.Types.Mixed,
-  _someId: Schema.Types.ObjectId,
-  array: [],
-  ofString: [String], // You can also have an array of each of the other types too.
-  nested: { stuff: { type: String, lowercase: true, trim: true } }
-})
- -

Most of the SchemaTypes (the descriptors after “type:” or after field names) are self explanatory. The exceptions are:

- - - -

The code also shows both ways of declaring a field:

- - - -

For more information about options see SchemaTypes (Mongoose docs).

- -

Validation

- -

Mongoose provides built-in and custom validators, and synchronous and asynchronous validators. It allows you to specify both the acceptable range or values and the error message for validation failure in all cases.

- -

The built-in validators include:

- - - -

The example below (slightly modified from the Mongoose documents) shows how you can specify some of the validator types and error messages:

- -

-    var breakfastSchema = new Schema({
-      eggs: {
-        type: Number,
-        min: [6, 'Too few eggs'],
-        max: 12,
-        required: [true, 'Why no eggs?']
-      },
-      drink: {
-        type: String,
-        enum: ['Coffee', 'Tea', 'Water',]
-      }
-    });
-
- -

For complete information on field validation see Validation (Mongoose docs).

- -

Virtual properties

- -

Virtual properties are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields, while setters are useful for de-composing a single value into multiple values for storage. The example in the documentation constructs (and deconstructs) a full name virtual property from a first and last name field, which is easier and cleaner than constructing a full name every time one is used in a template.

- -
-

Note: We will use a virtual property in the library to define a unique URL for each model record using a path and the record's _id value.

-
- -

For more information see Virtuals (Mongoose documentation).

- -

Methods and query helpers

- -

A schema can also have instance methods, static methods, and query helpers. The instance and static methods are similar, but with the obvious difference that an instance method is associated with a particular record and has access to the current object. Query helpers allow you to extend mongoose's chainable query builder API (for example, allowing you to add a query "byName" in addition to the find(), findOne() and findById() methods).

- -

Using models

- -

Once you've created a schema you can use it to create models. The model represents a collection of documents in the database that you can search, while the model's instances represent individual documents that you can save and retrieve.

- -

We provide a brief overview below. For more information see: Models (Mongoose docs).

- -

Creating and modifying documents

- -

To create a record you can define an instance of the model and then call save(). The examples below assume SomeModel is a model (with a single field "name") that we have created from our schema.

- -
// Create an instance of model SomeModel
-var awesome_instance = new SomeModel({ name: 'awesome' });
-
-// Save the new model instance, passing a callback
-awesome_instance.save(function (err) {
-  if (err) return handleError(err);
-  // saved!
-});
-
- -

Creation of records (along with updates, deletes, and queries) are asynchronous operations — you supply a callback that is called when the operation completes. The API uses the error-first argument convention, so the first argument for the callback will always be an error value (or null). If the API returns some result, this will be provided as the second argument.

- -

You can also use create() to define the model instance at the same time as you save it. The callback will return an error for the first argument and the newly-created model instance for the second argument.

- -
SomeModel.create({ name: 'also_awesome' }, function (err, awesome_instance) {
-  if (err) return handleError(err);
-  // saved!
-});
- -

Every model has an associated connection (this will be the default connection when you use mongoose.model()). You create a new connection and call .model() on it to create the documents on a different database.

- -

You can access the fields in this new record using the dot syntax, and change the values. You have to call save() or update() to store modified values back to the database.

- -
// Access model field values using dot notation
-console.log(awesome_instance.name); //should log 'also_awesome'
-
-// Change record by modifying the fields, then calling save().
-awesome_instance.name="New cool name";
-awesome_instance.save(function (err) {
-   if (err) return handleError(err); // saved!
-   });
-
- -

Searching for records

- -

You can search for records using query methods, specifying the query conditions as a JSON document. The code fragment below shows how you might find all athletes in a database that play tennis, returning just the fields for athlete name and age. Here we just specify one matching field (sport) but you can add more criteria, specify regular expression criteria, or remove the conditions altogether to return all athletes.

- -
var Athlete = mongoose.model('Athlete', yourSchema);
-
-// find all athletes who play tennis, selecting the 'name' and 'age' fields
-Athlete.find({ 'sport': 'Tennis' }, 'name age', function (err, athletes) {
-  if (err) return handleError(err);
-  // 'athletes' contains the list of athletes that match the criteria.
-})
- -

If you specify a callback, as shown above, the query will execute immediately. The callback will be invoked when the search completes.

- -
-

Note: All callbacks in Mongoose use the pattern callback(error, result). If an error occurs executing the query, the error parameter will contain an error document, and result will be null. If the query is successful, the error parameter will be null, and the result will be populated with the results of the query.

-
- -

If you don't specify a callback then the API will return a variable of type Query. You can use this query object to build up your query and then execute it (with a callback) later using the exec() method.

- -
// find all athletes that play tennis
-var query = Athlete.find({ 'sport': 'Tennis' });
-
-// selecting the 'name' and 'age' fields
-query.select('name age');
-
-// limit our results to 5 items
-query.limit(5);
-
-// sort by age
-query.sort({ age: -1 });
-
-// execute the query at a later time
-query.exec(function (err, athletes) {
-  if (err) return handleError(err);
-  // athletes contains an ordered list of 5 athletes who play Tennis
-})
- -

Above we've defined the query conditions in the find() method. We can also do this using a where() function, and we can chain all the parts of our query together using the dot operator (.) rather than adding them separately. The code fragment below is the same as our query above, with an additional condition for the age.

- -
Athlete.
-  find().
-  where('sport').equals('Tennis').
-  where('age').gt(17).lt(50).  //Additional where query
-  limit(5).
-  sort({ age: -1 }).
-  select('name age').
-  exec(callback); // where callback is the name of our callback function.
- -

The find() method gets all matching records, but often you just want to get one match. The following methods query for a single record:

- - - -
-

Note: There is also a count() method that you can use to get the number of items that match conditions. This is useful if you want to perform a count without actually fetching the records.

-
- -

There is a lot more you can do with queries. For more information see: Queries (Mongoose docs).

- - - -

You can create references from one document/model instance to another using the ObjectId schema field, or from one document to many using an array of ObjectIds. The field stores the id of the related model. If you need the actual content of the associated document, you can use the populate() method in a query to replace the id with the actual data.

- -

For example, the following schema defines authors and stories. Each author can have multiple stories, which we represent as an array of ObjectId. Each story can have a single author. The "ref" (highlighted in bold below) tells the schema which model can be assigned to this field.

- -
var mongoose = require('mongoose')
-  , Schema = mongoose.Schema
-
-var authorSchema = Schema({
-  name    : String,
-  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
-});
-
-var storySchema = Schema({
-  author : { type: Schema.Types.ObjectId, ref: 'Author' },
-  title    : String
-});
-
-var Story  = mongoose.model('Story', storySchema);
-var Author = mongoose.model('Author', authorSchema);
- -

We can save our references to the related document by assigning the _id value. Below we create an author, then a story, and assign the author id to our stories author field.

- -
var bob = new Author({ name: 'Bob Smith' });
-
-bob.save(function (err) {
-  if (err) return handleError(err);
-
-  //Bob now exists, so lets create a story
-  var story = new Story({
-    title: "Bob goes sledding",
-    author: bob._id    // assign the _id from the our author Bob. This ID is created by default!
-  });
-
-  story.save(function (err) {
-    if (err) return handleError(err);
-    // Bob now has his story
-  });
-});
- -

Our story document now has an author referenced by the author document's ID. In order to get the author information in our story results we use populate(), as shown below.

- -
Story
-.findOne({ title: 'Bob goes sledding' })
-.populate('author') //This populates the author id with actual author information!
-.exec(function (err, story) {
-  if (err) return handleError(err);
-  console.log('The author is %s', story.author.name);
-  // prints "The author is Bob Smith"
-});
- -
-

Note: Astute readers will have noted that we added an author to our story, but we didn't do anything to add our story to our author's stories array. How then can we get all stories by a particular author? One way would be to add our author to the stories array, but this would result in us having two places where the information relating authors and stories needs to be maintained.

- -

A better way is to get the _id of our author, then use find() to search for this in the author field across all stories.

- -
Story
-.find({ author : bob._id })
-.exec(function (err, stories) {
-  if (err) return handleError(err);
-  // returns all stories that have Bob's id as their author.
-});
-
-
- -

This is almost everything you need to know about working with related items for this tutorial. For more detailed information see Population (Mongoose docs).

- -

One schema/model per file

- -

While you can create schemas and models using any file structure you like, we highly recommend defining each model schema in its own module (file), exporting the method to create the model. This is shown below:

- -
// File: ./models/somemodel.js
-
-//Require Mongoose
-var mongoose = require('mongoose');
-
-//Define a schema
-var Schema = mongoose.Schema;
-
-var SomeModelSchema = new Schema({
-    a_string          : String,
-    a_date            : Date,
-});
-
-//Export function to create "SomeModel" model class
-module.exports = mongoose.model('SomeModel', SomeModelSchema );
- -

You can then require and use the model immediately in other files. Below we show how you might use it to get all instances of the model.

- -
//Create a SomeModel model just by requiring the module
-var SomeModel = require('../models/somemodel')
-
-// Use the SomeModel object (model) to find all SomeModel records
-SomeModel.find(callback_function);
- -

Setting up the MongoDB database

- -

Now that we understand something of what Mongoose can do and how we want to design our models, it's time to start work on the LocalLibrary website. The very first thing we want to do is set up a MongoDb database that we can use to store our library data.

- -

For this tutorial we're going to use mLab's free cloud-hosted "sandbox" database. This database tier is not considered suitable for production websites because it has no redundancy, but it is great for development and prototyping. We're using it here because it is free and easy to set up, and because mLab is a popular database as a service vendor that you might reasonably choose for your production database (other popular choices at the time of writing include Compose, ScaleGrid and MongoDB Atlas).

- -
-

Note: If you prefer you can set up a MongoDb database locally by downloading and installing the appropriate binaries for your system. The rest of the instructions in this article would be similar, except for the database URL you would specify when connecting.

-
- -

You will first need to create an account with mLab (this is free, and just requires that you enter basic contact details and acknowledge their terms of service). 

- -

After logging in, you'll be taken to the home screen:

- -
    -
  1. Click Create New in the MongoDB Deployments section.
  2. -
  3. This will open the Cloud Provider Selection screen.
    - MLab - screen for new deployment
    - -
      -
    • Select the SANDBOX (Free) plan from the Plan Type section. 
    • -
    • Select any provider from the Cloud Provider section. Different providers offer different regions (displayed below the selected plan type).
    • -
    • Click the Continue button.
    • -
    -
  4. -
  5. This will open the Select Region screen. -

    Select new region screen

    - -
      -
    • -

      Select the region closest to you and then Continue.

      -
    • -
    -
  6. -
  7. -

    This will open the Final Details screen.
    - New deployment database name

    - -
      -
    • -

      Enter the name for the new database as local_library and then select Continue.

      -
    • -
    -
  8. -
  9. -

    This will open the Order Confirmation screen.
    - Order confirmation screen

    - -
      -
    • -

      Click Submit Order to create the database.

      -
    • -
    -
  10. -
  11. -

    You will be returned to the home screen. Click on the new database you just created to open its details screen. As you can see the database has no collections (data).
    - mLab - Database details screen
    -  
    - The URL that you need to use to access your database is displayed on the form above (shown for this database circled above). In order to use this you need to create a database user that you can specify in the URL.

    -
  12. -
  13. Click the Users tab and select the Add database user button.
  14. -
  15. Enter a username and password (twice), and then press Create. Do not select Make read only.
    -
  16. -
- -

You have now created the database, and have an URL (with username and password) that can be used to access it. This will look something like: mongodb://your_user_namer:your_password@ds119748.mlab.com:19748/local_library.

- -

Install Mongoose

- -

Open a command prompt and navigate to the directory where you created your skeleton Local Library website. Enter the following command to install Mongoose (and its dependencies) and add it to your package.json file, unless you have already done so when reading the Mongoose Primer above.

- -
npm install mongoose
-
- -

Connect to MongoDB

- -

Open /app.js (in the root of your project) and copy the following text below where you declare the Express application object (after the line var app = express();). Replace the database url string ('insert_your_database_url_here') with the location URL representing your own database (i.e. using the information from mLab).

- -
//Set up mongoose connection
-var mongoose = require('mongoose');
-var mongoDB = 'insert_your_database_url_here';
-mongoose.connect(mongoDB);
-mongoose.Promise = global.Promise;
-var db = mongoose.connection;
-db.on('error', console.error.bind(console, 'MongoDB connection error:'));
- -

As discussed in the Mongoose primer above, this code creates the default connection to the database and binds to the error event (so that errors will be printed to the console). 

- -

Defining the LocalLibrary Schema

- -

We will define a separate module for each model, as discussed above. Start by creating a folder for our models in the project root (/models) and then create separate files for each of the models:

- -
/express-locallibrary-tutorial  //the project root
-  /models
-    author.js
-    book.js
-    bookinstance.js
-    genre.js
-
- -

Author model

- -

Copy the Author schema code shown below and paste it into your ./models/author.js file. The scheme defines an author has having String SchemaTypes for the first and family names, that are required and have a maximum of 100 characters, and Date fields for the date of birth and death.

- -
var mongoose = require('mongoose');
-
-var Schema = mongoose.Schema;
-
-var AuthorSchema = new Schema(
-  {
-    first_name: {type: String, required: true, max: 100},
-    family_name: {type: String, required: true, max: 100},
-    date_of_birth: {type: Date},
-    date_of_death: {type: Date},
-  }
-);
-
-// Virtual for author's full name
-AuthorSchema
-.virtual('name')
-.get(function () {
-  return this.family_name + ', ' + this.first_name;
-});
-
-// Virtual for author's lifespan
-AuthorSchema
-.virtual('lifespan')
-.get(function () {
-  return (this.date_of_death.getYear() - this.date_of_birth.getYear()).toString();
-});
-
-// Virtual for author's URL
-AuthorSchema
-.virtual('url')
-.get(function () {
-  return '/catalog/author/' + this._id;
-});
-
-//Export model
-module.exports = mongoose.model('Author', AuthorSchema);
-
-
- -

We've also declared a virtual for the AuthorSchema named "url" that returns the absolute URL required to get a particular instance of the model — we'll use the property in our templates whenever we need to get a link to a particular author.

- -
-

Note: Declaring our URLs as a virtual in the schema is a good idea because then the URL for an item only ever needs to be changed in one place.
- At this point, a link using this URL wouldn't work, because we haven't got any routes handling code for individual model instances. We'll set those up in a later article!

-
- -

At the end of the module we export the model.

- -

Book model

- -

Copy the Book schema code shown below and paste it into your ./models/book.js file. Most of this is similar to the author model — we've declared a schema with a number of string fields and a virtual for getting the URL of specific book records, and we've exported the model.

- -
var mongoose = require('mongoose');
-
-var Schema = mongoose.Schema;
-
-var BookSchema = new Schema(
-  {
-    title: {type: String, required: true},
-    author: {type: Schema.Types.ObjectId, ref: 'Author', required: true},
-    summary: {type: String, required: true},
-    isbn: {type: String, required: true},
-    genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}]
-  }
-);
-
-// Virtual for book's URL
-BookSchema
-.virtual('url')
-.get(function () {
-  return '/catalog/book/' + this._id;
-});
-
-//Export model
-module.exports = mongoose.model('Book', BookSchema);
-
- -

The main difference here is that we've created two references to other models:

- - - -

BookInstance model

- -

Finally, copy the BookInstance schema code shown below and paste it into your ./models/bookinstance.js file. The BookInstance represents a specific copy of a book that someone might borrow, and includes information about whether the copy is available or on what date it is expected back, "imprint" or version details.

- -
var mongoose = require('mongoose');
-
-var Schema = mongoose.Schema;
-
-var BookInstanceSchema = new Schema(
-  {
-    book: { type: Schema.Types.ObjectId, ref: 'Book', required: true }, //reference to the associated book
-    imprint: {type: String, required: true},
-    status: {type: String, required: true, enum: ['Available', 'Maintenance', 'Loaned', 'Reserved'], default: 'Maintenance'},
-    due_back: {type: Date, default: Date.now}
-  }
-);
-
-// Virtual for bookinstance's URL
-BookInstanceSchema
-.virtual('url')
-.get(function () {
-  return '/catalog/bookinstance/' + this._id;
-});
-
-//Export model
-module.exports = mongoose.model('BookInstance', BookInstanceSchema);
- -

The new things we show here are the field options:

- - - -

Everything else should be familiar from our previous schema.

- -

Genre model - challenge!

- -

Open your ./models/genre.js file and create a schema for storing genres (the category of book, e.g. whether it is fiction or non-fiction, romance or military history, etc).

- -

The definition will be very similar to the other models:

- - - -

Testing — create some items

- -

That's it. We now have all models for the site set up!

- -

In order to test the models (and to create some example books and other items that we can use in our next articles) we'll now run an independent script to create items of each type:

- -
    -
  1. Download (or otherwise create) the file populatedb.js inside your express-locallibrary-tutorial directory (in the same level as package.json). - -
    -

    Note: You don't need to know how populatedb.js works; it just adds sample data into the database.

    -
    -
  2. -
  3. Enter the following commands in the project root to install the async module that is required by the script (we'll discuss this in later tutorials, ) -
    npm install async
    -
  4. -
  5. Run the script using node in your command prompt, passing in the URL of your MongoDB database (the same one you replaced the insert_your_database_url_here placeholder with, inside app.js earlier): -
    node populatedb <your mongodb url>​​​​
    -
  6. -
  7. The script should run through to completion, displaying items as it creates them in the terminal.
  8. -
- -
-

Tip: Go to your database on mLab. You should now be able to drill down into individual collections of Books, Authors, Genres and BookInstances, and check out individual documents.

-
- -

Summary

- -

In this article, we've learned a bit about databases and ORMs on Node/Express, and a lot about how Mongoose schema and models are defined. We then used this information to design and implement Book, BookInstance, Author and Genre models for the LocalLibrary website.

- -

Last of all we tested our models by creating a number of instances (using a standalone script). In the next article we'll look at creating some pages to display these objects.

- -

See also

- - - -

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/es/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.html b/files/es/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.html deleted file mode 100644 index 3acb3d4039..0000000000 --- a/files/es/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.html +++ /dev/null @@ -1,295 +0,0 @@ ---- -title: Primeros pasos con Vue -slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started -translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started -original_slug: >- - Learn/Herramientas_y_pruebas/Lado-del-cliente_JavaScript_frameworks/Vue_primeros_pasos ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
- -

Ahora vamos a introducir Vue, el tercero de nuestros frameworks. En este articulo vamos a ver un poco del background de Vue, aprenderemos cómo instalarlo y a crear un nuevo proyecto, estudiar la estructura de alto nivel de todo el proyecto y un componente individual, sabremos como correr el proyecto localmente, y tenerlo preparado para empezar a construir nuestro ejemplo.

- - - - - - - - - - - - -
Pre-requisitos: -

Familiaridad con los motores de los lenguajes  HTML, CSS, y  JavaScript languages, conocimiento del terminal/command line.

- -

Los componentes Vue son escritos como una combinacion de objectos Javascript que administran los datos de la app y una sintaxis de plantilla basada en HTML que se enlaza con la estructura DOM subyacente. Para la instalación, y para usar algunas de las caracteristicas mas avanzadas de Vue (como Componentes de archivos simples o renderizado de funciones), vas a necesitar un terminar con node + npm instalados.

-
Objetivo:Configurar un entorno de desarrollo local de Vue, crear una app de inicio y entender los principios de su funcionamiento.
- -

Un Vue más claro

- -

Vue es un framework moderno de Javascript que proveé facilidades muy utiles para el mejoramiento progresivo- al contrario de otros frameworks, puedes usar Vue para mejorar un HTML exstente. Esto permite usar Vue como un remplazo agregado para una libreria como JQuery.

- -

Habiendo dicho esto, tambien puedes usar Vue para escribir completamente una aplicación de una sola página(SPAs).This allows you to create markup managed entirely by Vue, which can improve developer experience and performance when dealing with complex applications. It also allows you to take advantage of libraries for client-side routing and state management when you need to. Additionally, Vue takes a "middle ground" approach to tooling like client-side routing and state management. While the Vue core team maintains suggested libraries for these functions, they are not directly bundled into Vue. This allows you to select a different routing/state management library if they better fit your application.

- -

In addition to allowing you to progressively integrate Vue into your applications, Vue also provides a progressive approach to writing markup. Like most frameworks, Vue lets you create reusable blocks of markup via components. Most of the time, Vue components are written using a special HTML template syntax. When you need more control than the HTML syntax allows, you can write JSX or plain JavaScript functions to define your  components.

- -

As you work through this tutorial, you might want to keep the Vue guide and API documentation open in other tabs, so you can refer to them if you want more information on any sub topic.
- For a good (but potentially biased) comparison between Vue and many of the other frameworks, see Vue Docs: Comparison with Other Frameworks.

- -

Installation

- -

To use Vue in an existing site, you can drop one of the following <script> elements onto a page. This allows you to start using Vue on existing sites, which is why Vue prides itself on being a progressive framework. This is a great option when migrating an existing project using a library like JQuery to Vue. With this method, you can use a lot of the core features of Vue, such as the attributes, custom components, and data-management.

- - - -

However, this approach has some limitations. To build more complex apps, you’ll want to use the Vue NPM package. This will let you use advanced features of Vue and take advantage of bundlers like WebPack. To make building apps with Vue easier, there is a CLI to streamline the development process. To use the npm package & the CLI you will need:

- -
    -
  1. Node.js 8.11+ installed.
  2. -
  3. npm or yarn.
  4. -
- -
-

Note: If you don't have the above installed, find out more about installing npm and Node.js here.

-
- -

To install the CLI, run the following command in your terminal:

- -
npm install --global @vue/cli
- -

Or if you'd prefer to use yarn:

- -
yarn global add @vue/cli
- -

Once installed, to initialize a new project you can then open a terminal in the directory you want to create the project in, and run vue create <project-name>. The CLI will then give you a list of project configurations you can use. There are a few preset ones, and you can make your own. These options let you configure things like TypeScript, linting, vue-router, testing, and more.

- -

We’ll look at using this below.

- -

Initializing a new project

- -

To explore various features of Vue, we will be building up a sample todo list app. We'll begin by using the Vue CLI to create a new app framework to build our app into. Follow the steps below:

- -
    -
  1. In terminal, cd to where you'd like to create your sample app, then run vue create moz-todo-vue.
  2. -
  3. Use the arrow keys and Enter to select the "Manually select features" option.
  4. -
  5. The first menu you’ll be presented with allows you to choose which features you want to include in your project. Make sure that "Babel" and "Linter / Formatter" are selected. If they are not, use the arrow keys and the space bar to toggle them on. Once they are selected, press Enter to proceed.
  6. -
  7. Next you’ll select a config for the linter / formatter. Navigate to "Eslint with error prevention only" and hit Enter again. This will help us catch common errors, but not be overly opinionated.
  8. -
  9. Next you are asked to configure what kind of automated linting we want. Select "Lint on save". This will check for errors when we save a file inside the project. Hit Enter to continue.
  10. -
  11. Now, you will select how we want your config files to be managed. "In dedicated config files" will put your config settings for things like ESLint into their own, dedicated files. The other option, "In package.json", will put all of your config settings into the app's package.json file. Select "In dedicated config files" and push Enter.
  12. -
  13. Finally, you are asked if you want to save this as a preset for future options. This is entirely up to you. If you like these settings over the existing presets and want to use them again, type y , otherwise type n.
  14. -
- -

The CLI will now begin scaffolding out your project, and installing all of your dependencies.

- -

If you've never run the Vue CLI before, you'll get one more question — you'll be asked to choose a package manager. You can use the arrow keys to select which one you prefer. The Vue CLI will default to this package manager from now on. If you need to use a different package manager after this, you can pass in a flag --packageManager=<package-manager>, when you run vue create.  So if you wanted to create the moz-todo-vue project with npm and you'd previously chosen yarn, you’d run vue create moz-todo-vue --packageManager=npm.

- -
-

Note: We've not gone over all of the options here, but you can find more information on the CLI in the Vue docs.

-
- -

Project structure

- -

If everything went successfully, the CLI should have created a series of files and directories for your project. The most significant ones are as follows:

- - - -
-

Note: Depending on the options you select when creating a new project, there might be other directories present (for example, if you choose a router, you will also have a views directory).

-
- -

.vue files (single file components)

- -

Like in many front-end frameworks, components are a central part of building apps in Vue. These components let you break a large application into discrete building blocks that can be created and managed separately, and transfer data between each other as required. These small blocks can help you reason about and test your code.

- -

While some frameworks encourage you to separate your template, logic, and styling code into separate files, Vue takes the opposite approach. Using Single File Components, Vue lets you group your templates, corresponding script, and CSS all together in a single file ending in .vue. These files are processed by a JS build tool (such as Webpack), which means you can take advantage of build-time tooling in your project. This allows you to use tools like Babel, TypeScript, SCSS and more to create more sophisticated components.

- -

As a bonus, projects created with the Vue CLI are configured to use .vue files with Webpack out of the box. In fact, if you look inside the src folder in the project we created with the CLI, you'll see your first .vue file: App.vue.

- -

Let's explore this now.

- -

App.vue

- -

Open your App.vue file — you’ll see that it has three parts: <template>, <script>, and <style>, which contain the component’s template, scripting, and styling information. All Single File Components share this same basic structure.

- -

<template> contains all the markup structure and display logic of your component. Your template can contain any valid HTML, as well as some Vue-specific syntax that we'll cover later.

- -
-

Note: By setting the lang attribute on the <template> tag, you can use Pug template syntax instead of standard HTML — <template lang="pug">. We'll stick to standard HTML through this tutorial, but it is worth knowing that this is possible.

-
- -

<script> contains all of the non-display logic of your component. Most importantly, your <script> tag needs to have a default exported JS object. This object is where you locally register components, define component inputs (props), handle local state, define methods, and more. Your build step will process this object and transform it (with your template) into a Vue component with a render() function.

- -

In the case of App.vue, our default export sets the name of the component to app and registers the HelloWorld component by adding it into the components property. When you register a component in this way, you're registering it locally. Locally registered components can only be used inside the components that register them, so you need to import and register them in every component file that uses them. This can be useful for bundle splitting/tree shaking since not every page in your app necessarily needs every component.

- -
import HelloWorld from './components/HelloWorld.vue';
-
-export default {
-  name: 'app',
-  components: {
-    //You can register components locally here.
-    HelloWorld
-  }
-};
- -
-

Note: If you want to use TypeScript syntax, you need to set the lang attribute on the <script> tag to signify to the compiler that you're using TypeScript — <script lang="ts">.

-
- -

<style> is where you write your CSS for the component. If you add a scoped attribute — <style scoped> — Vue will scope the styles to the contents of your SFC. This works similar to CSS-in-JS solutions, but allows you to just write plain CSS.

- -
-

Note: If you select a CSS pre-processor when creating the project via the CLI, you can add a lang attribute to the <style> tag so that the contents can be processed by Webpack at build time. For example, <style lang="scss"> will allow you to use SCSS syntax in your styling information.

-
- -

Running the app locally

- -

The Vue CLI comes with a built-in development server. This allows you to run your app locally so you can test it easily without needing to configure a server yourself. The CLI adds a serve command to the project’s package.json file as an npm script, so you can easily run it.

- -

In your terminal, try running npm run serve (or yarn serve if you prefer yarn). Your terminal should output something like the following:

- -
INFO  Starting development server...
-98% after emitting CopyPlugin
-
- DONE  Compiled successfully in 18121ms
-
-  App running at:
-  - Local:   <http://localhost:8080/>
-  - Network: <http://192.168.1.9:8080/>
-
-  Note that the development build is not optimized.
-  To create a production build, run npm run build.
- -

If you navigate to the “local” address in a new browser tab (this should be something like http://localhost:8080 as stated above, but may vary based on your setup), you should see your app. Right now, it should contain a welcome message, a link to the Vue documentation, links to the plugins you added when you initialized the app with your CLI, and some other useful links to the Vue community and ecosystem.

- -

default vue app render, with vue logo, welcome message, and some documentation links

- -

Making a couple of changes

- -

Let's make our first change to the app — we’ll delete the Vue logo. Open the App.vue file, and delete the <img> element from the template section:

- -
<img alt="Vue logo" src="./assets/logo.png">
- -

If your server is still running, you should see the logo removed from the rendered site almost instantly. Let’s also remove the HelloWorld component from our template.

- -

First of all delete this line:

- -
<HelloWorld msg="Welcome to Your Vue.js App"/>
- -

If you save your App.vue file now, the rendered app will throw an error because we’ve registered the component but are not using it. We also need to remove the lines from inside the <script> element that import and register the component:

- -

Delete these lines now:

- -
import HelloWorld from './components/HelloWorld.vue'
- -
components: {
-  HelloWorld
-}
- -

Your rendered app should no longer show an error, just a blank page, as we currently have no visible content inside <template>.

- -

Let’s add a new <h1> inside <div id="app">. Since we’re going to be creating a todo list app below, let's set our header text to "To-Do List". Add it like so:

- -
<template>
-  <div id="app">
-    <h1>To-Do List</h1>
-  </div>
-</template>
- -

App.vue will now show our heading, as you'd expect.

- -

Summary

- -

Let's leave this here for now. We've learnt about some of the ideas behind Vue, created some scaffolding for our example app to live inside, inspected it, and made a few preliminary changes.

- -

With a basic introduction out of the way, we'll now go further and build up our sample app, a basic Todo list application that allows us to store a list of items, check them off when done, and filter the list by all, complete, and incomplete todos.

- -

In the next article we'll build our first custom component, and look at some important concepts such as passing props into it and saving its data state.

- -

{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}

- -

In this module

- - diff --git a/files/es/mdn/contribute/howto/document_a_css_property/index.html b/files/es/mdn/contribute/howto/document_a_css_property/index.html deleted file mode 100644 index 41b3fcb14f..0000000000 --- a/files/es/mdn/contribute/howto/document_a_css_property/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Cómo documentar una propiedad CSS -slug: MDN/Contribute/Howto/Document_a_CSS_property -translation_of: MDN/Contribute/Howto/Document_a_CSS_property ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/en-US/docs/MDN")}}
- -

As the CSS standards evolve, new properties are always being added. The MDN CSS Reference needs to be kept up to date with these developments. This document gives step-by-step instructions for creating a CSS property reference page.

- -

Each CSS property reference page follows the same structure. This helps readers find information more easily, especially once they are familiar with the standard reference page format.

- -

Step 1 — Decide which property to document

- -

First, you will need to decide which property to document. The CSS Documentation status page lists properties that need to be documented. For details about the CSS property you will need to find a relevant specification for it (e.g., a W3C specification, a Mozilla Wiki page, or a bug report for a non-standard property used in rendering engines like Gecko or Blink).

- -
-

Pro tips:

- - -
- -

Step 2 — Check the database of CSS properties

- -

Several characteristics of a CSS property, such as its syntax or if it can be animated, are mentioned in several pages and are therefore stored in an ad-hoc database. Macros that you'll use on the page need information about the property that is stored there, so start by checking that this information is there.

- -

If not, contact an admin or a power user, either on the MDN Web Docs chat room, or, if nobody is available, by filing an issue report.

- -

Step 3 — Creating the CSS property page

- -

Preparations finished! Now we can add the actual CSS property page. The easiest way to create a new CSS property page is to copy the content of an existing page and to edit it. We will go through the different steps now.

- -
-

Cloning a page is currently broken on MDN. That's why we need to go through these somewhat more complex steps. Please vote for ({{bug(870691)}}).

-
- -
    -
  1. Clone the following page, set the title to your-property (without capitals) and the slug to Web/CSS/your-property.
  2. -
  3. Change the summary to fit, but keep it starting the same way : "The your-property CSS property…". Explain briefly what this property is for.
  4. -
  5. If the property is not experimental, remove the \{{SeeCompatTable}} macro. The purpose of this macro is to alert developers to the possibility that the feature may not yet have consistent support across browsers, and may change in the future as its specificaton evolves. Deciding whether a feature is experimental is a matter of judgement, and should include factors like: -
      -
    • Is the feature supported by several browsers?
    • -
    • Is the feature prefixed or behind a preference?
    • -
    • Is there any reason to think that the implementation of the feature will change in the future?
    • -
    -
  6. -
  7. Replace the parameter of the \{{cssinfo("animation-name")}} macro by the name of the CSS property you are documenting. This will allow you to build the summary box using the data you entered in step 2.
  8. -
  9. Replace the example of the syntax by relevant ones. Keep them very simple and don't forget that a lot of people don't understand a formal syntax so it needs to be simple and exhaustive. Keep the inherit, initial, and unset keywords examples at the end. It reminds users that these are valid values, too.
  10. -
  11. Under the chapter Values, put the meaning of each value. If it is a keyword, don't forget to mark it as code (select it and press CTRL-O). Each description should start by "Is a" followed by the type of the value, or indicating it is a keyword.
  12. -
  13. Clear the Examples chapter, we will add them at the end!
  14. -
  15. Update the specification table. For information about how to do it, read this tutorial.
  16. -
  17. Update the compatibility information. For information about how to do it, read this tutorial.
  18. -
  19. Update the See also section with relevant links. Do not link to specs here and usually link to internal documents. External documents are welcome, but only if they bring really good information. There are spam or SEO links often, so don't worry if external links are removed sometimes. Just start the discussion if you still find it useful and want to see it back.
  20. -
  21. Add the relevant tags: you need to add CSS, CSS Property, and Reference. You also need to add Experimental or Non-standard if this is the case. Finally you also need to add a CSS XYZ tag, where XYZ stands for the group of CSS properties it belongs to. It is often the spec short name. All these tags are used to generate quicklinks and other niceties.
  22. -
- -

At any point, you can save by hitting the SAVE button. You can continue to edit right along. If you haven't saved your page until now, please do so! :-)

- -

The last step is to add Examples. To do that follow this tutorial about live samples. Don't forget that we are in a document explaining one single property: you need to add examples that show how this property is working in isolation, not how the whole specification is used. That means, examples for list-style-type will show what the different values generate, but not how to combine it with other property, pseudo-classes or pseudo-elements to generate nice effects; tutorials and guide can be written to show more.

- -

Step 4 — Getting a review

- -

You have documented your CSS property! Congratulations!

- -

In order to have a good quality and consistency throughout the MDN CSS reference, it is good practice to request a review. Just click on the checkbox at the bottom of the article (in edit mode), and, optional, if you want to have a more personal review helping you to improve editorial skills, ask for it on the MDN forum.

- -

Step 5 — Integrating the new page in the MDN

- -

Now that your page is created, you want it to be found by the readers. Adding tags helped about this already as it allowed it to appear in the quicklinks to related CSS pages. Also you want it to appear on the CSS index page. If the newly documented property is on the standard track and at least one major browser is implementing it, it deserves to be listed this. Only administrator can add it there, so contact the CSS driver on IRC (currently at #mdn ping teoli) or file a documentation bug requesting it.

- -

Also, if the property is implemented by Firefox, you need to check that it is listed, and linked! in the correct Firefox for developers MDN page. The new CSS property is likely already listed in the HTML section, just be sure that its name links back to your newly created page.

- -

Contact us

- - diff --git a/files/es/mozilla/add-ons/webextensions/api/webnavigation/index.html b/files/es/mozilla/add-ons/webextensions/api/webnavigation/index.html deleted file mode 100644 index d561c6d796..0000000000 --- a/files/es/mozilla/add-ons/webextensions/api/webnavigation/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: webNavigation -slug: Mozilla/Add-ons/WebExtensions/API/webNavigation -translation_of: Mozilla/Add-ons/WebExtensions/API/webNavigation ---- -
{{AddonSidebar}}
- -

Add event listeners for the various stages of a navigation. A navigation consists of a frame in the browser transitioning from one URL to another, usually (but not always) in response to a user action like clicking a link or entering a URL in the location bar.

- -

Compared with the {{WebExtAPIRef("webRequest")}} API: navigations usually result in the browser making web requests, but the webRequest API is concerned with the lower-level view from the HTTP layer, while the webNavigation API is more concerned with the view from the browser UI itself.

- -

Each event corresponds to a particular stage in the navigation. The sequence of events is like this:

- -

- - - -

Each navigation is a URL transition in a particular browser frame. The browser frame is identified by a tab ID and a frame ID. The frame may be the top-level browsing context in the tab, or may be a nested browsing context implemented as an iframe.

- -

Each event's addListener() call accepts an optional filter parameter. The filter will specify one or more URL patterns, and the event will then only be fired for navigations in which the target URL matches one of the patterns.

- -

The onCommitted event listener is passed two additional properties: a {{WebExtAPIRef("webNavigation.TransitionType","TransitionType")}} indicating the cause of the navigation (for example, because the user clicked a link, or because the user selected a bookmark), and a {{WebExtAPIRef("webNavigation.TransitionQualifier","TransitionQualifier")}} providing further information about the navigation.

- -

To use this API you need to have the "webNavigation" permission.

- -

Types

- -
-
{{WebExtAPIRef("webNavigation.TransitionType")}}
-
Cause of the navigation: for example, the user clicked a link, or typed an address, or clicked a bookmark.
-
{{WebExtAPIRef("webNavigation.TransitionQualifier")}}
-
-
Extra information about a transition.
-
-
- -

Functions

- -
-
{{WebExtAPIRef("webNavigation.getFrame()")}}
-
Retrieves information about a particular frame. A frame may be the top-level frame in a tab or a nested iframe, and is uniquely identified by a tab ID and a frame ID.
-
{{WebExtAPIRef("webNavigation.getAllFrames()")}}
-
-

Given a tab ID, retrieves information about all the frames it contains.

-
-
- -

Events

- -
-
{{WebExtAPIRef("webNavigation.onBeforeNavigate")}}
-
-

Fired when the browser is about to start a navigation event.

-
-
{{WebExtAPIRef("webNavigation.onCommitted")}}
-
Fired when a navigation is committed. At least part of the new document has been received from the server and the browser has decided to switch to the new document.
-
{{WebExtAPIRef("webNavigation.onDOMContentLoaded")}}
-
Fired when the DOMContentLoaded event is fired in the page.
-
{{WebExtAPIRef("webNavigation.onCompleted")}}
-
Fired when a document, including the resources it refers to, is completely loaded and initialized. This is equivalent to the DOM load event.
-
{{WebExtAPIRef("webNavigation.onErrorOccurred")}}
-
Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, or the user aborted the navigation.
-
{{WebExtAPIRef("webNavigation.onCreatedNavigationTarget")}}
-
Fired when a new window, or a new tab in an existing window, is created to host a navigation: for example, if the user opens a link in a new tab.
-
{{WebExtAPIRef("webNavigation.onReferenceFragmentUpdated")}}
-
Fired if the fragment identifier for a page is changed.
-
{{WebExtAPIRef("webNavigation.onTabReplaced")}}
-
-

Fired when the contents of the tab is replaced by a different (usually previously pre-rendered) tab.

-
-
{{WebExtAPIRef("webNavigation.onHistoryStateUpdated")}}
-
Fired when the page used the history API to update the URL displayed in the browser's location bar.
-
- -

Browser compatibility

- -

{{Compat("webextensions.api.webNavigation")}}

- - - -

Edge incompatibilities

- -

Promises are not supported in Edge. Use callbacks instead.

- -

{{WebExtExamples("h2")}}

- -
Acknowledgements - -

This API is based on Chromium's chrome.webNavigation API. This documentation is derived from web_navigation.json in the Chromium code.

- -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
- - diff --git a/files/es/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html b/files/es/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html deleted file mode 100644 index 426aeae50f..0000000000 --- a/files/es/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: Extending the developer tools -slug: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools -translation_of: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools ---- -
{{AddonSidebar}}
- -
-

This page describes devtools APIs as they exist in Firefox 55. Although the APIs are based on the Chrome devtools APIs, there are still many features that are not yet implemented in Firefox, and therefore are not documented here. To see which features are currently missing please see Limitations of the devtools APIs.

-
- -

You can use WebExtensions APIs to extend the browser's built-in developer tools. To create a devtools extension, include the "devtools_page" key in manifest.json:

- -
"devtools_page": "devtools/devtools-page.html"
- -

The value of this key is a URL pointing to an HTML file that's been bundled with your extension. The URL should be relative to the manifest.json file itself.

- -

The HTML file defines a special page in the extension, called the devtools page.

- -

The devtools page

- -

The devtools page is loaded when the browser devtools are opened, and unloaded when it is closed. Note that because the devtools window is associated with a single tab, it's quite possible for more than one devtools window - hence more than one devtools page - to exist at the same time.

- -

The devtools page doesn't have any visible DOM, but can include JavaScript sources using <script> tags. The sources must be bundled with the extension itself. The sources get access to:

- - - -

Note that the devtools page does not get access to any other WebExtension APIs, and the background page doesn't get access to the devtools APIs. Instead, the devtools page and the background page must communicate using the runtime messaging APIs. Here's an example:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-  </head>
-  <body>
-    <script src="devtools.js"></script>
-  </body>
-</html>
- -

The devtools.js file will hold the actual code creating your dev tools extensions.

- -

Creating panels

- -

The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".

- -

Using the devtools.panels.create() API, you can create your own panel in the devtools window:

- -
browser.devtools.panels.create(
-  "My Panel",                      // title
-  "icons/star.png",                // icon
-  "devtools/panel/panel.html"      // content
-).then((newPanel) => {
-  newPanel.onShown.addListener(initialisePanel);
-  newPanel.onHidden.addListener(unInitialisePanel);
-});
- -

This takes three mandatory arguments: the panel's title, icon, and content. It returns a Promise which resolves to a devtools.panels.ExtensionPanel object representing the new panel.

- -

Interacting with the target window

- -

The developer tools are always attached to a particular browser tab. This is referred to as the "target" for the developer tools, or the "inspected window". You can interact with the inspected window using the devtools.inspectedWindow API.

- -

Running code in the target window

- -

The devtools.inspectedWindow.eval() provides one way to run code in the inspected window.

- -

This is somewhat like using {{WebExtAPIRef("tabs.executeScript()")}} to inject a content script, but with one important difference:

- - - -
-

Note that a clean view of the DOM is a security feature, intended to help prevent hostile pages from tricking extensions by redefining the behavior of native DOM functions. This means you need to be very careful using eval(), and should use a normal content script if you can.

-
- -

Scripts loaded using devtools.inspectedWindow.eval() also don't see any JavaScript variables defined by content scripts.

- -

Working with content scripts

- -

A devtools document doesn't have direct access to {{WebExtAPIRef("tabs.executeScript()")}}, so if you need to inject a content script, the devtools document must send a message to the background script asking it to inject the script. The devtools.inspectedWindow.tabId provides the ID of the target tab: the devtools document can pass this to the background script, and the background script can in turn pass it into {{WebExtAPIRef("tabs.executeScript()")}}:

- -
// devtools-panel.js
-
-const scriptToAttach = "document.body.innerHTML = 'Hi from the devtools';";
-
-window.addEventListener("click", () => {
-  browser.runtime.sendMessage({
-    tabId: browser.devtools.inspectedWindow.tabId,
-    script: scriptToAttach
-  });
-});
- -
// background.js
-
-function handleMessage(request, sender, sendResponse) {
-  browser.tabs.executeScript(request.tabId, {
-    code: request.script
-  });
-}
-
-browser.runtime.onMessage.addListener(handleMessage);
- -

If you need to exchange messages between the content scripts running in the target window and a devtools document, it's a good idea to use the {{WebExtAPIRef("runtime.connect()")}} and {{WebExtAPIRef("runtime.onConnect")}} to set up a connection between the background page and the devtools document. The background page can then maintain a mapping between tab IDs and {{WebExtAPIRef("runtime.Port")}} objects, and use this to route messages between the two scopes.

- -

- -

Limitations of the devtools APIs

- -

These APIs are based on the Chrome devtools APIs, but many features are still missing, compared with Chrome. This section lists the features that are still not implemented, as of Firefox 54. Note that the devtools APIs are under active development and we expect to add support for most of them in future releases.

- -

devtools.inspectedWindow

- -

The following are not supported:

- - - -

None of the options to inspectedWindow.eval() are supported.

- -

Scripts injected using inspectedWindow.eval() can't use all the Console's command-line helper functions, but $0 and inspect(...) are both supported (starting from Firefox 55).

- -

devtools.panels

- -

The following are not supported:

- - - -

Examples

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use devtools panels:

- - diff --git a/files/es/mozilla/add-ons/webextensions/internationalization/index.html b/files/es/mozilla/add-ons/webextensions/internationalization/index.html deleted file mode 100644 index 89c542a2e7..0000000000 --- a/files/es/mozilla/add-ons/webextensions/internationalization/index.html +++ /dev/null @@ -1,405 +0,0 @@ ---- -title: Internationalization -slug: Mozilla/Add-ons/WebExtensions/Internationalization -translation_of: Mozilla/Add-ons/WebExtensions/Internationalization ---- -
H
- -

The WebExtensions API has a rather handy module available for internationalizing extensions — i18n. In this article we'll explore its features and provide a practical example of how it works. The i18n system for extensions built using WebExtension APIs is similar to common JavaScript libraries for i18n such as i18n.js.

- -
-

The example extension featured in this article — notify-link-clicks-i18n — is available on GitHub. Follow along with the source code as you go through the sections below.

-
- -

Anatomy of an internationalized extension

- -

An internationalized extension can contain the same features as any other extension — background scripts, content scripts, etc. — but it also has some extra parts to allow it to switch between different locales. These are summarized in the following directory tree:

- - - -

Let's explore each of the new features in turn — each of the below sections represents a step to follow when internationalizing your extension.

- -

Providing localized strings in _locales

- -
-
You can look up language subtags using the Find tool on the Language subtag lookup page. Note that you need to search for the English name of the language.
-
- -

Every i18n system requires the provision of strings translated into all the different locales you want to support. In extensions, these are contained within a directory called _locales, placed inside the extension root. Each individual locale has its strings (referred to as messages) contained within a file called messages.json, which is placed inside a subdirectory of _locales, named using the language subtag for that locale's language.

- -

Note that if the subtag includes a basic language plus a regional variant, then the language and variant are conventionally separated using a hyphen: for example, "en-US". However, in the directories under _locales, the separator must be an underscore: "en_US".

- -

So for example, in our sample app we have directories for "en" (English), "de" (German), "nl" (Dutch), and "ja" (Japanese). Each one of these has a messages.json file inside it.

- -

Let's now look at the structure of one of these files (_locales/en/messages.json):

- -
{
-  "extensionName": {
-    "message": "Notify link clicks i18n",
-    "description": "Name of the extension."
-  },
-
-  "extensionDescription": {
-    "message": "Shows a notification when the user clicks on links.",
-    "description": "Description of the extension."
-  },
-
-  "notificationTitle": {
-    "message": "Click notification",
-    "description": "Title of the click notification."
-  },
-
-  "notificationContent": {
-    "message": "You clicked $URL$.",
-    "description": "Tells the user which link they clicked.",
-    "placeholders": {
-      "url" : {
-        "content" : "$1",
-        "example" : "https://developer.mozilla.org"
-      }
-    }
-  }
-}
- -

This file is standard JSON — each one of its members is an object with a name, which contains a message and a description. All of these items are strings; $URL$ is a placeholder, which is replaced with a substring at the time the notificationContent member is called by the extension. You'll learn how to do this in the {{anch("Retrieving message strings from JavaScript")}} section.

- -
-

Note: You can find much more information about the contents of messages.json files in our Locale-Specific Message reference.

-
- -

Internationalizing manifest.json

- -

There are a couple of different tasks to carry out to internationalize your manifest.json.

- -

Retrieving localized strings in manifests

- -

Your manifest.json includes strings that are displayed to the user, such as the extension's name and description. If you internationalize these strings and put the appropriate translations of them in messages.json, then the correct translation of the string will be displayed to the user, based on the current locale, like so.

- -

To internationalize strings, specify them like this:

- -
"name": "__MSG_extensionName__",
-"description": "__MSG_extensionDescription__",
- -

Here, we are retrieving message strings dependant on the browser's locale, rather than just including static strings.

- -

To call a message string like this, you need to specify it like this:

- -
    -
  1. Two underscores, followed by
  2. -
  3. The string "MSG", followed by
  4. -
  5. One underscore, followed by
  6. -
  7. The name of the message you want to call as defined in messages.json, followed by
  8. -
  9. Two underscores
  10. -
- -
__MSG_ + messageName + __
- -

Specifying a default locale

- -

Another field you should specify in your manifest.json is default_locale:

- -
"default_locale": "en"
- -

This specifies a default locale to use if the extension doesn't include a localized string for the browser's current locale. Any message strings that are not available in the browser locale are taken from the default locale instead. There are some more details to be aware of in terms of how the browser selects strings — see {{anch("Localized string selection")}}.

- -

Locale-dependent CSS

- -

Note that you can also retrieve localized strings from CSS files in the extension. For example, you might want to construct a locale-dependent CSS rule, like this:

- -
header {
-  background-image: url(../images/__MSG_extensionName__/header.png);
-}
- -

This is useful, although you might be better off handling such a situation using {{anch("Predefined messages")}}.

- -

Retrieving message strings from JavaScript

- -

So, you've got your message strings set up, and your manifest. Now you just need to start calling your message strings from JavaScript so your extension can talk the right language as much as possible. The actual i18n API is pretty simple, containing just four main methods:

- - - -

In our notify-link-clicks-i18n example, the background script contains the following lines:

- -
var title = browser.i18n.getMessage("notificationTitle");
-var content = browser.i18n.getMessage("notificationContent", message.url);
- -

The first one just retrieves the notificationTitle message field from the available messages.json file most appropriate for the browser's current locale. The second one is similar, but it is being passed a URL as a second parameter. What gives? This is how you specify the content to replace the $URL$ placeholder we see in the notificationContent message field:

- -
"notificationContent": {
-  "message": "You clicked $URL$.",
-  "description": "Tells the user which link they clicked.",
-  "placeholders": {
-    "url" : {
-      "content" : "$1",
-      "example" : "https://developer.mozilla.org"
-    }
-  }
-}
-
- -

The "placeholders" member defines all the placeholders, and where they are retrieved from. The "url" placeholder specifies that its content is taken from $1, which is the first value given inside the second parameter of getMessage(). Since the placeholder is called "url", we use $URL$ to call it inside the actual message string (so for "name" you'd use $NAME$, etc.) If you have multiple placeholders, you can provide them inside an array that is given to {{WebExtAPIRef("i18n.getMessage()")}} as the second parameter — [a, b, c] will be available as $1, $2, and $3, and so on, inside messages.json.

- -

Let's run through an example: the original notificationContent message string in the en/messages.json file is

- -
You clicked $URL$.
- -

Let's say the link clicked on points to https://developer.mozilla.org. After the {{WebExtAPIRef("i18n.getMessage()")}} call, the contents of the second parameter are made available in messages.json as $1, which replaces the $URL$ placeholder as defined in the "url" placeholder. So the final message string is

- -
You clicked https://developer.mozilla.org.
- -

Direct placeholder usage

- -

It is possible to insert your variables ($1, $2, $3, etc.) directly into the message strings, for example we could rewrite the above "notificationContent" member like this:

- -
"notificationContent": {
-  "message": "You clicked $1.",
-  "description": "Tells the user which link they clicked."
-}
- -

This may seem quicker and less complex, but the other way (using "placeholders") is seen as best practice. This is because having the placeholder name (e.g. "url") and example helps you to remember what the placeholder is for — a week after you write your code, you'll probably forget what $1$8 refer to, but you'll be more likely to know what your placeholder names refer to.

- -

Hardcoded substitution

- -

It is also possible to include hardcoded strings in placeholders, so that the same value is used every time, instead of getting the value from a variable in your code. For example:

- -
"mdn_banner": {
-  "message": "For more information on web technologies, go to $MDN$.",
-  "description": "Tell the user about MDN",
-  "placeholders": {
-    "mdn": {
-      "content": "https://developer.mozilla.org/"
-    }
-  }
-}
- -

In this case we are just hardcoding the placeholder content, rather than getting it from a variable value like $1. This can sometimes be useful when your message file is very complex, and you want to split up different values to make the strings more readable in the file, plus then these values could be accessed programmatically.

- -

In addition, you can use such substitutions to specify parts of the string that you don't want to be translated, such as person or business names.

- -

Localized string selection

- -

Locales can be specified using only a language code, like fr or en, or they may be further qualified with a region code, like en_US or en_GB, which describes a regional variant of the same basic language. When you ask the i18n system for a string, it will select a string using the following algorithm:

- -
    -
  1. if there is a messages.json file for the exact current locale, and it contains the string, return it.
  2. -
  3. Otherwise, if the current locale is qualified with a region (e.g. en_US) and there is a messages.json file for the regionless version of that locale (e.g. en), and that file contains the string, return it.
  4. -
  5. Otherwise, if there is a messages.json file for the default_locale defined in the manifest.json, and it contains the string, return it.
  6. -
  7. Otherwise return an empty string.
  8. -
- -

Take the following example:

- - - -

Suppose the default_locale is set to fr, and the browser's current locale is en_GB:

- - - -

Predefined messages

- -

The i18n module provides us with some predefined messages, which we can call in the same way as we saw earlier in {{anch("Calling message strings from manifests and extension CSS")}}. For example:

- -
__MSG_extensionName__
- -

Predefined messages use exactly the same syntax, except with @@ before the message name, for example

- -
__MSG_@@ui_locale__
- -

The following table shows the different available predefined messages:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message nameDescription
@@extension_id -

The extension's internally-generated UUID. You might use this string to construct URLs for resources inside the extension. Even unlocalized extensions can use this message.

- -

You can't use this message in a manifest file.

- -

Also note that this ID is not the add-on ID returned by {{WebExtAPIRef("runtime.id")}}, and that can be set using the applications key in manifest.json. It's the generated UUID that appears in the add-on's URL. This means that you can't use this value as the extensionId parameter to {{WebExtAPIRef("runtime.sendMessage()")}}, and can't use it to check against the id property of a {{WebExtAPIRef("runtime.MessageSender")}} object.

-
@@ui_localeThe current locale; you might use this string to construct locale-specific URLs.
@@bidi_dirThe text direction for the current locale, either "ltr" for left-to-right languages such as English or "rtl" for right-to-left languages such as Arabic.
@@bidi_reversed_dirIf the @@bidi_dir is "ltr", then this is "rtl"; otherwise, it's "ltr".
@@bidi_start_edgeIf the @@bidi_dir is "ltr", then this is "left"; otherwise, it's "right".
@@bidi_end_edgeIf the @@bidi_dir is "ltr", then this is "right"; otherwise, it's "left".
- -

Going back to our earlier example, it would make more sense to write it like this:

- -
header {
-  background-image: url(../images/__MSG_@@ui_locale__/header.png);
-}
- -

Now we can just store our local specific images in directories that match the different locales we are supporting — en, de, etc. — which makes a lot more sense.

- -

Let's look at an example of using @@bidi_* messages in a CSS file:

- -
body {
-  direction: __MSG_@@bidi_dir__;
-}
-
-div#header {
-  margin-bottom: 1.05em;
-  overflow: hidden;
-  padding-bottom: 1.5em;
-  padding-__MSG_@@bidi_start_edge__: 0;
-  padding-__MSG_@@bidi_end_edge__: 1.5em;
-  position: relative;
-}
- -

For left-to-right languages such as English, the CSS declarations involving the predefined messages above would translate to the following final code lines:

- -
direction: ltr;
-padding-left: 0;
-padding-right: 1.5em;
-
- -

For a right-to-left language like Arabic, you'd get:

- -
direction: rtl;
-padding-right: 0;
-padding-left: 1.5em;
- -

Testing out your extension

- -

Starting in Firefox 45, you can install extensions temporarily from disk — see Loading from disk. Do this, and then try testing out our notify-link-clicks-i18n extension. Go to one of your favourite websites and click a link to see if a notification appears reporting the URL of the clicked link.

- -

Next, change Firefox's locale to one supported in the extension that you want to test.

- -
    -
  1. Open "about:config" in Firefox, and search for the intl.locale.requested preference (bear in mind that before Firefox 59, this pref is called general.useragent.locale).
  2. -
  3. If the preference exists, double-click it (or press Return/Enter) to select it, enter the language code for the locale you want to test, then click "OK" (or press Return/Enter). For example in our example extension, "en" (English), "de" (German), "nl" (Dutch), and "ja" (Japanese) are supported. You can also set the value to an empty string (""), which will cause the browser to use the OS default locale.
  4. -
  5. If the intl.locale.requested preference does not exist, right-click the list of preferences (or activate the context menu using the keyboard), and choose "New" followed by "String". Enter intl.locale.requested for the preference name and, "de", or "nl", etc. for the preference value, as described in step 2 above.
  6. -
  7. Search for intl.locale.matchOS and, if the preference exists and has the value true, double-click it  so that it is set to false.
  8. -
  9. Restart your browser to complete the change.
  10. -
- -
-

Note: This works to change the browser's locale, even if you haven't got the language pack installed for that language. You'll just get the browser UI in your default language if this is the case.

-
- -
    -
- -
-

Note: To change the result of getUILanguage the language pack is required, since it reflects the browser UI language and not the language used for extension messages.

-
- -

Load the extension temporarily from disk again, then test your new locale:

- - - -

{{EmbedYouTube("R7--fp5pPGg")}}

diff --git a/files/es/mozilla/firefox/releases/62/index.html b/files/es/mozilla/firefox/releases/62/index.html deleted file mode 100644 index ccc68fce29..0000000000 --- a/files/es/mozilla/firefox/releases/62/index.html +++ /dev/null @@ -1,235 +0,0 @@ ---- -title: Firefox 62 for developers -slug: Mozilla/Firefox/Releases/62 -translation_of: Mozilla/Firefox/Releases/62 ---- -
{{FirefoxSidebar}}
- -

Este artículo provee información sobre los cambios de Firefox 62 que van a afectar a los programadores. Firefox 62 ha sido lanzado en 5 de septiembre, 2018.

- -

Cambios para programadores de red

- -

Herramientas para programadores

- - - -

Removals

- - - -

HTML

- -

No changes.

- -

CSS

- - - -

Removals

- - - -

SVG

- -

No changes.

- -

JavaScript

- - - -

Removals

- - - -

APIs

- -

New APIs

- - - -

DOM

- - - -

DOM events

- -

No changes.

- -

Service workers

- -

No changes.

- -

Media, Web Audio, and WebRTC

- - - -

Removals

- - - - - - - -

HTTP

- -

Removals

- - - -

Security

- -

No changes.

- -

Plugins

- -

No changes.

- -

WebDriver conformance (Marionette)

- -

New features

- - - -

API changes

- - - -

Bug fixes

- - - -

Other

- -

No changes.

- -

Changes for add-on developers

- -

API changes

- - - -

Manifest changes

- - - -

Theme changes

- - - -

Removals

- - - -

See also

- - - -

Older versions

- -

{{Firefox_for_developers(61)}}

diff --git a/files/es/mozilla/firefox/releases/67/index.html b/files/es/mozilla/firefox/releases/67/index.html deleted file mode 100644 index a60df8ab8a..0000000000 --- a/files/es/mozilla/firefox/releases/67/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Firefox 67 for developers -slug: Mozilla/Firefox/Releases/67 -tags: - - '67' - - Firefox - - Lanzamiento - - Mozilla -translation_of: Mozilla/Firefox/Releases/67 ---- -

{{FirefoxSidebar}}

- -

Este artículo provee información sobre los cambios en Firefox 67 que afectarán a los desarrolladores. Firefox 67 fue lanzado el 21 de Mayo de 2019.

- -

Cambios para desarrolladores web

- -

Herramientas de desarrollo

- - - -

Removals

- - - -

HTML

- - - -

CSS

- - - -

Removals

- - - -

SVG

- -

No changes.

- -

JavaScript

- - - -

APIs

- -

DOM

- - - -

DOM events

- - - -

Workers/Service workers

- - - -

Media, Web Audio, and WebRTC

- - - -

Canvas and WebGL

- - - -

Removals

- - - -

Security

- - - -

WebDriver conformance (Marionette)

- -

API changes

- - - -

Corrección de errores

- - - -

Otros

- - - -

Changes for add-on developers

- -

Cambios en API

- - - -

Cambios en manifiesto

- - - -

Ver también

- - - -

Versiones anteriores

- -

{{Firefox_for_developers(66)}}

diff --git a/files/es/mozilla/firefox/releases/68/index.html b/files/es/mozilla/firefox/releases/68/index.html deleted file mode 100644 index 4c2649dcd2..0000000000 --- a/files/es/mozilla/firefox/releases/68/index.html +++ /dev/null @@ -1,233 +0,0 @@ ---- -title: Firefox 68 for developers -slug: Mozilla/Firefox/Releases/68 -translation_of: Mozilla/Firefox/Releases/68 ---- -

{{FirefoxSidebar}}

- -

This article provides information about the changes in Firefox 68 that will affect developers. Firefox 68 was released on July 9, 2019.

- -

Changes for web developers

- -

Developer tools

- -

Browser/web console

- - - -

JavaScript debugger

- - - -

Network monitor

- - - -

Page inspector

- - - -

Storage inspector

- - - -

Other

- - - -

Removals

- - - -

HTML

- - - -

 Removals

- - - -

CSS

- - - -

Removals

- - - -

SVG

- -

No changes.

- -

JavaScript

- - - -

APIs

- -

CSS Object Model (CSSOM)

- - - -

DOM

- - - -

DOM events

- - - -

Media, Web Audio, and WebRTC

- - - -

Removals

- - - -

HTTP

- - - -

Removals

- - - -

Security

- -

No changes.

- -

WebDriver conformance (Marionette)

- -

Bug fixes

- - - -

Other

- - - -

Plugins

- -

No changes.

- -

Changes for add-on developers

- -

API changes

- - - -

Manifest changes

- -

No changes.

- -

See also

- - - -

Older versions

- -

{{Firefox_for_developers(67)}}

diff --git a/files/es/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html b/files/es/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html deleted file mode 100644 index 089f74510c..0000000000 --- a/files/es/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html +++ /dev/null @@ -1,727 +0,0 @@ ---- -title: Applying styles and colors -slug: Web/API/Canvas_API/Tutorial/Applying_styles_and_colors -translation_of: Web/API/Canvas_API/Tutorial/Applying_styles_and_colors -original_slug: Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors ---- -
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_shapes", "Web/API/Canvas_API/Tutorial/Drawing_text")}}
- -
-

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

-
- -

Colors

- -

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

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

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

- -
-

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

-
- -

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

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

A fillStyle example

- -

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

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

The result looks like this:

- -

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

- -

A strokeStyle example

- -

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

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

The result looks like this:

- -

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

- -

Transparency

- -

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

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

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

- -

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

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

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

- -

A globalAlpha example

- -

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

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

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

- -

An example using rgba()

- -

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

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

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

- -

Line styles

- -

There are several properties which allow us to style lines.

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

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

- -

A lineWidth example

- -

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

- -

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

- -

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

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

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

- -

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

- -

- -

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

- -

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

- -
-

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

- -

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

-
- -

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

- -

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

- -

A lineCap example

- -

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

- -

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

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

- -

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

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

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

- -

A lineJoin example

- -

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

- -

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

- -

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

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

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

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

- -

A demo of the miterLimit property

- -

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

- -

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

- -

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

- - - -

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

- -

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

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

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

- -

Using line dashes

- -

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

- -

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

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

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

- -

Gradients

- -

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

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

For example:

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

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

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

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

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

A createLinearGradient example

- -

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

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

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

- -

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

- -

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

- -

A createRadialGradient example

- -

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

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

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

- -

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

- -

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

- -

Patterns

- -

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

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

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

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

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

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

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

-
- -

A createPattern example

- -

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

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

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

- -

Shadows

- -

Using shadows involves just four properties:

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

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

- -

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

- -

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

- -
-

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

-
- -

A shadowed text example

- -

This example draws a text string with a shadowing effect.

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

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

- -

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

- -

Canvas fill rules

- -

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

- - - -

In this example we are using the evenodd rule.

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

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

- -

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

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

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

- -

Concepts and usage

- -

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

- -

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

- -
-

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

-
- -

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

- -

Constraint validation interfaces

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

Extensions to other interfaces

- -

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

- - - -

Properties

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

Methods

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

Examples

- -

Take the following form:

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

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

- -

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

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

The example renders like so:

- -

{{EmbedLiveSample('Examples')}}

- -

In brief:

- - - -
-

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

-
- -

Specifications

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

See also

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

Summary

-

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

-

Syntax

-
stylesheet = cssRule.parentStyleSheet
-
-

Parameters

- -

Instance

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

Letters

-

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

-

Specification

-

DOM Level 2 Style - cssRule

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

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

- -

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

- -

Lista de propiedades

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

Lista de métodos

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

Propiedades

- -

dropEffect

- -

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

- -

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

- -

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

- -

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

- -

Possible values:

- - - -

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

- -

effectAllowed

- -

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

- -

Possible values:

- - - -

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

- -

files

- -

{{ gecko_minversion_header("1.9.2") }}

- -

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

- -

Example

- -

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

- -

types

- -

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

- -

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

- -

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

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

Possible values

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

mozItemCount

- -

The number of items being dragged.

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

mozSourceNode

- -

{{ gecko_minversion_header("2") }}

- -

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

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

mozUserCancelled

- -

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

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

Métodos

- -

addElement()

- -

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

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

clearData()

- -

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

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

getData()

- -

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

- -

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

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

setData()

- -

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

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

setDragImage()

- -

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

- -

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

- -

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

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

mozClearDataAt()

- -

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

- -

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

- -

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

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

mozGetDataAt()

- -

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

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

mozSetDataAt()

- -

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

- -

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

- -

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

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

mozTypesAt()

- -

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

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

Mira también

- -

Drag and Drop

- -

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

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

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

- -

Sintaxis

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

Ejemplo

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

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

- -

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

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

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

- -

See Introduction to using XPath in JavaScript for more information.

- -

Nota

- - - -

Tipos de resultados

- -

(Merge with Template:XPathResultConstants?

- -

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

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

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

- -

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

- -

Especificaciones

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

Compatibilidad del navegador

- -

{{CompatibilityTable}}

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

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

- -

Ver también

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

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

- -

Syntax

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

Value

- -

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

- -

Examples

- -

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

- -

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

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

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

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

Specifications

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

Browser compatibility

- - - -

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

- -

See also

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

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

- -

Sintaxis

- -
var tipo = file.type;
- -

Valor

- -

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

- -

Ejemplo

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

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

- -

Especificaciones

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

Compatibilidad de los navegadores

- - - -

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

- -

Ver también

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

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

- -

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

- -

Syntax

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

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

- -

Specification

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

Browser compatibility

- - - -

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

- -

See also

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

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

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

first_page.php:

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

second_page.php:

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

third_page.php:

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

css/style.css:

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

include/after_content.php:

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

include/before_content.php:

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

include/header.php:

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

js/ajax_nav.js:

- -

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

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

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

- -

See also

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

{{ APIRef("Web Components") }}

- -

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

- -

Syntax

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

Example

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

Specifications

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

Browser compatibility

- -

{{CompatibilityTable}}

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

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

- -

See also

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

{{ APIRef("Web Components") }}

- -

{{Deprecated_header}}

- -

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

- -

Properties

- -

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

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

Methods

- -

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

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

Specifications

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

Browser compatibility

- -

{{CompatibilityTable}}

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

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

- -

See also

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

{{ APIRef("Web Components") }}

- -

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

- -

Syntax

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

Example

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

Specifications

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

Browser compatibility

- -

{{CompatibilityTable}}

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

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

- -

See also

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

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

- -
-

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

-
- -

Syntax

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

Value

- -

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

- -

Example

- -

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

- -

HTML

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

JavaScript

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

Result

- -

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

- -

Specification

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

Browser compatibility

- - - -

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

- -

See also

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

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

- -

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

- -

Properties

- -

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

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

Methods

- -

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

- -

Specifications

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

Browser compatibility

- -

{{CompatibilityTable}}

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

See also

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

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

- -

Información general

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

Propiedades

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

{{APIRef("DOM Events")}}

- -

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

- -

Sintaxis

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

Retorna

- -

A {{jsxref("Boolean")}}

- -

Parámetros

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

Teclas modificadoras en Internet Explorer

- -

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

- -

Teclas modificadoras en Gecko

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

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

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

 El modificador virtual "Accel"

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

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

- -

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

- -

Ejemplo

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

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

-
- -

Especificaciones

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

Compatibilidad con Browsers

- - - -

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

- -

Ver también

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

{{APIRef("DOM Events")}}

- -

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

- -
-

See a full list of key values.

-
- - - -

KeyboardEvent Sequence

- -

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

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

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

- -

KeyboardEvent Sequence Sample

- -

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

- -

Try experimenting using the following two test cases:

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

HTML

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

CSS

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

JavaScript

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

Result

- -

{{EmbedLiveSample('KeyboardEvent_Sequence_Sample')}}

- -

Case 1

- -

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

- -

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

- -

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

- -

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

- -

Case 2

- -

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

- -

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

- -

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

- -

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

- -

Example

- -

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

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

Specification

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

Browser compatibility

- - - -

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

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

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

- -

Syntax

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

Return value

- -

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

- -

Specifications

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

Browser compatibility

- - - -

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

- -

See also

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

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

- -

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

- -
-

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

-
- -

Sintaxis

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

Parámetros

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

Retorna

- -

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

- -

Especificaciones

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

Compactibilidad del Navegador

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

Ver también

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

{{ ApiRef() }}

-

Summary

-

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

-

Syntax

-
bool = range.intersectsNode( referenceNode )
-
-

Parameters

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

Example

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

Notes

-

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

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

The following function can be used as replacement:

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

Specification

-

This method is not part of a specification.

-
-  
-

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

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

{{ServiceWorkerSidebar}}

- -

{{ SeeCompatTable() }}

- -
-

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

-
- -

La premisa de los service workers

- -

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

- -

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

- -
-

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

-
- -

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

- -

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

- -

Setting up to play with service workers

- -

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

- - - -

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

- -

Basic architecture

- -

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

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

- -

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

- -

install, activate, message, fetch, sync, push

- -

Promises

- -

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

- -

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

- -

sync

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

async

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

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

- -

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

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

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

- -

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

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

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

- -

This all happens asynchronously.

- -
-

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

-
- -
-

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

-
- -

Service workers demo

- -

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

- -


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

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

Enter service workers

- -

Now let’s get on to service workers!

- -

Registering your worker

- -

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

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

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

- -
-

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

-
- -
-

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

-
- -

Why is my service worker failing to register?

- -

This could be for the following reasons:

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

- -

Also note:

- - - -

Install and activate: populating your cache

- -

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

- -
-

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

-
- -

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

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

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

-
- -
-

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

-
- -

Custom responses to requests

- -

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

- -

- -

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

- -

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

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

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

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

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

- -

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

- -
    -
  1. -

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

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

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

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

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

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

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

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

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

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

Recovering failed requests

- -

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

- -

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

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

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

- -

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

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

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

- -

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

- -

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

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

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

- -

Updating your service worker

- -

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

- -

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

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

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

- -

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

- -

Deleting old caches

- -

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

- -

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

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

Developer tools

- -

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

- -

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

- - - -
-

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

-
- -

Specifications

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

Browser compatibility

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

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

- -

See also

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

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

- -

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

- -
-

Note: This feature is available in Web Workers.

-
- -

Properties

- -

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

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

Event handlers

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

Methods

- -

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

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

Examples

- -

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

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

Specifications

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

Browser compatibility

- - - -

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

- -

See also

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

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

- -

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

- -

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

- -

Making the square rotate

- -

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

- -
var squareRotation = 0.0;
-
- -

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

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

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

- -

After drawing, we need to restore the original matrix:

- -
  mvPopMatrix();
-
- -

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

- -

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

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

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

- -

Making the square move

- -

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

- -

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

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

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

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

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

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

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

- -

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

- -

More matrix operations

- -

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

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

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

- -

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

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

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

- -

Notes

- -

The sidebar object returned has the following methods:

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

Specification

- -

Mozilla-specific. Not part of any standard.

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

{{ ApiRef() }}

-

Test Summary

-

The unload event is raised when the document is unloaded.

-

Syntax

-
window.onunload = funcRef;
-
- -

Example

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

Notes

-

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

-

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

-

Specification

-

{{ DOM0() }}

-

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

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

{{APIRef("XMLHttpRequest")}}

- -

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

- -

{{InheritanceDiagram}}

- -

Properties

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

Specifications

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

Browser compatibility

- - - -

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

- -

See also

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

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

- -

Sintaxis

- -
XMLHttpRequest.onload = callback;
- -

 Valores

- - - -

Ejemplo

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

Especificaciones

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

Browser compatibility

- - - -

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

diff --git a/files/es/web/css/@viewport/index.html b/files/es/web/css/@viewport/index.html deleted file mode 100644 index 7e55775592..0000000000 --- a/files/es/web/css/@viewport/index.html +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: '@viewport' -slug: Web/CSS/@viewport -tags: - - Adaptation - - At-rule - - CSS - - Device - - NeedsContent - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/CSS/@viewport ---- -

{{CSSRef}}

- -

Summary

- -

The @viewport CSS at-rule contains a set of nested descriptors in a CSS block that is delimited by curly braces. These descriptors control viewport settings, primarily on mobile devices.

- -

Syntax

- -

A zoom factor of 1.0 or 100% corresponds to no zooming. Larger values zoom in. Smaller values zoom out.

- -

Descriptors

- -

Browsers are supposed to ignore unrecognized descriptors.

- -
-
min-width
-
Used in the determination of the width of the viewport when the document is first displayed.
-
max-width
-
Used in the determination of the width of the viewport when the document is first displayed.
-
width
-
A shorthand descriptor for setting both min-width and max-width
-
min-height
-
Used in the determination of the height of the viewport when the document is first displayed.
-
max-height
-
Used in the determination of the height of the viewport when the document is first displayed.
-
height
-
A shorthand descriptor for setting both min-height and max-height
-
zoom
-
Sets the initial zoom factor.
-
min-zoom
-
Sets the minimum zoom factor.
-
max-zoom
-
Sets the maximum zoom factor.
-
user-zoom
-
Controls whether or not the user should be able to change the zoom factor.
-
orientation
-
Controls the document's orientation.
-
- -

Formal syntax

- -{{csssyntax}} - -

Examples

- -
@viewport {
-  min-width: 640px;
-  max-width: 800px;
-}
-@viewport {
-  zoom: 0.75;
-  min-zoom: 0.5;
-  max-zoom: 0.9;
-}
-@viewport {
-  orientation: landscape;
-}
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS3 Device', '#the-atviewport-rule', '@viewport')}}{{Spec2('CSS3 Device')}}Initial definition
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support29 (behind a flag) [4]{{CompatNo()}} [2]10 {{property_prefix("-ms")}}11.10
- Removed in 15
- Reintroduced behind a flag in 16
{{CompatNo}} [3]
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.429{{CompatNo}} [2]10{{property_prefix("-ms")}}[1]11.10
- Removed in 15
- Reintroduced behind a flag in 16
{{CompatNo}} [3]
-
- -

[1] There is a bug in IE Mobile 10 on older versions of Windows Phone 8, where device-width, when used within @-ms-viewport, evaluates to the screen width in physical pixels rather than normalized CSS pixels, which is wrong according to the specification. However, when used within a viewport {{HTMLElement("meta")}} tag, device-width evaluates correctly. According to Microsoft, this bug was fixed in Windows Phone 8 Update 3 (a.k.a. GDR3), although there are some reports that the Lumia Black GDR3 update did not fix the bug (at least on the Lumia 920). For more details and a workaround, see Tim Kadlec's blog post "Windows Phone 8 and Device-Width".

- -

[2]: See {{bug(747754, 'summary')}}

- -

[3]: See {{webkitbug(95959)}}

-

[4]: See Chromium issue #235457: Enable @viewport on all platforms

-

See also

- - diff --git a/files/es/web/css/css_grid_layout/css_grid_layout_and_accessibility/index.html b/files/es/web/css/css_grid_layout/css_grid_layout_and_accessibility/index.html deleted file mode 100644 index 7339530ff1..0000000000 --- a/files/es/web/css/css_grid_layout/css_grid_layout_and_accessibility/index.html +++ /dev/null @@ -1,169 +0,0 @@ ---- -title: CSS Grid Layout y accesibilidad -slug: Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility -translation_of: Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility ---- -

Los que llevamos en esto del desarrollo web más años de los que queremos recordar podríamos considerar que CSS Grid es un poco como "maquetar con tablas". En los primeros tiempos del diseño web la manera de maquetar la página era usando tablas HTML y "troceando" los elementos dentro de las celdas de esas tablas para crear un diseño. This had some advantages over the “CSS Positioning” that came afterwards, in that we could take advantage of the alignment and full height columns offered by table display. The biggest downside however was that it tied our design to the mark-up, often creating accessibility issues as it did so. In order to lay the design out in the table we often broke up the content in ways that made no sense at all when read out by a screen reader for example.

- -

In moving to CSS we often spoke about CSS for layout enabling a separation of content and markup and presentation. The ultimate aim being that we could create a semantic and well structured document, then apply CSS to create the layout we desired. Sites such as the CSS Zen Garden showcased this ability. The CSS Zen Garden challenged us to take identical markup and create a unique design using CSS.

- -

CSS Grid Layout does not have the same issues that tables did, our grid structure is defined in CSS rather than in the mark-up. If we need to add an element we can use something with no semantic meaning. On paper grid helps us properly fulfill that promise of content separated from mark-up, however is it possible to go too far with this idea? Is it possible that we could create an accessibility issue through our use of grids?

- -

Re-ordering content in CSS Grid Layout

- -

We’ve already seen in these guides that grid gives us power to re-order the content of our page in various ways. We can use the {{cssxref("order")}} property, which will change how items auto-place. We can use grid-auto-flow: dense which will take items visually out of DOM order. We can also position items using line-based placement of grid template areas, without considering their location in the source.

- -

The specification includes a section that covers Reordering and Accessibility. In the introduction to that section are details of what the specification expects browsers to do when the content is visually reordered using Grid Layout.

- -
-

Grid layout gives authors great powers of rearrangement over the document. However, these are not a substitute for correct ordering of the document source. The order property and grid placement do not affect ordering in non-visual media (such as speech). Likewise, rearranging grid items visually does not affect the default traversal order of sequential navigation modes (such as cycling through links, see e.g. tabindex HTML5).

-
- -

If you reorder things visually using grid layout, this will not change how the items are ordered if the content is being read out by a screen reader, or other text to speech user agent. In addition, the reordering will not change tab order. This means that someone navigating using the keyboard could be tabbing through links on your site and suddenly find themselves jumping from the top to the bottom of the document due to a reordered item being next in line.

- -

The specification warns authors (the CSSWG term for web developers) not to do this reordering.

- -
-

Authors must use order and the grid-placement properties only for visual, not logical, reordering of content. Style sheets that use these features to perform logical reordering are non-conforming.

-
- -

What does this mean for designing with grid layout in practice?

- -

Visual not logical re-ordering

- -

Any time you reorder things with grid layout – or with flexbox – you only perform visual reordering. The underlying source is what controls things like text to speech, and the tab order of the document. You can see how this works with a very simple example.

- -

In this example I have used grid to lay out a set of boxes that contain links. I have used the line-based placement properties to position box 1 on the second row of the grid. Visually it now appears as the fourth item in the list. However, if I tab from link to link the tab order still begins with box 1, as it comes first in the source.

- -
- - -
.wrapper {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  grid-auto-rows: 100px;
-}
-
-.box1 {
-  grid-column: 1;
-  grid-row: 2;
-}
-
- -
<div class="wrapper">
-  <div class="box box1"><a href="">One</a></div>
-  <div class="box box2"><a href="">Two</a></div>
-  <div class="box box3"><a href="">Three</a></div>
-  <div class="box box4"><a href="">Four</a></div>
-  <div class="box box5"><a href="">Five</a></div>
-</div>
-
- -

{{ EmbedLiveSample('accessibility_1', '500', '330') }}

-
- -

The specification says that in this scenario, if box 1 really makes sense logically in that position, we should go back to our source and make the change there rather than reordering using grid layout. This is what is meant by visual versus logical reordering, logical ordering is important for the meaning and structure of our document, and we should make sure that we preserve that structure.

- -

How should we approach accessibility for grid layout?

- -

From the specification we know that we need to ensure our document maintains the logical order of our content. How should we approach our development to make sure that we maintain accessibility for the different users and the ways that they interact with our pages?

- -
-
Start with a structured and accessible document
-
A grid layout should mean we do not need to change our document source in order to get the layout that we want. Therefore the starting point of your page should be a well structured and accessible source document. As is noted in the CSS Grid Layout specification, this is quite often going to give you a good structure for your smallest screen devices too. If a user is scrolling through a long document on mobile, the priorities for that user quite often map to what should be a priority in the source.
-
Create a responsive, and responsible grid
-
With a solid document you can begin to add your layout, it is likely you will be using media queries to create additional columns and make changes for different screen sizes and devices. Grid can be really very useful here, elements deprioritized in the mobile source order can be moved into a sidebar in a desktop layout, for example. The key here is to keep testing, a very simple test is to tab around the document. Does that order still make sense? Check that you do not end up leaping from the top to the bottom of the layout in a peculiar way. If so that would be a sign that you need to address something about the layout.
-
Returning to the source
-
If at any time in the design process you find yourself using grid to relocate the position of an element, consider whether you should return to your document and make a change to the logical order too. The nice thing about using CSS Grid Layout is that you should be able to move an item in the source to match the logical order, without needing to make big changes to your layout. This is a huge improvement over a {{cssxref("float")}}-based layout for example, where document source matters a lot in order to get layouts at different breakpoints. However the onus is on us as developers to remember to go back to our source and update it to maintain logical order.
-
- -

Grid and the danger of markup flattening

- -

Another issue to be aware of in CSS Grid Layout and to a lesser extent in CSS Flexbox, is the temptation to flatten markup. As we have discovered, for an item to become a grid item it needs to be a direct child of the grid container. Therefore, where you have a {{HTMLElement("ul")}} element inside a grid container, that ul becomes a grid item – the child {{HTMLElement("li")}} elements do not.

- -

If the subgrid value of {{cssxref("display")}} becomes implemented, it would be possible to make these children of a grid item participate in the overall grid layout by declaring the ul element a subgrid. Currently the only way to do this is to use display: contents to cause the box generated by the ul to disappear from the DOM. For more information about this interaction see the guide on the Relationship of Grid Layout to other layout methods and the section on display: contents.

- -

Given that interoperable support for display: contents is limited and we do not yet have subgrids, there is a definite temptation when developing a site using CSS Grid Layout to flatten out the markup, to remove semantic elements in order to make it simpler to create a layout. An example would be where some content was semantically marked up as a list but you decide to use a set of {{HTMLElement("div")}} elements instead as then you can have the element to be a direct child of a container set to display: grid. Be aware of this temptation and find ways to develop your design without stripping out the markup. Starting out with a well-structured document is a very good way to avoid the problem, as you will be aware that you are removing semantic elements in order to make the layout work if you actually have to go into the document and do so!

- -

Further reading

- -

There is not a lot of existing material regarding accessibility and CSS Grid Layout. Many of the issues are similar to those raised regarding CSS Flexbox, which also gives methods of reordering content with {{cssxref("flex-direction")}} and the {{cssxref("order")}} property.

- -

The concept of visual display following document source order is detailed in the WCAG Techniques for Success Criteria – Technique C27.

- -

As a way to start thinking about these issues, as you use CSS Grid Layout I would suggest reading Flexbox & the Keyboard Navigation Disconnect from Léonie Watson. Also the video of Léonie’s presentation from ffconf is helpful to understand more about how screen readers work with the visual representation of things in CSS. Adrian Roselli has also posted regarding tab order in various browsers – although this was prior to grid support being fully implemented in Firefox.

- - diff --git a/files/es/web/css/max-width/index.html b/files/es/web/css/max-width/index.html deleted file mode 100644 index 3b3f0a21ff..0000000000 --- a/files/es/web/css/max-width/index.html +++ /dev/null @@ -1,158 +0,0 @@ ---- -title: max-width -slug: Web/CSS/max-width -tags: - - Referencia_CSS -translation_of: Web/CSS/max-width ---- -
{{CSSRef}}
- -

The max-width CSS property sets the maximum width of an element. It prevents the used value of the {{ Cssxref("width") }} property from becoming larger than the value specified by max-width.

- -
/* <length> value */
-max-width: 3.5em;
-
-/* <percentage> value */
-max-width: 75%;
-
-/* Keyword values */
-max-width: none;
-max-width: max-content;
-max-width: min-content;
-max-width: fit-content;
-max-width: fill-available;
-
-/* Global values */
-max-width: inherit;
-max-width: initial;
-max-width: unset;
-
- -

{{ Cssxref("max-width") }} overrides {{cssxref("width")}}, but {{ Cssxref("min-width") }} overrides {{ Cssxref("max-width") }}.

- -

{{cssinfo}}

- -

Syntax

- -

Values

- -
-
{{cssxref("<length>")}}
-
The maximum width, expressed as a {{cssxref("<length>")}}.
-
{{cssxref("<percentage>")}}
-
The maximum width, expressed as a {{cssxref("<percentage>")}} of the containing block's width.
-
- -

Keyword values

- -
-
none
-
The width has no maximum value.
-
max-content{{experimental_inline()}}
-
The intrinsic preferred width.
-
min-content{{experimental_inline()}}
-
The intrinsic minimum width.
-
fill-available{{experimental_inline()}}
-
The containing block's width minus the horizontal margin, border, and padding. (Note that some browsers implement an ancient name for this keyword, available.)
-
fit-content{{experimental_inline()}}
-
The same as max-content.
-
- -

Formal syntax

- -{{csssyntax}} - -

Examples

- -

In this example, the "child" will be either 150 pixels wide or the width of the "parent," whichever is smaller:

- -
-
<div id="parent">
-  <div id="child">
-    Fusce pulvinar vestibulum eros, sed luctus ex lobortis quis.
-  </div>
-</div>
-
- -
#parent {
-  background: lightblue;
-  width: 300px;
-}
-
-#child {
-  background: gold;
-  width: 100%;
-  max-width: 150px;
-}
-
-
- -

{{EmbedLiveSample("basic-max-width-demo", 350, 100)}}

- -

The fit-content value can be used to set the width of an element based on the intrinsic size required by its content:

- -
- - -
#parent {
-  background: lightblue;
-  width: 300px;
-}
-
-#child  {
-  background: gold;
-  width: 100%;
-  max-width: -moz-fit-content;
-  max-width: -webkit-fit-content;
-}
-
-
- -

{{EmbedLiveSample("fit-content-demo", 400, 100)}}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{ SpecName('CSS3 Sizing', '#width-height-keywords', 'max-width') }}{{ Spec2('CSS3 Sizing') }}Adds the max-content, min-content, fit-content, and fill-available keywords. (Both CSS3 Box and CSS3 Writing Modes drafts used to define these keywords, but are superseded by this spec.)
{{ SpecName('CSS3 Transitions', '#animatable-css', 'max-width') }}{{ Spec2('CSS3 Transitions') }}Defines max-width as animatable.
{{ SpecName('CSS2.1', 'visudet.html#min-max-widths', 'max-width') }}{{ Spec2('CSS2.1') }}Initial definition.
- -

Browser compatibility

- - - -

{{Compat("css.properties.max-width")}}

- -

See also

- - diff --git a/files/es/web/http/cors/errors/corsnotsupportingcredentials/index.html b/files/es/web/http/cors/errors/corsnotsupportingcredentials/index.html deleted file mode 100644 index b27a103689..0000000000 --- a/files/es/web/http/cors/errors/corsnotsupportingcredentials/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: >- - Reason: Credential is not supported if the CORS header - ‘Access-Control-Allow-Origin’ is ‘*’ -slug: Web/HTTP/CORS/Errors/CORSNotSupportingCredentials -translation_of: Web/HTTP/CORS/Errors/CORSNotSupportingCredentials ---- -
{{HTTPSidebar}}
- -

Reason

- -
Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’
- -

What went wrong?

- -

The {{Glossary("CORS")}} request was attempted with the credentials flag set, but the server is configured using the wildcard ("*") as the value of {{HTTPHeader("Access-Control-Allow-Origin")}}, which doesn't allow the use of credentials.

- -

To correct this problem on the client side, simply ensure that the credentials flag's value is false when issuing your CORS request.

- - - -

If, instead, you need to adjust the server's behavior, you'll need to change the value of Access-Control-Allow-Origin to grant access to the origin from which the client is loaded.

- -

See also

- - diff --git a/files/es/web/http/headers/accept-charset/index.html b/files/es/web/http/headers/accept-charset/index.html deleted file mode 100644 index 26433c22db..0000000000 --- a/files/es/web/http/headers/accept-charset/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Accept-Charset -slug: Web/HTTP/Headers/Accept-Charset -tags: - - Negociación de Contenido -translation_of: Web/HTTP/Headers/Accept-Charset ---- -
{{HTTPSidebar}}
- -

The Accept-Charset request HTTP header advertises which character set the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice within the {{HTTPHeader("Content-Type")}} response header. Browsers usually don't set this header as the default value for each content type is usually correct and transmitting it would allow easier fingerprinting.

- -

If the server cannot serve any matching character set, it can theoretically send back a {{HTTPStatus("406")}} (Not Acceptable) error code. But, for a better user experience, this is rarely done and the more common way is to ignore the Accept-Charset header in this case.

- -
-

In early versions of HTTP/1.1, a default charset (ISO-8859-1) was defined. This is no more the case and now each content type may have its own default.

-
- - - - - - - - - - - - -
Header type{{Glossary("Request header")}}
{{Glossary("Forbidden header name")}}yes
- -

Syntax

- -
Accept-Charset: <charset>
-
-// Multiple types, weighted with the {{glossary("quality values", "quality value")}} syntax:
-Accept-Charset: utf-8, iso-8859-1;q=0.5
- -

Directives

- -
-
<charset>
-
Un conjunto de caracteres como utf-8 o iso-8859-15.
-
*
-
Any charset not mentioned elsewhere in the header; '*' being used as a wildcard.
-
;q= (q-factor weighting)
-
Any value is placed in an order of preference expressed using a relative quality value called the weight.
-
- -

Examples

- -
Accept-Charset: iso-8859-1
-
-Accept-Charset: utf-8, iso-8859-1;q=0.5
-
-Accept-Charset: utf-8, iso-8859-1;q=0.5, *;q=0.1
-
- -

Especificaciones

- - - - - - - - - - - - -
EspecificaciónTítulo
{{RFC("7231", "Accept-Charset", "5.3.3")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Context
- -

Compatibilidad del navegador

- - - -

{{Compat("http.headers.Accept-Charset")}}

- -

También puedes revisar:

- - diff --git a/files/es/web/http/status/301/index.html b/files/es/web/http/status/301/index.html deleted file mode 100644 index 496fb038f3..0000000000 --- a/files/es/web/http/status/301/index.html +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: 301 Movido Permanentemente -slug: Web/HTTP/Status/301 -translation_of: Web/HTTP/Status/301 ---- -
{{HTTPSidebar}}
- -

The HyperText Transfer Protocol (HTTP) 301 Moved Permanently redirect status response code indicates that the resource requested has been definitively moved to the URL given by the {{HTTPHeader("Location")}} headers. A browser redirects to this page and search engines update their links to the resource (in 'SEO-speak', it is said that the 'link-juice' is sent to the new URL).

- -

Even if the specification requires the method (and the body) not to be altered when the redirection is performed, not all user-agents align with it - you can still find this type of bugged software out there. It is therefore recommended to use the 301 code only as a response for {{HTTPMethod("GET")}} or {{HTTPMethod("HEAD")}} methods and to use the {{HTTPStatus("308", "308 Permanent Redirect")}} for {{HTTPMethod("POST")}} methods instead, as the method change is explicitly prohibited with this status.

- -

Status

- -
301 Moved Permanently
- -

Example

- -

Client request

- -
GET /index.php HTTP/1.1
-Host: www.example.org
- -

Server response

- -
HTTP/1.1 301 Moved Permanently
-Location: http://www.example.org/index.asp
- -

Specifications

- - - - - - - - - - - - -
SpecificationTitle
{{RFC("7231", "301 Moved Permanently" , "6.4.2")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
- -

Browser compatibility

- - - -

{{Compat("http.status.301")}}

- -

See also

- - diff --git a/files/es/web/javascript/reference/deprecated_and_obsolete_features/the_legacy_iterator_protocol/index.html b/files/es/web/javascript/reference/deprecated_and_obsolete_features/the_legacy_iterator_protocol/index.html deleted file mode 100644 index 007decfe89..0000000000 --- a/files/es/web/javascript/reference/deprecated_and_obsolete_features/the_legacy_iterator_protocol/index.html +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: The legacy Iterator protocol -slug: >- - Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol -translation_of: >- - Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol -original_slug: >- - Web/JavaScript/Referencia/Características_Desaprobadas/The_legacy_Iterator_protocol ---- -
{{jsSidebar("More")}}
- -
Non-standard. The legacy iterator protocol is a SpiderMonkey-specific feature, and will be removed at some point. For future-facing usages, consider using for..of loops and the iterator protocol.
- -

The deprecated Firefox-only iterator protocol

- -

Firefox, prior to version 26 implemented another iterator protocol that is similar to the standard ES6 Iterator protocol.

- -

An object is an legacy iterator when it implements a next() method with the following semantics, and throws {{jsxref("Global_Objects/StopIteration", "StopIteration")}} at the end of iteration.

- - - - - - - - - - - - -
PropertyValue
nextA zero arguments function that returns an value.
- -

Difference between legacy and ES6 iterator protocols

- - - -

Simple example with the old protocol

- -
function makeIterator(array){
-    var nextIndex = 0;
-
-    return {
-       next: function(){
-           if(nextIndex < array.length){
-               return array[nextIndex++];
-           else
-               throw new StopIteration();
-       }
-    }
-}
-
-var it = makeIterator(['yo', 'ya']);
-
-console.log(it.next()); // 'yo'
-console.log(it.next()); // 'ya'
-try{
-    console.log(it.next());
-}
-catch(e){
-    if(e instanceof StopIteration){
-         // iteration over
-    }
-}
-
- -

Mira también

- - diff --git a/files/es/web/javascript/reference/errors/precision_range/index.html b/files/es/web/javascript/reference/errors/precision_range/index.html deleted file mode 100644 index 22c37598ff..0000000000 --- a/files/es/web/javascript/reference/errors/precision_range/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: 'RangeError: precision is out of range' -slug: Web/JavaScript/Reference/Errors/Precision_range -translation_of: Web/JavaScript/Reference/Errors/Precision_range ---- -
{{jsSidebar("Errors")}}
- -

The JavaScript exception "precision is out of range" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into toFixed or toPrecision.

- -

Message

- -
RangeError: The number of fractional digits is out of range (Edge)
-RangeError: The precision is out of range (Edge)
-RangeError: precision {0} out of range (Firefox)
-RangeError: toExponential() argument must be between 0 and 20 (Chrome)
-RangeError: toFixed() digits argument must be between 0 and 20 (Chrome)
-RangeError: toPrecision() argument must be between 1 and 21 (Chrome)
-
- -

Error type

- -

{{jsxref("RangeError")}}

- -

Que salió mal?

- -

Fué un argumento preciso fuera de rango en uno de estos metodos:

- - - -

El rango permitido para estos metodos usualmente esta entre 0 o 20 (o 21). De todas formas la especificación  ECMAScript permite extender este rango.

- - - - - - - - - - - - - - - - - - - - - - - - - - -
MethodFirefox (SpiderMonkey)Chrome, Opera (V8)
{{jsxref("Number.prototype.toExponential()")}}0 to 1000 to 20
{{jsxref("Number.prototype.toFixed()")}}-20 to 1000 to 20
{{jsxref("Number.prototype.toPrecision()")}}1 to 1001 to 21
- -

Examples

- -

Casos no validos

- -
77.1234.toExponential(-1);  // RangeError
-77.1234.toExponential(101); // RangeError
-
-2.34.toFixed(-100);         // RangeError
-2.34.toFixed(1001);         // RangeError
-
-1234.5.toPrecision(-1);     // RangeError
-1234.5.toPrecision(101);    // RangeError
-
- -

Casos validos

- -
77.1234.toExponential(4); // 7.7123e+1
-77.1234.toExponential(2); // 7.71e+1
-
-2.34.toFixed(1); // 2.3
-2.35.toFixed(1); // 2.4 (note that it rounds up in this case)
-
-5.123456.toPrecision(5); // 5.1235
-5.123456.toPrecision(2); // 5.1
-5.123456.toPrecision(1); // 5
-
- -

También te puede interesar:

- - diff --git a/files/es/web/javascript/reference/global_objects/date/getutchours/index.html b/files/es/web/javascript/reference/global_objects/date/getutchours/index.html deleted file mode 100644 index 525a0a2730..0000000000 --- a/files/es/web/javascript/reference/global_objects/date/getutchours/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: Date.prototype.getUTCHours() -slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCHours -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCHours -original_slug: Web/JavaScript/Referencia/Objetos_globales/Date/getUTCHours ---- -
{{JSRef}}
- -

El método getUTCHours() retorna las horas especificadas en la fecha deacuerdo al horario universal.

- -

Syntax

- -
dateObj.getUTCHours()
- -

Return value

- -

An integer number, between 0 and 23, representing the hours in the given date according to universal time.

- -

Examples

- -

Using getUTCHours()

- -

The following example assigns the hours portion of the current time to the variable hours.

- -
var today = new Date();
-var hours = today.getUTCHours();
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.19', 'Date.prototype.getUTCHours')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getutchours', 'Date.prototype.getUTCHours')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getutchours', 'Date.prototype.getUTCHours')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/es/web/javascript/reference/global_objects/math/fround/index.html b/files/es/web/javascript/reference/global_objects/math/fround/index.html deleted file mode 100644 index ff06c8c12c..0000000000 --- a/files/es/web/javascript/reference/global_objects/math/fround/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Math.fround() -slug: Web/JavaScript/Reference/Global_Objects/Math/fround -tags: - - JavaScript - - Math - - Referencia - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/Math/fround -original_slug: Web/JavaScript/Referencia/Objetos_globales/Math/fround ---- -
{{JSRef}}
- -

The Math.fround() function returns the nearest 32-bit single precision float representation of a {{jsxref("Number")}}.

- -
{{EmbedInteractiveExample("pages/js/math-fround.html")}}
- - - -

Syntax

- -
var singleFloat = Math.fround(doubleFloat);
- -

Parameters

- -
-
doubleFloat
-
A {{jsxref("Number")}}. If the parameter is of a different type, it will get converted to a number or to {{jsxref("NaN")}} if it cannot be converted.
-
- -

Return value

- -

The nearest 32-bit single precision float representation of the given number.

- -

Description

- -

JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a {{jsxref("Float32Array")}}. This can create confusion: Checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical.

- -

To solve this, Math.fround() can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to 0. If the number is outside the range of a 32-bit float, {{jsxref("Infinity")}} or -Infinity is returned.

- -

Because fround() is a static method of Math, you always use it as Math.fround(), rather than as a method of a Math object you created (Math is not a constructor).

- -

Examples

- -

Using Math.fround()

- -

The number 1.5 can be precisely represented in the binary numeral system, and is identical in 32-bit and 64-bit:

- -
Math.fround(1.5); // 1.5
-Math.fround(1.5) === 1.5; // true
-
- -

However, the number 1.337 cannot be precisely represented in the binary numeral system, so it differs in 32-bit and 64-bit:

- -
Math.fround(1.337); // 1.3370000123977661
-Math.fround(1.337) === 1.337; // false
-
- -

21502^150 is too big for a 32-bit float, so Infinity is returned:

- -
2 ** 150; // 1.42724769270596e+45
-Math.fround(2 ** 150); // Infinity
-
- -

If the parameter cannot be converted to a number, or it is not-a-number (NaN), Math.fround() will return NaN:

- -
Math.fround('abc'); // NaN
-Math.fround(NaN); // NaN
-
- -

Polyfill

- -

This can be emulated with the following function, if {{jsxref("Float32Array")}} are supported:

- -
Math.fround = Math.fround || (function (array) {
-  return function(x) {
-    return array[0] = x, array[0];
-  };
-})(new Float32Array(1));
-
- -

Supporting older browsers is slower, but also possible:

- -
if (!Math.fround) Math.fround = function(arg) {
-  arg = Number(arg);
-  // Return early for ±0 and NaN.
-  if (!arg) return arg;
-  var sign = arg < 0 ? -1 : 1;
-  if (sign < 0) arg = -arg;
-  // Compute the exponent (8 bits, signed).
-  var exp = Math.floor(Math.log(arg) / Math.LN2);
-  var powexp = Math.pow(2, Math.max(-126, Math.min(exp, 127)));
-  // Handle subnormals: leading digit is zero if exponent bits are all zero.
-  var leading = exp < -127 ? 0 : 1;
-  // Compute 23 bits of mantissa, inverted to round toward zero.
-  var mantissa = Math.round((leading - arg / powexp) * 0x800000);
-  if (mantissa <= -0x800000) return sign * Infinity;
-  return sign * powexp * (leading - mantissa / 0x800000);
-};
- -

Faster Alternative Polyfill (Work In Progress)

- -

The below polyfill is much faster and uses double-precision rounding errors to emulate the rounding errors caused by floating point narrowing. Although the polyfill higher on the page is good for comprehension, all of the complex Math function that it uses make it terrible slow. Although this polyfill is much faster, it is off by a bit in about 1 out of 2048 of the tests due to the tendency to round upwards like Math.ceil instead of like Math.round in the division of the subnormal-handling section of the code. Because single precision floating points have 23 bits of precision, the mean error deviation from the correct value is roughly 2**-28 or 0.0000000058%. This deviation from the correct value should be insignifigant in most circumstances, however please edit this polyfill if you have some tweaks to increase correctness without bloating the code size too much. NaN is not optimized for because it is most likely (almost certain) that you will not be calling Math.fround with NaN exclusively in a tight loop. Moreover, an additional check just for NaN instead of letting NaN naturally arise would induce a performance penalty for this function in older browsers when not called with NaN. Thus, the code below handles NaN correctly, but inefficiently for good reason.

- -
const Math_round = Math.round;
-if (!Math.fround) Math.fround = function(x) {
-    if (x > 3.402823669209385e+38) return Infinity; // maximum float is 2**128
-    if (x < -3.402823669209385e+38) return -Infinity; // minimum is -2**128
-    if (-1.1754943508222875e-38 < x && x < 1.1754943508222875e-38) {
-        if (-1.401298464324817e-45 < x && x < 1.401298464324817e-45) return 0;
-        // else, it is a subnormal
-        var mul = Math_round(x/1.4012984643e-45)*1e-323;
-        return mul * 1.418129833677085e+278;
-    }
-
-    var hi = x * 9007199254740992; // 9007199254740992 is 2**53 which is the maximum of double precision
-    var exp = (x + hi) - hi; // adding this number chops off all lower bits, rounding the number.
-    exp /= 16777216; // 8388608 = 2**23 * 2, so preserve 23 bits in x because there are 23 bits in a float
-                     //            The "* 2" compensates for the addition shifting up the bits unwantedly
-    return Math_round(x / exp) * exp;
-}
-
- -

Below is code used to test for deviations from the correct value. The code below is meant for testing the merit of the function, not for polyfilling older browsers (as evidenced by the fact that the native Math.fround function is used).

- -
requestIdleCallback(function(){"use strict";
-    const Math_fround = Math.fround;
-    const Math_round = Math.round;
-    function my_fround(x) {
-        if (x > 3.402823669209385e+38) return Infinity; // maximum float is 2**128
-        if (x < -3.402823669209385e+38) return -Infinity; // minimum is -2**128
-        if (-1.1754943508222875e-38 < x && x < 1.1754943508222875e-38) {
-            if (-1.401298464324817e-45 < x && x < 1.401298464324817e-45) return 0;
-            // else, it is a subnormal
-            var mul = Math_round(x/1.4012984643e-45)*1e-323;
-            return mul * 1.418129833677085e+278;
-        }
-
-        var hi = x * 9007199254740992; // 9007199254740992 is 2**53 which is the maximum of double precision
-        var exp = (x + hi) - hi; // adding this number chops off all lower bits, rounding the number.
-        exp /= 16777216; // 8388608 = 2**23 * 2, so preserve 23 bits in x because there are 23 bits in a float
-                         //            The "* 2" compensates for the addition shifting up the bits unwantedly
-        return Math_round(x / exp) * exp;
-    }
-
-    const doublesArray = new Float64Array(8192);
-    const int32s = new Uint32Array(doublesArray.buffer);
-
-    const crypto = window.crypto;
-
-    var hasWarned = false, warnings=0;
-    for (var i=0; i<4; i=i+1|0) {
-        crypto.getRandomValues(int32s);
-        for (var k=0; k<8192; k=k+1|0) {
-            const myValue = my_fround(doublesArray[k]);
-            const froundVal = Math_fround(doublesArray[k]);
-            // quicker version of Object.is because of no function call overhead:
-            if (myValue === myValue ? myValue !== froundVal : froundVal === froundVal) {
-                if (!hasWarned) console.error(doublesArray[k]); // only show the first incorrect number
-                hasWarned = true;
-                warnings = warnings + 1|0;
-            }
-        }
-    }
-    console[warnings > 0 ? "warn" : "log"]( "Total number of mishandled floats: " + warnings );
-});
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-math.fround', 'Math.fround')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.fround', 'Math.fround')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -

{{Compat("javascript.builtins.Math.fround")}}

- -

See also

- - diff --git a/files/es/web/javascript/reference/global_objects/object/__lookupgetter__/index.html b/files/es/web/javascript/reference/global_objects/object/__lookupgetter__/index.html deleted file mode 100644 index d99273a3fe..0000000000 --- a/files/es/web/javascript/reference/global_objects/object/__lookupgetter__/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Object.prototype.__lookupGetter__() -slug: Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__ -translation_of: Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__ -original_slug: Web/JavaScript/Referencia/Objetos_globales/Object/__lookupGetter__ ---- -
{{JSRef}} {{deprecated_header}}
- -

Los __lookupGetter__ metodos retornan la funcion  enlazada como un getter para especificar la propiedad.

- -

Syntax

- -
obj.__lookupGetter__(sprop)
- -

Parameters

- -
-
sprop
-
A string containing the name of the property whose getter should be returned.
-
- -

Return value

- -

The function bound as a getter to the specified property.

- -

Description

- -

If a getter has been defined for an object's property, it's not possible to reference the getter function through that property, because that property refers to the return value of that function. __lookupGetter__ can be used to obtain a reference to the getter function.

- -

It is now possible to do this in a standardized way using {{jsxref("Object.getOwnPropertyDescriptor()")}} and {{jsxref("Object.getPrototypeOf()")}}.

- -

Examples

- -
var obj = {
-  get foo() {
-    return Math.random() > 0.5 ? 'foo' : 'bar';
-  }
-};
-
-
-// Non-standard and deprecated way
-obj.__lookupGetter__('foo');
-// (function() { return Math.random() > 0.5 ? 'foo' : 'bar'; })
-
-
-// Standard-compliant way
-Object.getOwnPropertyDescriptor(obj, "foo").get;
-// (function() { return Math.random() > 0.5 ? 'foo' : 'bar'; })
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-object.prototype.__lookupGetter__', 'Object.prototype.__lookupGetter__()')}}{{Spec2('ESDraft')}}Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Object.lookupGetter")}}

-
- -

See also

- - diff --git a/files/es/web/media/formats/containers/index.html b/files/es/web/media/formats/containers/index.html deleted file mode 100644 index 2864534d67..0000000000 --- a/files/es/web/media/formats/containers/index.html +++ /dev/null @@ -1,1329 +0,0 @@ ---- -title: Media container formats (file types) -slug: Web/Media/Formats/Containers -tags: - - Hugo javier duran miranda. -translation_of: Web/Media/Formats/Containers ---- -
{{QuickLinksWithSubpages("/en-US/docs/Web/Media")}}
- -

The format of audio and video media files is defined in two parts (three if a file has both audio and video in it, of course): the audio and/or video codecs used and the media container format (or file type) used. In this guide, we'll look at the container formats used most commonly on the web, covering basics about their specifications as well as their benefits, limitations, and ideal use cases.

- -

WebRTC does not use a container at all. Instead, it streams the encoded audio and video tracks directly from one peer to another using {{domxref("MediaStreamTrack")}} objects to represent each track. See Codecs used by WebRTC for information about codecs commonly used for making WebRTC calls, as well as browser compatibility information around codec support in WebRTC.

- -

Common container formats

- -

While there are a vast number of media container formats, the ones listed below are the ones you are most likely to encounter. Some support only audio while others support both audio and video. The MIME types and extensions for each are listed.The most commonly used containers for media on the web are probably MPEG-4 (MP4), QuickTime Movie (MOV), and the Wavefile Audio File Format (WAV). However, you may also encounter MP3, Ogg, WebM, AVI, and other formats. Not all of these are broadly supported by browsers, however; some combinations of container and codec are sometimes given their own file extensions and MIME types as a matter of convenience, or because of their ubiquity. For example, an Ogg file with only an Opus audio track is sometimes referred to as an Opus file, and might even have the extension .opus. But it's still actually just an Ogg file.

- -

In other cases, a particular codec, stored in a certain container type, is so ubiquitous that the pairing is treated in a unique fashion. A good example of this is the MP3 audio file, which is in fact an MPEG-1 container with a single audio track encoded using MPEG-1 Audio Layer III encoding. These files use the audio/mp3 MIME type and the .mp3 extension, even though their containers are just MPEG.

- -

Index of media container formats (file types)

- -

To learn more about a specific container format, find it in this list and click through to the details, which include information about what the container is typically useful for, what codecs it supports, and which browsers support it, among other specifics.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Codec name (short)Full codec nameBrowser compatibility1
{{anch("3GP")}}Third Generation PartnershipFirefox for Android
{{anch("ADTS")}}Audio Data Transport StreamFirefox2
{{anch("FLAC")}}Free Lossless Audio CodecChrome 56, Edge 16, Firefox 51, Safari 11
{{anch("MPEG", "MPEG / MPEG-2")}}Moving Picture Experts Group (1 and 2)
{{anch("MP4", "MPEG-4 (MP4)")}}Moving Picture Experts Group 4Chrome 3, Edge 12, Firefox, Internet Explorer 9, Opera 24, Safari 3.1
{{anch("Ogg")}}OggChrome 3, Firefox 3.5, Edge 173 (desktop only), Internet Explorer 9, Opera 10.50
{{anch("QuickTime", "QuickTime (MOV)")}}Apple QuickTime movieOnly older versions of Safari, plus other browsers that supported Apple's QuickTime plugin
{{anch("WebM")}}Web MediaChrome 6, Edge 173 (desktop only), Firefox 4, Opera 10.6, Safari (WebRTC only)
- -

[1] Unless otherwise specified, both mobile and desktop browser compatibility is implied if a browser is listed here. Support is also implied only for the container itself, not for any specific codecs.

- -

[2] Available only if available on the underlying operating system's media framework.

- -

[3] Requires Web Media Extensions to be installed.

- -

3GP

- -

The 3GP or 3GPP media container is used to encapsulate audio and/or video that is specifically intended for transmission over cellular networks for consumption on mobile devices. The format was designed for use on 3G mobile phones, but can still be used on more modern phones and networks. However, the improved bandwidth availability and increased data caps on most networks has reduced the need for the 3GP format. However, this format is still used for slower networks and for lower-performance phones.

- -

This media container format is derived from the ISO Base Media File Format and MPEG-4, but is specifically streamlined for lower bandwidth scenarios.

- - - - - - - - - - - - - - - - - - - - - - - -
Base 3GP media MIME types
AudioVideo
audio/3gppvideo/3gpp
audio/3gpp2video/3gpp2
audio/3gp2video/3gp2
- -

These MIME types are the fundamental types for the 3GP media container; other types may be used depending on the specific codec or codecs in use; in addition, you can add the codecs parameter to the MIME type string to indicate which codecs are used for the audio and/or video tracks, and to optionally provide details about the profile, level, and/or other codec configuration specifics.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Video codecs supported by 3GP
CodecBrowser support
ChromeEdgeFirefoxSafari
AVC (H.264)Yes1,2
H.263Yes1
MPEG-4 Part 2 (MP4v-es)Yes1
VP8Yes1
- -

[1] Firefox only supports 3GP on OpenMAX-based devices, which currently means the Boot to Gecko (B2G) platform.

- -

[2] Firefox support for H.264 relies upon the operating system's media infrastructure, so it is available as long as the OS supports it.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Audio codecs supported by 3GP
CodecBrowser support
ChromeEdgeFirefoxSafari
AMR-NBYes1
AMR-WBYes1
AMR-WB+Yes1
AAC-LCYes1,2
HE-AAC v1Yes1,2
HE-AAC v2Yes1,2
MP3Yes1
- -

[1] Firefox only supports 3GP on OpenMAX-based devices, which currently means the Boot to Gecko (B2G) platform.

- -

[2] Firefox support for AAC relies upon the operating system's media infrastructure, so it is available as long as the OS supports it.

- -

ADTS

- -

Audio Data Transport Stream (ADTS) is a container format specified by MPEG-4 Part 3 for audio data, intended to be used for streamed audio, such as for Internet radio. It is, essentially, an almost bare stream of AAC audio data, comprised of ADTS frames with a minimal header.

- - - - - - - - - - - - - - - - -
ADTS media MIME types
Audio
audio/aac[1]
audio/mpeg[1]
- -

[1] The MIME type used for ADTS depends on what kind of audio frames are contained within. If ADTS frames are used, the audio/aac MIME type should be used. If the audio frames are in MPEG-1/MPEG-2 Audio Layer I, II, or III format, the MIME type should be audio/mpeg.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Audio codecs supported by ADTS
CodecBrowser support
ChromeEdgeFirefoxSafari
AACYes1
MP3Yes
- -

[1] Firefox support for AAC relies upon the operating system's media infrastructure, so it is available as long as the OS supports it.

- -

FLAC

- -

The Free Lossless Audio Codec (FLAC) is a lossless audio codec; there is also an associated simple container format, also called FLAC, that can contain this audio. The format is not encumbered by any patents, so its use is safe from interference. FLAC files can only contain FLAC audio data.

- - - - - - - - - - - - - - - - -
FLAC media MIME type
Audio
audio/flac
audio/x-flac (non-standard)
- - - - - - - - - - - - - - - - - - - - - - - - -
Audio codecs supported by FLAC
CodecBrowser support
ChromeEdgeFirefoxSafari
FLACYes
- -

MPEG/MPEG-2

- -

The {{interwiki("wikipedia", "MPEG-1")}} and {{interwiki("wikipedia", "MPEG-2")}} file formats are essentially identical. Created by the Moving Picture Experts Group (MPEG), these formats are widely used in physical media, including as the format of the video on DVD media.

- -

On the internet, perhaps the most common use of the MPEG file format is to contain {{interwiki("wikipedia", "MPEG-1", "Layer_III/MP3", "MPEG-1 Audio Layer 3")}} sound data; the resulting files are the wildly popular MP3 file used by digital music devices around the world. Otherwise, MPEG-1 and MPEG-2 are not widely used in Web content.

- -

The main differences between MPEG-1 and MPEG-2 take place in the media data formats rather than the container format. MPEG-1 was introduced in 1992; MPEG-2 was introduced in 1996.

- - - - - - - - - - - - - - - -
MPEG-1 and MPEG-2 media MIME types
AudioVideo
audio/mpegvideo/mpeg
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Video codecs supported by MPEG-1 and MPEG-2
CodecBrowser support
ChromeEdgeFirefoxSafari
MPEG-1 Part 2No
MPEG-2 Part 2No
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Audio codecs supported by MPEG-1 and MPEG-2
CodecBrowser support
ChromeEdgeFirefoxSafari
MPEG-1 Audio Layer INo
MPEG-1 Audio Layer IINo
MPEG-1 Audio Layer III (MP3)Yes
- -

MPEG-4 (MP4)

- -

{{interwiki("wikipedia", "MPEG-4")}} (MP4) is the latest version of the MPEG file format. There are two versions of the format, defined in parts 1 and 14 of the specification. MP4 is a popular container today, as it supports several of the most-used codecs and is broadly supported.

- -

The original MPEG-4 Part 1 file format was introduced in 1999; the version 2 format, defined in Part 14, was added in 2003. The MP4 file format is derived from the {{interwiki("wikipedia", "ISO base media file format")}}, which is directly derived from the {{interwiki("wikipedia", "QuickTime file format")}} developed by Apple.

- -

When specifying the MPEG-4 media type (audio/mp4 or video/mp4), you can add the codecs parameter to the MIME type string to indicate which codecs are used for the audio and/or video tracks, and to optionally provide details about the profile, level, and/or other codec configuration specifics.

- - - - - - - - - - - - - - - -
Base MPEG-4 media MIME types
AudioVideo
audio/mp4video/mp4
- -

These MIME types are the fundamental types for the MPEG-4 media container; other MIME types may be used depending on the specific codec or codecs in use within the container. In addition, you can add the codecs parameter to the MIME type string to indicate which codecs are used for the audio and/or video tracks, and to optionally provide details about the profile, level, and/or other codec configuration specifics.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Video codecs supported by MPEG-4
CodecBrowser support
ChromeEdgeFirefoxSafari
AVC (H.264)Yes1
AV1Yes1
H.263No
MPEG-4 Part 2 VisualNo
VP9Yes
- -

[1] Firefox support for H.264 relies upon the operating system's media infrastructure, so it is available as long as the OS supports it.

- -

[2] Firefox support for AV1 is currently disabled by default; it can be enabled by setting the preference media.av1.enabled to true.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Audio codecs supported by MPEG-4
CodecBrowser support
ChromeEdgeFirefoxSafari
AACYes1
FLACYes
MPEG-1 Audio Layer III (MP3)Yes
OpusYes
- -

[1] Firefox support for H.264 relies upon the operating system's media infrastructure, so it is available as long as the OS supports it.

- -

Ogg

- -

The {{interwiki("wikipedia", "Ogg")}} container format is a free and open format maintained by the Xiph.org Foundation. The Ogg framework also defines patent unencumbered media data formats, such as the Theora video codec and the Vorbis and Opus audio codecs. Xiph.org documents about the Ogg format are available on their web site.

- -

While Ogg has been around for a long time, it has never gained the wide support needed to make it a good first choice for a media container. You are typically better off using WebM, though there are times when Ogg is useful to offer, such as when you wish to support older versions of Firefox and Chrome which don't yet support WebM. For example, Firefox 3.5 and 3.6 support Ogg, but not WebM.

- -

You can get more information about Ogg and its codecs in the Theora Cookbook.

- - - - - - - - - - - - - - - -
Base Ogg media MIME types
AudioVideo
audio/oggvideo/ogg
- -

The application/ogg MIME type can be used when you don't necessarily know whether the media contains audio or video. If at all possible, you should use one of the specific types, but fall back to application/ogg if you don't know the content format or formats.

- -

You can also add the codecs parameter to the MIME type string to indicate which codecs are used for the audio and/or video tracks, and to optionally further describe the track media formats.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Video codecs supported by Ogg
CodecBrowser support
ChromeEdgeFirefoxSafari
TheoraYes
VP8Yes
VP9Yes
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Audio codecs supported by Ogg
CodecBrowser support
ChromeEdgeFirefoxSafari
FLACYes
OpusYes
VorbisYes
- -

QuickTime

- -

The QuickTime file format (QTFF, QT, or MOV) was created by Apple for use by its media framework of the same name. The extension for these files, .mov, comes from the fact that the format was initially used for movies and was usually called the "QuickTime movie" format. While QTFF served as the basis for the MPEG-4 file format, there are differences and the two are not quite interchangeable.

- -

QuickTime files support any sort of time-based data, including audio and video media, text tracks, and so forth. QuickTime files are primarily supported by macOS, but for a number of years, QuickTime for Windows was available to access them on Windows. However, QuickTime for Windows is no longer supported by Apple as of early 2016, and should not be used, as there are known security concerns. However, Windows Media Player now has integrated support for  QuickTime version 2.0 and earlier files; support for later versions of QuickTime requires third-party additions.

- -

On Mac OS, the QuickTime framework not only supported QuickTime format movie files and codecs, but supported a vast array of popular and specialty audio and video codecs, as well as still image formats. Through QuickTime, Mac applications (including web browsers, through the QuickTime plugin or direct QuickTime integration) were able to read and write audio formats including AAC, AIFF, MP3, PCM, and Qualcomm PureVoice; and video formats including AVI, DV, Pixlet, ProRes, FLAC, Cinepak, 3GP, H.261 through H.265, MJPEG, MPEG-1 and MPEG-4 Part 2, Sorenson, and many more.

- -

In addition, a number of third-party components are available for QuickTime, some of which add support for additional codecs.

- -

Because QuickTime support is, for all intents and purposes, primarily available on Apple devices, it is no longer widely used on the internet. Apple itself generally now uses MP4 for video. In addition, the QuickTime framework has been deprecated on the Mac for some time, and is no longer available at all starting in macOS 10.15 Catalina.

- - - - - - - - - - - - - -
Base QuickTime media MIME type
Video
video/quicktime
- -

The video/quicktime MIME type is the fundamental type for the QuickTime media container. It's worth noting that QuickTime (the media framework on Mac operating systems) supports a wide variety of containers and codecs, so it actually supports many other MIME types.

- -

You can add the codecs parameter to the MIME type string to indicate which codecs are used for the audio and/or video tracks, and to optionally provide details about the profile, level, and/or other codec configuration specifics.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Video codecs supported by QuickTime
CodecBrowser support
ChromeEdgeFirefoxSafari
AVC (H.264)No
CinepakNo
Component VideoNo
DVNo
H.261No
H.263No
MPEG-2No
MPEG-4 Part 2 VisualNo
Motion JPEGNo
Sorenson Video 2No
Sorenson Video 3No
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Audio codecs supported by QuickTime
CodecBrowser support
ChromeEdgeFirefoxSafari
AACNo
ALaw 2:1No
Apple Lossless (ALAC)No
HE-AACNo
MPEG-1 Audio Layer III (MP3)No
Microsoft ADPCMNo
µ-Law 2:1 (u-Law)No
- -

WAVE (WAV)

- -

The Waveform Audio File Format (WAVE), usually referred to simply as WAV due to its filename extension being .wav, is a format developed by Microsoft and IBM to store audio bitstream data.

- -

It is derived from the Resource Interchange File Format (RIFF), and as such is similar to other formats such as Apple's AIFF. The WAV codec registry can be found at {{RFC(2361)}}; however, because nearly all WAV files use linear PCM, support for the other codecs is sparse.

- -

The WAVE format was first released in 1991.

- - - - - - - - - - - - - - - - - - - - - - -
WAVE media MIME types
Audio
audio/wave1
audio/wav
audio/x-wav
audio/x-pn-wav
- -

[1] The audio/wave MIME type is the standard type, and is preferred; however, the others have been used by various products over the years and may be used as well in some environments. 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Audio codecs supported by WAVE
CodecBrowser support
ChromeEdgeFirefoxSafari
ADPCM (Adaptive Differential Pulse Code Modulation)No
GSM 06.10No
LPCM (Linear Pulse Code Modulation)Yes
MPEG-1 Audio Layer III (MP3)No
µ-Law (u-Law)No
- -

WebM

- -

{{interwiki("wikipedia", "WebM")}} (Web Media) is a format based on {{interwiki("wikipedia", "Matroska")}} which is designed specifically for use in modern web environments. It's based entirely on free and open technologies and primarily uses codecs that are in turn free and open, although some products support other codecs in WebM containers as well.

- -

WebM was first introduced in 2010 and is now widely supported. Compliant implementations of WebM are required to support the VP8 and VP8 video codecs and the Theora and Opus audio codecs. The WebM container format and its required codecs are all available under open licenses. Any other codecs may require a license to use.

- - - - - - - - - - - - - - - -
WebM media MIME types
AudioVideo
audio/webmvideo/webm
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Video codecs supported by WebM
CodecBrowser support
ChromeEdgeFirefoxSafari
AV1YesYesYes1Yes
VP8YesYesYesYes
VP9YesYesYesYes
- -

[1] Firefox support for AV1 was added to macOS in Firefox 66; for Windows in Firefox 67; and Firefox 68 on Linux. Firefox for Android does not yet support AV1; the implementation in Firefox is designed to use a secure process, which is not supported yet in Android.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Audio codecs supported by WebM
CodecBrowser support
ChromeEdgeFirefoxSafari
OpusYesYesYesYes
VorbisYesYesYesYes
- -

Choosing the right container

- -

There are a few factors to consider when selecting the best container or containers to use for your media. The relative importance of each will depend on your needs, your license requirements, and the compatibility requirements of your target audience.

- -

Guidelines

- -

The best choice also depends on what you'll be doing with the media. Playing back media is a different thing than recording and/or editing it. If you're going to be manipulating the media data, using an uncompressed format can improve performance, while using a lossless compressed format at least prevent the accumulation of noise as compression artifacts are multiplied with each re-compression that occurs.

- - - -

Unfortunately, neither of the relatively major lossless compression formats (FLAC and ALAC) are universally supported. FLAC is the more broadly supported of the two, but is not supported by macOS without additional software installed, and is not supported at all on iOS. If you need to offer lossless audio, you may need to provide both FLAC and ALAC to get close to universal compatibility.

- -

Container selection advice

- -

The tables below offer suggested containers to use in various scenarios. These are just suggestions. Be sure to consider the needs of your application and your organization before selecting a container format.

- -

Audio-only files

- - - - - - - - - - - - - - - - - - - - - - -
If you need...Consider using this container format
Compressed files for general-purpose playbackMP3 (MPEG-1 Audio Layer III)
Losslessly compressed filesFLAC with ALAC fallback
Uncompressed filesWAV
- -

Now that MP3's patents have all expired, the choice of audio file format has become much easier to make. It's no longer necessary to choose between MP3's broad compatibility and the need to pay royalties when using it.

- -

Video files

- - - - - - - - - - - - - - - - - - - - - - - - -
If you need...Consider using this container format
General purpose video, preferably in an open formatWebM (ideally with MP4 fallback)
General purpose videoMP4 (ideally with WebM or Ogg fallback)
High compression optimized for slow connections3GP (ideally with MP4 fallback)
Compatibility with older devices/browsersQuickTime (ideally with AVI and/or MPEG-2 fallback)
- -

These suggestions make a number of assumptions. You should carefully consider the options before making a final decision, especially if you have a lot of media that will need to be encoded.

- -

Maximizing compatibility with multiple containers

- -

To optimize compatibility, it's worth considering providing more than one version of media files, using the {{HTMLElement("source")}} element to specify each source within the {{HTMLElement("audio")}} or {{HTMLElement("video")}} element. For example, you can offer an Ogg or WebM video as the first choice, with a fallback in MP4 format. You could even choose to offer a retro-like QuickTime or AVI fallback for good measure.

- -

To do this, you create a <video> (or <audio>) element with no {{htmlattrxref("src", "video")}} attribute. Then add child {{HTMLElement("source")}} elements within the <video> element, one for each version of the video you offer. This can be used to offer various versions of a video that can be selected depending on bandwidth availability, but in our case, we'll use it to offer format options.

- -

In the example shown here, a video is offered to the browser in two formats: WebM and MP4.

- -
{{EmbedInteractiveExample("pages/tabbed/source.html", "tabbed-standard")}}
- - - -

The video is offered first in WebM format (with the {{htmlattrxref("type", "video")}} attribute set to video/webm). If the {{Glossary("user agent")}} can't play that, it moves on to the next option, whose type is specified as video/mp4. If neither of those can be played, the text "This browser does not support the HTML5 video element." is presented.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationComment
ETSI 3GPPDefines the 3GP container format
ISO/IEC 14496-3 (MPEG-4 Part 3 Audio)Defines MP4 audio including ADTS
FLAC FormatThe FLAC format specification
ISO/IEC 11172-1 (MPEG-1 Part 1 Systems)Defines the MPEG-1 container format
ISO/IEC 13818-1 (MPEG-2 Part 1 Systems)Defines the MPEG-2 container format
ISO/IEC 14496-14 (MPEG-4 Part 14: MP4 file format)Defines the MPEG-4 (MP4) version 2 container format
ISO/IEC 14496-1 (MPEG-4 Part 1 Systems)Defines the original MPEG-4 (MP4) container format
{{RFC(3533)}}Defines the Ogg container format
{{RFC(5334)}}Defines the Ogg media types and file extensions
QuickTime File Format SpecificationDefines the QuickTime movie (MOV) format
Multimedia Programming Interface and Data Specifications 1.0The closest thing to an official WAVE specification
Resource Interchange File Format (used by WAV)Defines the RIFF format; WAVE files are a form of RIFF
WebM Container GuidelinesGuide for adapting Matroska for WebM
Matroska SpecificationsThe specification for the Matroska container format upon which WebM is based
WebM Byte Stream FormatWebM byte stream format for use with Media Source Extensions
- -

Browser compatibility

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Container format nameAudioVideo
MIME typeExtension(s)Browser supportMIME typeExtension(s)Browser support
3GPaudio/3gpp.3gpFirefoxvideo/3gpp.3gpFirefox
ADTS (Audio Data Transport Stream)audio/aac.aacFirefox
FLACaudio/flac.flacFirefox
MPEG-1 / MPEG-2 (MPG or MPEG)audio/mpeg.mpg
- .mpeg
Firefoxvideo/mpeg.mpg
- .mpeg
Firefox
audio/mp3.mp3Firefox
MPEG-4 (MP4)audio/mp4.mp4
- .m4a
Firefoxvideo/mp4.mp4
- .m4v
- .m4p
Firefox
Oggaudio/ogg.oga
- .ogg
Firefoxvideo/ogg.ogv
- .ogg
Firefox
QuickTime Movie (MOV)video/quicktime.movSafari
WAV (Waveform Audiofile)audio/wav.wavFirefox
WebMaudio/webm.webmFirefoxvideo/webm.webmFirefox
- -

 See also

- - diff --git a/files/es/web/performance/how_browsers_work/index.html b/files/es/web/performance/how_browsers_work/index.html deleted file mode 100644 index 95677a1f2d..0000000000 --- a/files/es/web/performance/how_browsers_work/index.html +++ /dev/null @@ -1,208 +0,0 @@ ---- -title: 'Populating the page: how browsers work' -slug: Web/Performance/How_browsers_work -tags: - - Composición - - Navegadorres - - Renderizado -translation_of: Web/Performance/How_browsers_work ---- -

Los usuarios quieren que las experiencias en la web sean rápidas y que tengan una intereacción sencilla. Por este motivo, los desarrolladores debén esforzarse para lograr estos dos objetivos

- -

Para entender como mejorar el desempeño, es importante entender como funciona el navegador.

- -

Overview

- -

Fast sites provide better user experiences. Users want and expect web experiences with content that is fast to load and smooth to interact with.

- -

Two major issues in web performance are understanding issues having to do with latency and issues having to do with the fact that for the most part, browsers are single threaded.

- -

Latency is our main threat to overcome to ensure a fast load. To be fast to load, the developers’ goals include sending requested information as fast as possible, or at least seem super fast. Network latency is the time it takes to transmit bytes over-the-air to computers. Web performance is what we have to do to make the page load happen as quickly as possible.

- -

For the most part, browsers are considered single threaded. For smooth interactions, the developer's goal is to ensure performant site interactions, from smooth scrolling to being responsive to touch. Render time is key, with ensuring the main thread can complete all the work we throw at it and still always be available to handle user interactions. Web performance can be improved by understanding the single-threaded nature of the browser and minimizing the main thread's responsibilities, where possible and appropriate, to ensure rendering is smooth and responses to interactions are immediate.

- - - -

Navigation is the first step in loading a web page. It occurs whenever a user requests a page by entering a URL into the address bar, clicking a link, submitting a form, as well as other actions.

- -

One of the goals of web performance is to minimize the amount of time a navigation takes to complete. In ideal conditions, this usually doesn't take too long, but latency and bandwidth are foes which can cause delays.

- -

DNS Lookup

- -

The first step of navigating to a web page is finding where the assets for that page are located. If you navigate to https://example.com, the HTML page is located on the server with IP address of 93.184.216.34. If you’ve never visited this site, a DNS lookup must happen.

- -

Your browser requests a DNS lookup, which is eventually fielded by a name server, which in turn responds with an IP address. After this initial request, the IP will likely be cached for a time, which speeds up subsequent requests by retrieving the IP address from the cache instead of contacting a name server again.

- -

DNS lookups usually only need to be done once per hostname for a page load. However, DNS lookups must be done for each unique hostname the requested page references. If your fonts, images, scripts, ads, and metrics all have different hostnames, a DNS lookup will have to be made for each one.

- -

Mobile requests go first to the cell tower, then to a central phone company computer before being sent to the internet

- -

This can be problematic for performance, particularly on mobile networks. When a user is on a mobile network, each DNS lookup has to go from the phone to the cell tower to reach an authoritative DNS server. The distance between a phone, a cell tower, and the name server can add significant latency.

- -

TCP Handshake

- -

Once the IP address is known, the browser sets up a connection to the server via a {{glossary('TCP handshake','TCP three-way handshake')}}. This mechanism is designed so that two entities attempting to communicate—in this case the browser and web server—can negotiate the parameters of the network TCP socket connection before transmitting data, often over {{glossary('HTTPS')}}.

- -

TCP's three way handshaking technique is often referred to as "SYN-SYN-ACK"—or more accurately SYN, SYN-ACK, ACK—because there are three messages transmitted by TCP to negotiate and start a TCP session between two computers. Yes, this means three more messages back and forth between each server, and the request has yet to be made.

- -

TLS Negotiation

- -

For secure connections established over HTTPS, another "handshake" is required. This handshake, or rather the {{glossary('TLS')}} negotiation, determines which cipher will be used to encrypt the communication, verifies the server, and establishes that a secure connection is in place before beginning the actual transfer of data. This requires three more round trips to the server before the request for content is actually sent.

- -

The DNS lookup, the TCP handshake, and 5 steps of the TLS handshake including clienthello, serverhello and certificate, clientkey and finished for both server and client.

- -

While making the connection secure adds time to the page load, a secure connection is worth the latency expense, as the data transmitted between the browser and the web server cannot be decrypted by a third party.

- -

After the 8 round trips, the browser is finally able to make the request.

- -

Response

- -

Once we have an established connection to a web server, the browser sends an initial HTTP GET request on behalf of the user, which for websites is most often an HTML file. Once the server receives the request, it will reply with relevant response headers and the contents of the HTML.

- -
<!doctype HTML>
-<html>
- <head>
-  <meta charset="UTF-8"/>
-  <title>My simple page</title>
-  <link rel="stylesheet" src="styles.css"/>
-  <script src="myscript.js"></script>
-</head>
-<body>
-  <h1 class="heading">My Page</h1>
-  <p>A paragraph with a <a href="https://example.com/about">link</a></p>
-  <div>
-    <img src="myimage.jpg" alt="image description"/>
-  </div>
-  <script src="anotherscript.js"></script>
-</body>
-</html>
- -

This response for this initial request contains the first byte of data received. {{glossary('Time to First Byte')}} (TTFB) is the time between when the user made the request—say by clicking on a link—and the receipt of this first packet of HTML. The first chunk of content is usually 14kb of data.

- -

In our example above, the request is definitely less than 14Kb, but the linked resources aren't requested until the browser encounters the links during parsing, described below.

- -

TCP Slow Start / 14kb rule

- -

The first response packet will be 14Kb. This is part of {{glossary('TCP slow start')}}, an algorithm which balances the speed of a network connection. Slow start gradually increases the amount of data transmitted until the network's maximum bandwidth can be determined.

- -

In {{glossary('TCP slow start')}}, after receipt of the initial packet, the server doubles the size of the next packet to around 28Kb. Subsequent packets increase in size until a predetermined threshold is reached, or congestion is experienced.

- -

TCP slow start

- -

If you’ve ever heard of the 14Kb rule for initial page load, TCP slow start is the reason why the initial response is 14Kb, and why web performance optimization calls for focusing optimizations with this initial 14Kb response in mind. TCP slow start gradually builds up transmission speeds appropriate for the network's capabilities to avoid congestion.

- -

Congestion control

- -

As the server sends data in TCP packets, the user's client confirms delivery by returning acknowledgements, or ACKs. The connection has a limited capacity depending on hardware and network conditions. If the server sends too many packets too quickly, they will be dropped. Meaning, there will be no acknowledgement. The server registers this as missing ACKs. Congestion control algorithms use this flow of sent packets and ACKs to determine a send rate.

- -

Parsing

- -

Once the browser receives the first chunk of data, it can begin parsing the information received. {{glossary('speculative parsing', 'Parsing')}} is the step the browser takes to turn the data it receives over the network into the {{glossary('DOM')}} and {{glossary('CSSOM')}}, which is used by the renderer to paint a page to the screen.

- -

The DOM is the internal representation of the markup for the browser. The DOM is also exposed, and can be manipulated through various APIs in JavaScript.

- -

Even if the request page's HTML is larger than the initial 14KB packet, the browser will begin parsing and attempting to render an experience based on the data it has. This is why it's important for web performance optimization to include everything the browser needs to start rendering a page, or at least a template of the page - the CSS and HTML needed for the first render -- in the first 14 kilobytes. But before anything is rendered to the screen, the HTML, CSS, and JavaScript have to be parsed.

- -

Building the DOM tree

- -

We describe five steps in the critical rendering path.

- -

The first step is processing the HTML markup and building the DOM tree. HTML parsing involves tokenization and tree construction. HTML tokens include start and end tags, as well as attribute names and values. If the document is well-formed, parsing it is straightforward and faster. The parser parses tokenized input into the document, building up the document tree.

- -

The DOM tree describes the content of the document. The <html> element is the first tag and root node of the document tree. The tree reflects the relationships and hierarchies between different tags. Tags nested within other tags are child nodes. The greater the number of DOM nodes, the longer it takes to construct the DOM tree.

- -

The DOM tree for our sample code, showing all the nodes, including text nodes.

- -

When the parser finds non-blocking resources, such as an image, the browser will request those resources and continue parsing. Parsing can continue when a CSS file is encountered, but <script> tags—particularly those without an async or defer attribute—block rendering, and pause the parsing of HTML. Though the browser's preload scanner hastens this process, excessive scripts can still be a significant bottleneck.

- -

Preload scanner

- -

While the browser builds the DOM tree, this process occupies the main thread. As this happens, the preload scanner will parse through the content available and request high priority resources like CSS, JavaScript, and web fonts. Thanks to the preload scanner, we don't have to wait until the parser finds a reference to an external resource to request it. It will retrieve resources in the background so that by the time the main HTML parser reaches requested assets, they may possibly already be in flight, or have been downloaded. The optimizations the preload scanner provides reduce blockages.

- -
<link rel="stylesheet" src="styles.css"/>
-<script src="myscript.js" async></script>
-<img src="myimage.jpg" alt="image description"/>
-<script src="anotherscript.js" async></script>
-
- -

In this example, while the main thread is parsing the HTML and CSS, the preload scanner will find the scripts and image, and start downloading them as well. To ensure the script doesn't block the process, add the async attribute, or the defer attribute if JavaScript parsing and execution order is not important.

- -

Waiting to obtain CSS doesn't block HTML parsing or downloading, but it does block JavaScript, because JavaScript is often used to query CSS properties’ impact on elements.

- -

Building the CSSOM

- -

The second step in the critical rendering path is processing CSS and building the CSSOM tree. The CSS object model is similar to the DOM. The DOM and CSSOM are both trees. They are independent data structures. The browser converts the CSS rules into a map of styles it can understand and work with. The browser goes through each rule set in the CSS, creating a tree of nodes with parent, child, and sibling relationships based on the CSS selectors.

- -

As with HTML, the browser needs to convert the received CSS rules into something it can work with. Hence, it repeats the HTML-to-object process, but for the CSS.

- -

The CSSOM tree includes styles from the user agent style sheet. The browser begins with the most general rule applicable to a node and recursively refines the computed styles by applying more specific rules. In other words, it cascades the property values.

- -

Building the CSSOM is very, very fast and is not displayed in a unique color in current developer tools. Rather, the "Recalculate Style" in developer tools shows the total time it takes to parse CSS, construct the CSSOM tree, and recursively calculate computed styles. In terms of web performance optimization, there are lower hanging fruit, as the total time to create the CSSOM is generally less than the time it takes for one DNS lookup.

- -

Other Processes

- -

JavaScript Compilation

- -

While the CSS is being parsed and the CSSOM created, other assets, including JavaScript files, are downloading (thanks to the preload scanner). JavaScript is interpreted, compiled, parsed and executed. The scripts are parsed into abstract syntax trees. Some browser engines take the {{glossary('Abstract Syntax Tree')}} and pass it into an interpreter, outputting bytecode which is executed on the main thread. This is known as JavaScript compilation.

- -

Building the Accessibility Tree

- -

The browser also builds an accessibility tree that assistive devices use to parse and interpret content. The accessibility object model (AOM) is like a semantic version of the DOM. The browser updates the accessibility tree when the DOM is updated. The accessibility tree is not modifiable by assistive technologies themselves.

- -

Until the AOM is built, the content is not accessible to screen readers.

- -

Render

- -

Rendering steps include style, layout, paint and, in some cases, compositing. The CSSOM and DOM trees created in the parsing step are combined into a render tree which is then used to compute the layout of every visible element, which is then painted to the screen. In some cases, content can be promoted to their own layers and composited, improving performance by painting portions of the screen on the GPU instead of the CPU, freeing up the main thread.

- -

Style

- -

The third step in the critical rendering path is combining the DOM and CSSOM into a render tree.The computed style tree, or render tree, construction starts with the root of the DOM tree, traversing each visible node.

- -

Tags that aren't going to be displayed, like the <head> and its children and any nodes with display: none, such as the script { display: none; } you will find in user agent stylesheets, are not included in the render tree as they will not appear in the rendered output. Nodes with visibility: hidden applied are included in the render tree, as they do take up space. As we have not given any directives to override the user agent default, the script node in our code example above will not be included in the render tree.

- -

Each visible node has its CSSOM rules applied to it. The render tree holds all the visible nodes with content and computed styles -- matching up all the relevant styles to every visible node in the DOM tree, and determining, based on the CSS cascade, what the computed styles are for each node.

- -

Layout

- -

The fourth step in the critical rending path is running layout on the render tree to compute the geometry of each node. Layout is the process by which the width, height, and location of all the nodes in the render tree are determined, plus the determination of the size and position of each object on the page. Reflow is any subsequent size and position determination of any part of the page or the entire document.

- -

Once the render tree is built, layout commences. The render tree identified which nodes are displayed (even if invisible) along with their computed styles, but not the dimensions or location of each node. To determine the exact size and location of each object, the browser starts at the root of the render tree and traverses it.

- -

On the web page, most everything is a box. Different devices and different desktop preferences mean an unlimited number of differing viewport sizes. In this phase, taking the viewport size into consideration, the browser determines what the dimensions of all the different boxes are going to be on the screen. Taking the size of the viewport as its base, layout generally starts with the body, laying out the dimensions of all the body’s descendants, with each element's box model properties, providing placeholder space for replaced elements it doesn’t know the dimensions of, such as our image.

- -

The first time the size and position of nodes are determined is called layout. Subsequent recalculations of node size and locations are called reflows.  In our example, suppose the initial layout occurs before the image is returned. Since we didn't declare the size of our image, there will be a reflow once the image size is known.

- -

Paint

- -

The last step in the critical rendering path is painting the individual nodes to the screen, the first occurence of which is called the first meaningful paint. In the painting or rasterization phase, the browser converts each box calculated in the layout phase to actual pixels on the screen. Painting involves drawing every visual part of an element to the screen, including text, colors, borders, shadows, and replaced elements like buttons and images. The browser needs to do this super quickly.

- -

To ensure smooth scrolling and animation, everything occupying the main thread, including calculating styles, along with reflow and paint, must take the browser less than 16.67ms to accomplish. At 2048 X 1536, the iPad has over 3,145,000 pixels to be painted to the screen. That is a lot of pixels that have to be painted very quickly. To ensure repainting can be done even faster than the initial paint, the drawing to the screen is generally broken down into several layers. If this occurs, then compositing is necessary.

- -

Painting can break the elements in the layout tree into layers. Promoting content into layers on the GPU (instead of the main thread on the CPU) improves paint and repaint performance. There are specific properties and elements that instantiate a layer, including <video> and <canvas>, and any element which has the CSS properties of opacity, a 3D transform, will-change, and a few others. These nodes will be painted onto their own layer, along with their descendants, unless a descendant necessitates its own layer for one (or more) of the above reasons.

- -

Layers do improve performance, but are expensive when it comes to memory management, so should not be overused as part of web performance optimization strategies.

- -

Compositing

- -

When sections of the document are drawn in different layers, overlapping each other, compositing is necessary to ensure they are drawn to the screen in the right order and the content is rendered correctly.

- -

As the page continues to load assets, reflows can happen (recall our example image that arrived late).  A reflow sparks a repaint and a re-composite. Had we defined the size of our image, no reflow would have been necessary, and only the layer that needed to be repainted would be repainted, and composited if necessary. But we didn't include the image size! When the image is obtained from the server, the rendering process goes back to the layout steps and restarts from there.

- -

Interactivity

- -

Once the main thread is done painting the page, you would think we would be "all set." That isn't necessarily the case. If the load includes JavaScript, that was correctly deferred, and only executed after the onload event fires, the main thread might be busy, and not available for scrolling, touch, and other interactions.

- -

{{glossary('Time to Interactive')}} (TTI) is the measurement of how long it took from that first request which led to the DNS lookup and SSL connection to when the page is interactive -- interactive being the point in time after the {{glossary('First Contentful Paint')}} when the page responds to user interactions within 50ms. If the main thread is occupied parsing, compiling, and executing JavaScript, it is not available and therefore not able to responsd to user interactions in a timely (less than 50ms) fashion.

- -

In our example, maybe the image loaded quickly, but perhaps the anotherscript.js file was 2MB and our user's network connection was slow.  In this case the user would see the page super quickly, but wouldn't be able to scroll without jank until the script was downloaded, parsed and executed. That is not a good user experience. Avoid occupying the main thread, as demonstrated in this WebPageTest example:

- -

The main thread is occupied by the downloading, parsing and execution of a  javascript file - over a fast connection

- -

In this example, the DOM content load process took over 1.5 seconds, and the main thread was fully occupied that entire time, unresponsive to click events or screen taps.

- -

See Also

- - diff --git a/files/es/web/svg/tutorial/svg_in_html_introduction/index.html b/files/es/web/svg/tutorial/svg_in_html_introduction/index.html deleted file mode 100644 index ff4bede205..0000000000 --- a/files/es/web/svg/tutorial/svg_in_html_introduction/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: SVG In HTML Introduction -slug: Web/SVG/Tutorial/SVG_In_HTML_Introduction -translation_of: Web/SVG/Tutorial/SVG_In_HTML_Introduction ---- -

Overview

- -

This article and its associated example shows how to use inline SVG to provide a background picture for a form. It shows how JavaScript and CSS can be used to manipulate the picture in the same way you would script regular XHTML. Note that the example will only work in browsers that support XHTML (not HTML) and SVG integration.

- -

Source

- -

Here is the source to the example:

- -
<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<title>XTech SVG Demo</title>
-<style>
-  stop.begin { stop-color:yellow; }
-  stop.end { stop-color:green; }
-  body.invalid stop.end { stop-color:red; }
-  #err { display:none; }
-  body.invalid #err { display:inline; }
-</style>
-<script>
-  function signalError() {
-    document.getElementById('body').setAttribute("class", "invalid");
-  }
-</script>
-</head>
-<body id="body"
-  style="position:absolute; z-index:0; border:1px solid black; left:5%; top:5%; width:90%; height:90%;">
-<form>
-  <fieldset>
-    <legend>HTML Form</legend>
-    <p><label>Enter something:</label>
-    <input type="text"/>
-    <span id="err">Incorrect value!</span></p>
-    <p><input type="button" value="Activate!" onclick="signalError();" /></p>
-  </fieldset>
-</form>
-
-<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
-  viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice"
-  style="width:100%; height:100%; position:absolute; top:0; left:0; z-index:-1;">
-  <linearGradient id="gradient">
-    <stop class="begin" offset="0%"/>
-    <stop class="end" offset="100%"/>
-  </linearGradient>
-  <rect x="0" y="0" width="100" height="100" style="fill:url(#gradient)" />
-  <circle cx="50" cy="50" r="30" style="fill:url(#gradient)" />
-</svg>
-</body>
-</html>
-
- -

Discussion

- -

The page is mainly regular XHTML, CSS and JavaScript. The only interesting part is the <svg> element it contains. This element and its children are declared to be in the SVG namespace. The element contains a gradient and two shapes filled with the gradient. The gradient color stops have their colors set by CSS. When the user enters something incorrect into the form, the script sets the invalid attribute on the <body>, and a style rule changes the gradient end-stop color to red. (Another style rule makes an error message appear.)

- -

This approach has the following points in its favor:

- - - -
-

To add a linked image with DOM methods to an embedded SVG element, one has to use setAttributeNS to set href. Like in the following example:

- -
 var img = document.createElementNS("http://www.w3.org/2000/svg", "image");
-img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "move.png");
-
-
-
-
- -

Details

- -

The viewBox attribute establishes a logical coordinate system which the SVG picture's coordinates are relative to. In this case our picture is laid out in a 100 by 100 viewport.

- -

The preserveAspectRatio attribute specifies that the aspect ratio must be preserved by centering the picture in the available size, sizing to the maximum of the height or width and then cutting off any overflow.

- -

The style attribute pins the SVG element to the background of the form.

- - - - -- cgit v1.2.3-54-g00ecf