From 4f0e1ec1c2772904c033f747dc38a08223e8d661 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Thu, 15 Jul 2021 13:42:10 -0400 Subject: delete pages that were never translated from en-US (es, part 2) (#1550) --- files/es/_redirects.txt | 21 - files/es/_wikihistory.json | 289 --- files/es/games/anatomy/index.html | 325 ---- .../index.html | 2004 -------------------- .../javascript/asynchronous/async_await/index.html | 411 ---- .../javascript/building_blocks/events/index.html | 579 ------ .../building_blocks/functions/index.html | 400 ---- .../building_blocks/image_gallery/index.html | 145 -- .../django/django_assessment_blog/index.html | 307 --- .../django/web_application_security/index.html | 176 -- files/es/mozilla/firefox/releases/19/index.html | 67 - files/es/mozilla/firefox/releases/63/index.html | 274 --- files/es/tools/3d_view/index.html | 82 - .../debugger/how_to/set_a_breakpoint/index.html | 44 - .../how_to/work_with_animations/index.html | 112 -- files/es/tools/settings/index.html | 206 -- files/es/web/api/audionode/index.html | 154 -- .../hit_regions_and_accessibility/index.html | 100 - files/es/web/api/filesystem/index.html | 118 -- files/es/web/api/headers/index.html | 135 -- .../recommended_drag_types/index.html | 145 -- .../es/web/api/htmlcanvaselement/toblob/index.html | 261 --- files/es/web/api/mediasource/index.html | 182 -- files/es/web/api/webvtt_api/index.html | 903 --------- .../api/window/domcontentloaded_event/index.html | 149 -- files/es/web/api/worker/postmessage/index.html | 206 -- .../index.html | 232 --- files/es/web/css/@document/index.html | 82 - files/es/web/css/background-position-x/index.html | 126 -- files/es/web/css/border-radius/index.html | 320 ---- files/es/web/css/cascade/index.html | 202 -- files/es/web/css/clip-path/index.html | 179 -- .../media_queries/testing_media_queries/index.html | 94 - .../es/web/html/attributes/autocomplete/index.html | 181 -- files/es/web/html/element/shadow/index.html | 153 -- .../global_objects/encodeuricomponent/index.html | 162 -- .../reference/statements/with/index.html | 167 -- files/es/web/mathml/authoring/index.html | 415 ---- files/es/web/mathml/authoring/openoffice.png | Bin 12489 -> 0 bytes files/es/web/media/formats/index.html | 88 - files/es/web/svg/element/foreignobject/index.html | 133 -- files/es/web/xslt/element/number/index.html | 170 -- 42 files changed, 10499 deletions(-) delete mode 100644 files/es/games/anatomy/index.html delete mode 100644 files/es/learn/forms/property_compatibility_table_for_form_controls/index.html delete mode 100644 files/es/learn/javascript/asynchronous/async_await/index.html delete mode 100644 files/es/learn/javascript/building_blocks/events/index.html delete mode 100644 files/es/learn/javascript/building_blocks/functions/index.html delete mode 100644 files/es/learn/javascript/building_blocks/image_gallery/index.html delete mode 100644 files/es/learn/server-side/django/django_assessment_blog/index.html delete mode 100644 files/es/learn/server-side/django/web_application_security/index.html delete mode 100644 files/es/mozilla/firefox/releases/19/index.html delete mode 100644 files/es/mozilla/firefox/releases/63/index.html delete mode 100644 files/es/tools/3d_view/index.html delete mode 100644 files/es/tools/debugger/how_to/set_a_breakpoint/index.html delete mode 100644 files/es/tools/page_inspector/how_to/work_with_animations/index.html delete mode 100644 files/es/tools/settings/index.html delete mode 100644 files/es/web/api/audionode/index.html delete mode 100644 files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html delete mode 100644 files/es/web/api/filesystem/index.html delete mode 100644 files/es/web/api/headers/index.html delete mode 100644 files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html delete mode 100644 files/es/web/api/htmlcanvaselement/toblob/index.html delete mode 100644 files/es/web/api/mediasource/index.html delete mode 100644 files/es/web/api/webvtt_api/index.html delete mode 100644 files/es/web/api/window/domcontentloaded_event/index.html delete mode 100644 files/es/web/api/worker/postmessage/index.html delete mode 100644 files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html delete mode 100644 files/es/web/css/@document/index.html delete mode 100644 files/es/web/css/background-position-x/index.html delete mode 100644 files/es/web/css/border-radius/index.html delete mode 100644 files/es/web/css/cascade/index.html delete mode 100644 files/es/web/css/clip-path/index.html delete mode 100644 files/es/web/css/media_queries/testing_media_queries/index.html delete mode 100644 files/es/web/html/attributes/autocomplete/index.html delete mode 100644 files/es/web/html/element/shadow/index.html delete mode 100644 files/es/web/javascript/reference/global_objects/encodeuricomponent/index.html delete mode 100644 files/es/web/javascript/reference/statements/with/index.html delete mode 100644 files/es/web/mathml/authoring/index.html delete mode 100644 files/es/web/mathml/authoring/openoffice.png delete mode 100644 files/es/web/media/formats/index.html delete mode 100644 files/es/web/svg/element/foreignobject/index.html delete mode 100644 files/es/web/xslt/element/number/index.html (limited to 'files/es') diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index 8783b96121..90b0245be0 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -73,7 +73,6 @@ /es/docs/CSS/border-image /es/docs/Web/CSS/border-image /es/docs/CSS/border-left /es/docs/Web/CSS/border-left /es/docs/CSS/border-left-color /es/docs/Web/CSS/border-left-color -/es/docs/CSS/border-radius /es/docs/Web/CSS/border-radius /es/docs/CSS/border-spacing /es/docs/Web/CSS/border-spacing /es/docs/CSS/border-style /es/docs/Web/CSS/border-style /es/docs/CSS/border-width /es/docs/Web/CSS/border-width @@ -401,7 +400,6 @@ /es/docs/Dibujar_texto_usando_canvas /es/docs/Web/API/Canvas_API/Tutorial/Drawing_text /es/docs/DragDrop/Drag_and_Drop /es/docs/Web/API/HTML_Drag_and_Drop_API /es/docs/DragDrop/Drag_and_Drop/drag_and_drop_archivo /es/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop -/es/docs/DragDrop/Recommended_Drag_Types /es/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types /es/docs/Drawing_text_using_a_canvas /es/docs/Web/API/Canvas_API/Tutorial/Drawing_text /es/docs/EXSLT /es/docs/Web/EXSLT /es/docs/EXSLT/exsl /es/docs/Web/EXSLT/exsl @@ -465,7 +463,6 @@ /es/docs/FUEL:Window /es/docs/FUEL/Window /es/docs/Firefox_1.5 /es/docs/Mozilla/Firefox/Releases/1.5 /es/docs/Firefox_1.5_para_Desarrolladores /es/docs/Mozilla/Firefox/Releases/1.5 -/es/docs/Firefox_19_para_desarrolladores /es/docs/Mozilla/Firefox/Releases/19 /es/docs/Firefox_2 /es/docs/Mozilla/Firefox/Releases/2 /es/docs/Firefox_2_para_desarrolladores /es/docs/Mozilla/Firefox/Releases/2 /es/docs/Firefox_3.1_para_desarrolladores /es/docs/Mozilla/Firefox/Releases/3.5 @@ -1026,7 +1023,6 @@ /es/docs/JavaScript/Referencia/Funciones_globales/decodeURI /es/docs/Web/JavaScript/Reference/Global_Objects/decodeURI /es/docs/JavaScript/Referencia/Funciones_globales/decodeURIComponent /es/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent /es/docs/JavaScript/Referencia/Funciones_globales/encodeURI /es/docs/Web/JavaScript/Reference/Global_Objects/encodeURI -/es/docs/JavaScript/Referencia/Funciones_globales/encodeURIComponent /es/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent /es/docs/JavaScript/Referencia/Funciones_globales/eval /es/docs/Web/JavaScript/Reference/Global_Objects/eval /es/docs/JavaScript/Referencia/Funciones_globales/isFinite /es/docs/Web/JavaScript/Reference/Global_Objects/isFinite /es/docs/JavaScript/Referencia/Funciones_globales/isNaN /es/docs/Web/JavaScript/Reference/Global_Objects/isNaN @@ -1202,7 +1198,6 @@ /es/docs/Learn/Getting_started_with_the_web/Manejando_los_archivos /es/docs/Learn/Getting_started_with_the_web/Dealing_with_files /es/docs/Learn/HTML/Forms/How_to_structure_an_HTML_form /es/docs/Learn/Forms/How_to_structure_a_web_form /es/docs/Learn/HTML/Forms/My_first_HTML_form /es/docs/Learn/Forms/Your_first_form -/es/docs/Learn/HTML/Forms/Property_compatibility_table_for_form_controls /es/docs/Learn/Forms/Property_compatibility_table_for_form_controls /es/docs/Learn/HTML/Forms/Prueba_tus_habilidades:_Otros_controles /es/docs/Learn/Forms/Test_your_skills:_Other_controls /es/docs/Learn/HTML/Forms/Prueba_tus_habilidades:_controles_HTML5 /es/docs/Learn/Forms/Test_your_skills:_HTML5_controls /es/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data /es/docs/Learn/Forms/Sending_and_retrieving_form_data @@ -1239,8 +1234,6 @@ /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 -/es/docs/Learn/JavaScript/Building_blocks/Eventos /es/docs/Learn/JavaScript/Building_blocks/Events -/es/docs/Learn/JavaScript/Building_blocks/Galeria_de_imagenes /es/docs/Learn/JavaScript/Building_blocks/Image_gallery /es/docs/Learn/JavaScript/Client-side_web_APIs/Introducción /es/docs/Learn/JavaScript/Client-side_web_APIs/Introduction /es/docs/Learn/JavaScript/First_steps/Generador_de_historias_absurdas /es/docs/Learn/JavaScript/First_steps/Silly_story_generator /es/docs/Learn/JavaScript/First_steps/Matemáticas /es/docs/Learn/JavaScript/First_steps/Math @@ -1330,7 +1323,6 @@ /es/docs/Referencia_de_JavaScript_1.5/Funciones_globales/decodeURI /es/docs/Web/JavaScript/Reference/Global_Objects/decodeURI /es/docs/Referencia_de_JavaScript_1.5/Funciones_globales/decodeURIComponent /es/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent /es/docs/Referencia_de_JavaScript_1.5/Funciones_globales/encodeURI /es/docs/Web/JavaScript/Reference/Global_Objects/encodeURI -/es/docs/Referencia_de_JavaScript_1.5/Funciones_globales/encodeURIComponent /es/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent /es/docs/Referencia_de_JavaScript_1.5/Funciones_globales/eval /es/docs/Web/JavaScript/Reference/Global_Objects/eval /es/docs/Referencia_de_JavaScript_1.5/Funciones_globales/isFinite /es/docs/Web/JavaScript/Reference/Global_Objects/isFinite /es/docs/Referencia_de_JavaScript_1.5/Funciones_globales/isNaN /es/docs/Web/JavaScript/Reference/Global_Objects/isNaN @@ -1459,7 +1451,6 @@ /es/docs/Referencia_de_JavaScript_1.5:Funciones_globales:decodeURI /es/docs/Web/JavaScript/Reference/Global_Objects/decodeURI /es/docs/Referencia_de_JavaScript_1.5:Funciones_globales:decodeURIComponent /es/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent /es/docs/Referencia_de_JavaScript_1.5:Funciones_globales:encodeURI /es/docs/Web/JavaScript/Reference/Global_Objects/encodeURI -/es/docs/Referencia_de_JavaScript_1.5:Funciones_globales:encodeURIComponent /es/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent /es/docs/Referencia_de_JavaScript_1.5:Funciones_globales:eval /es/docs/Web/JavaScript/Reference/Global_Objects/eval /es/docs/Referencia_de_JavaScript_1.5:Funciones_globales:isFinite /es/docs/Web/JavaScript/Reference/Global_Objects/isFinite /es/docs/Referencia_de_JavaScript_1.5:Funciones_globales:isNaN /es/docs/Web/JavaScript/Reference/Global_Objects/isNaN @@ -1791,7 +1782,6 @@ /es/docs/Web/CSS/transform-function/translateY /es/docs/Web/CSS/transform-function/translateY() /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/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 @@ -1816,14 +1806,12 @@ /es/docs/Web/Guide/AJAX/Primeros_Pasos /es/docs/Web/Guide/AJAX/Getting_Started /es/docs/Web/Guide/API/Vibration /es/docs/Web/API/Vibration_API /es/docs/Web/Guide/CSS /es/docs/Learn/CSS -/es/docs/Web/Guide/CSS/probando_media_queries /es/docs/Web/CSS/Media_Queries/Testing_media_queries /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/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 -/es/docs/Web/Guide/HTML/Canvas_tutorial/Hit_regions_and_accessibility /es/docs/Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility /es/docs/Web/Guide/HTML/Canvas_tutorial/Optimizing_canvas /es/docs/Web/API/Canvas_API/Tutorial/Optimizing_canvas /es/docs/Web/Guide/HTML/Canvas_tutorial/Pixel_manipulation_with_canvas /es/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas /es/docs/Web/Guide/HTML/Forms/How_to_structure_an_HTML_form /es/docs/Learn/Forms/How_to_structure_a_web_form @@ -1837,7 +1825,6 @@ /es/docs/Web/Guide/Usando_Objetos_FormData /es/docs/Web/API/FormData/Using_FormData_Objects /es/docs/Web/HTML/Atributos /es/docs/Web/HTML/Attributes /es/docs/Web/HTML/Atributos/accept /es/docs/Web/HTML/Attributes/accept -/es/docs/Web/HTML/Atributos/autocomplete /es/docs/Web/HTML/Attributes/autocomplete /es/docs/Web/HTML/Atributos/min /es/docs/Web/HTML/Attributes/min /es/docs/Web/HTML/Atributos/minlength /es/docs/Web/HTML/Attributes/minlength /es/docs/Web/HTML/Atributos/multiple /es/docs/Web/HTML/Attributes/multiple @@ -1873,7 +1860,6 @@ /es/docs/Web/HTML/Elemento/Audio2 /es/docs/Web/HTML/Element/audio /es/docs/Web/HTML/Elemento/Elementos_títulos /es/docs/Web/HTML/Element/Heading_Elements /es/docs/Web/HTML/Elemento/Progreso /es/docs/Web/HTML/Element/progress -/es/docs/Web/HTML/Elemento/Shadow /es/docs/Web/HTML/Element/shadow /es/docs/Web/HTML/Elemento/a /es/docs/Web/HTML/Element/a /es/docs/Web/HTML/Elemento/abbr /es/docs/Web/HTML/Element/abbr /es/docs/Web/HTML/Elemento/acronym /es/docs/Web/HTML/Element/acronym @@ -2173,7 +2159,6 @@ /es/docs/Web/JavaScript/Referencia/Funciones_globales/decodeURI /es/docs/Web/JavaScript/Reference/Global_Objects/decodeURI /es/docs/Web/JavaScript/Referencia/Funciones_globales/decodeURIComponent /es/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent /es/docs/Web/JavaScript/Referencia/Funciones_globales/encodeURI /es/docs/Web/JavaScript/Reference/Global_Objects/encodeURI -/es/docs/Web/JavaScript/Referencia/Funciones_globales/encodeURIComponent /es/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent /es/docs/Web/JavaScript/Referencia/Funciones_globales/isFinite /es/docs/Web/JavaScript/Reference/Global_Objects/isFinite /es/docs/Web/JavaScript/Referencia/Funciones_globales/isNaN /es/docs/Web/JavaScript/Reference/Global_Objects/isNaN /es/docs/Web/JavaScript/Referencia/Funciones_globales/parseInt /es/docs/Web/JavaScript/Reference/Global_Objects/parseInt @@ -2480,7 +2465,6 @@ /es/docs/Web/JavaScript/Referencia/Objetos_globales/decodeURI /es/docs/Web/JavaScript/Reference/Global_Objects/decodeURI /es/docs/Web/JavaScript/Referencia/Objetos_globales/decodeURIComponent /es/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent /es/docs/Web/JavaScript/Referencia/Objetos_globales/encodeURI /es/docs/Web/JavaScript/Reference/Global_Objects/encodeURI -/es/docs/Web/JavaScript/Referencia/Objetos_globales/encodeURIComponent /es/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent /es/docs/Web/JavaScript/Referencia/Objetos_globales/escape /es/docs/Web/JavaScript/Reference/Global_Objects/escape /es/docs/Web/JavaScript/Referencia/Objetos_globales/eval /es/docs/Web/JavaScript/Reference/Global_Objects/eval /es/docs/Web/JavaScript/Referencia/Objetos_globales/isFinite /es/docs/Web/JavaScript/Reference/Global_Objects/isFinite @@ -2563,7 +2547,6 @@ /es/docs/Web/JavaScript/Referencia/Sentencias/try...catch /es/docs/Web/JavaScript/Reference/Statements/try...catch /es/docs/Web/JavaScript/Referencia/Sentencias/var /es/docs/Web/JavaScript/Reference/Statements/var /es/docs/Web/JavaScript/Referencia/Sentencias/while /es/docs/Web/JavaScript/Reference/Statements/while -/es/docs/Web/JavaScript/Referencia/Sentencias/with /es/docs/Web/JavaScript/Reference/Statements/with /es/docs/Web/JavaScript/Referencia/template_strings /es/docs/Web/JavaScript/Reference/Template_literals /es/docs/Web/JavaScript/Una_nueva_introducción_a_JavaScript /es/docs/Web/JavaScript/A_re-introduction_to_JavaScript /es/docs/Web/JavaScript/Una_re-introducción_a_JavaScript /es/docs/Web/JavaScript/A_re-introduction_to_JavaScript @@ -2574,7 +2557,6 @@ /es/docs/Web/Performance/mejorando_rendimienot_inicial /es/docs/Web/Performance/Optimizing_startup_performance /es/docs/Web/Progressive_web_apps/Developer_guide/Instalar /es/docs/Web/Progressive_web_apps/Developer_guide/Installing /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/animationend /es/docs/Web/API/HTMLElement/animationend_event /es/docs/Web/Reference/Events/beforeunload /es/docs/Web/API/Window/beforeunload_event @@ -2641,7 +2623,6 @@ /es/docs/Web/XSLT/key /es/docs/Web/XSLT/Element/key /es/docs/Web/XSLT/message /es/docs/Web/XSLT/Element/message /es/docs/Web/XSLT/namespace-alias /es/docs/Web/XSLT/Element/namespace-alias -/es/docs/Web/XSLT/number /es/docs/Web/XSLT/Element/number /es/docs/Web/XSLT/otherwise /es/docs/Web/XSLT/Element/otherwise /es/docs/Web/XSLT/when /es/docs/Web/XSLT/Element/when /es/docs/Web/XSLT/with-param /es/docs/Web/XSLT/Element/with-param @@ -2724,7 +2705,6 @@ /es/docs/XSLT/key /es/docs/Web/XSLT/Element/key /es/docs/XSLT/message /es/docs/Web/XSLT/Element/message /es/docs/XSLT/namespace-alias /es/docs/Web/XSLT/Element/namespace-alias -/es/docs/XSLT/number /es/docs/Web/XSLT/Element/number /es/docs/XSLT/otherwise /es/docs/Web/XSLT/Element/otherwise /es/docs/XSLT/when /es/docs/Web/XSLT/Element/when /es/docs/XSLT/with-param /es/docs/Web/XSLT/Element/with-param @@ -2748,7 +2728,6 @@ /es/docs/XSLT:key /es/docs/Web/XSLT/Element/key /es/docs/XSLT:message /es/docs/Web/XSLT/Element/message /es/docs/XSLT:namespace-alias /es/docs/Web/XSLT/Element/namespace-alias -/es/docs/XSLT:number /es/docs/Web/XSLT/Element/number /es/docs/XSLT:otherwise /es/docs/Web/XSLT/Element/otherwise /es/docs/XSLT:when /es/docs/Web/XSLT/Element/when /es/docs/XSLT:with-param /es/docs/Web/XSLT/Element/with-param diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index e87c40ab52..83a0192a58 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -12,13 +12,6 @@ "chrisdavidmills" ] }, - "Games/Anatomy": { - "modified": "2019-01-16T22:18:47.235Z", - "contributors": [ - "wbamberg", - "cnaucler" - ] - }, "Games/Introduction": { "modified": "2020-11-28T21:23:49.961Z", "contributors": [ @@ -2356,12 +2349,6 @@ "eljonims" ] }, - "Learn/Forms/Property_compatibility_table_for_form_controls": { - "modified": "2020-08-30T01:12:52.090Z", - "contributors": [ - "edchasw" - ] - }, "Learn/Forms/Sending_and_retrieving_form_data": { "modified": "2020-07-16T22:21:26.056Z", "contributors": [ @@ -2956,14 +2943,6 @@ "madmaxdios" ] }, - "Learn/JavaScript/Asynchronous/Async_await": { - "modified": "2020-11-12T21:09:30.375Z", - "contributors": [ - "sargentogato", - "oscartzgz", - "SphinxKnight" - ] - }, "Learn/JavaScript/Asynchronous/Concepts": { "modified": "2020-11-19T20:30:13.091Z", "contributors": [ @@ -2996,32 +2975,6 @@ "carlosgocereceda" ] }, - "Learn/JavaScript/Building_blocks/Events": { - "modified": "2020-07-16T22:31:37.027Z", - "contributors": [ - "jhonarielgj", - "sebastiananea", - "maximilianotulian", - "ismamz" - ] - }, - "Learn/JavaScript/Building_blocks/Functions": { - "modified": "2020-10-10T22:09:39.322Z", - "contributors": [ - "GianGuerra", - "pmusetti", - "pablorebora", - "blanchart", - "Alessa", - "DanielAgustinTradito" - ] - }, - "Learn/JavaScript/Building_blocks/Image_gallery": { - "modified": "2020-07-16T22:31:42.753Z", - "contributors": [ - "amIsmael" - ] - }, "Learn/JavaScript/Building_blocks/Looping_code": { "modified": "2020-10-10T18:54:10.014Z", "contributors": [ @@ -3542,14 +3495,6 @@ "javierdelpino" ] }, - "Learn/Server-side/Django/django_assessment_blog": { - "modified": "2020-07-16T22:37:48.773Z", - "contributors": [ - "ricardo-soria", - "matiexe", - "javierdelpino" - ] - }, "Learn/Server-side/Django/skeleton_website": { "modified": "2020-07-16T22:36:52.017Z", "contributors": [ @@ -3560,14 +3505,6 @@ "javierdelpino" ] }, - "Learn/Server-side/Django/web_application_security": { - "modified": "2020-07-16T22:37:45.102Z", - "contributors": [ - "sebastianmr6", - "ricardo-soria", - "javierdelpino" - ] - }, "Learn/Server-side/Express_Nodejs": { "modified": "2020-07-16T22:37:51.529Z", "contributors": [ @@ -4235,15 +4172,6 @@ "Epaclon" ] }, - "Mozilla/Firefox/Releases/19": { - "modified": "2019-03-18T20:54:04.568Z", - "contributors": [ - "ulisestrujillo", - "wbamberg", - "Sebastianz", - "mannyatico" - ] - }, "Mozilla/Firefox/Releases/2": { "modified": "2019-03-23T23:58:56.168Z", "contributors": [ @@ -4429,13 +4357,6 @@ "JoaLop" ] }, - "Mozilla/Firefox/Releases/63": { - "modified": "2019-03-18T21:22:18.650Z", - "contributors": [ - "SphinxKnight", - "Dev-MADJ" - ] - }, "Mozilla/Firefox/Releases/66": { "modified": "2019-05-09T17:56:10.878Z", "contributors": [ @@ -4491,12 +4412,6 @@ "dinoop.p1" ] }, - "Tools/3D_View": { - "modified": "2020-07-16T22:34:25.151Z", - "contributors": [ - "rmilano" - ] - }, "Tools/Browser_Console": { "modified": "2020-07-16T22:35:42.205Z", "contributors": [ @@ -4539,12 +4454,6 @@ "drdavi7@hotmail.com" ] }, - "Tools/Debugger/How_to/Set_a_breakpoint": { - "modified": "2020-07-16T22:35:09.854Z", - "contributors": [ - "erickton" - ] - }, "Tools/Debugger/How_to/Use_a_source_map": { "modified": "2020-07-16T22:35:12.325Z", "contributors": [ @@ -4647,14 +4556,6 @@ "amaiafilo" ] }, - "Tools/Page_Inspector/How_to/Work_with_animations": { - "modified": "2020-07-16T22:34:36.333Z", - "contributors": [ - "lyono666", - "angelmillan", - "fmagrosoto" - ] - }, "Tools/Page_Inspector/UI_Tour": { "modified": "2020-07-16T22:34:48.922Z", "contributors": [ @@ -4710,12 +4611,6 @@ "maedca" ] }, - "Tools/Settings": { - "modified": "2020-07-16T22:36:34.818Z", - "contributors": [ - "amaiafilo" - ] - }, "Tools/Storage_Inspector": { "modified": "2020-07-16T22:36:09.696Z", "contributors": [ @@ -4986,12 +4881,6 @@ "rayrojas" ] }, - "Web/API/AudioNode": { - "modified": "2020-10-15T22:15:25.198Z", - "contributors": [ - "rayrojas" - ] - }, "Web/API/BaseAudioContext": { "modified": "2019-03-18T21:00:34.809Z", "contributors": [ @@ -5378,12 +5267,6 @@ "Debianpc" ] }, - "Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility": { - "modified": "2019-03-18T21:31:01.983Z", - "contributors": [ - "cepeami01" - ] - }, "Web/API/Canvas_API/Tutorial/Optimizing_canvas": { "modified": "2019-03-23T23:18:04.030Z", "contributors": [ @@ -6803,13 +6686,6 @@ "carlosbulnes" ] }, - "Web/API/FileSystem": { - "modified": "2019-07-04T14:31:32.136Z", - "contributors": [ - "lperezp", - "jpmontoya182" - ] - }, "Web/API/FormData": { "modified": "2020-10-15T21:22:58.694Z", "contributors": [ @@ -7080,12 +6956,6 @@ "empirreamm" ] }, - "Web/API/HTMLCanvasElement/toBlob": { - "modified": "2019-03-23T22:44:55.955Z", - "contributors": [ - "kodamirmo" - ] - }, "Web/API/HTMLCanvasElement/toDataURL": { "modified": "2020-10-15T21:38:42.950Z", "contributors": [ @@ -7429,18 +7299,6 @@ "rgomez" ] }, - "Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types": { - "modified": "2019-03-23T23:18:24.597Z", - "contributors": [ - "Evinton" - ] - }, - "Web/API/Headers": { - "modified": "2020-10-15T22:07:38.324Z", - "contributors": [ - "Estebanrg21" - ] - }, "Web/API/History": { "modified": "2020-10-15T22:28:24.964Z", "contributors": [ @@ -7658,12 +7516,6 @@ "PatoDeTuring" ] }, - "Web/API/MediaSource": { - "modified": "2019-03-23T22:38:20.191Z", - "contributors": [ - "Lazaro" - ] - }, "Web/API/MediaStreamAudioSourceNode": { "modified": "2019-03-18T20:35:52.439Z", "contributors": [ @@ -8816,12 +8668,6 @@ "karlalhdz" ] }, - "Web/API/WebVTT_API": { - "modified": "2020-10-15T22:33:07.538Z", - "contributors": [ - "Pablo-No" - ] - }, "Web/API/Web_Audio_API": { "modified": "2019-03-23T23:31:19.634Z", "contributors": [ @@ -8918,18 +8764,6 @@ "Mgjbot" ] }, - "Web/API/Window/DOMContentLoaded_event": { - "modified": "2019-09-06T00:37:43.389Z", - "contributors": [ - "wbamberg", - "jramcast", - "ExE-Boss", - "fscholz", - "AlexOfSoCal", - "jdmgarcia", - "daniville" - ] - }, "Web/API/Window/alert": { "modified": "2019-03-23T22:27:29.008Z", "contributors": [ @@ -9365,14 +9199,6 @@ "benjroy" ] }, - "Web/API/Worker/postMessage": { - "modified": "2020-04-23T06:46:10.302Z", - "contributors": [ - "aguilahorus", - "cristyansv", - "mar777" - ] - }, "Web/API/Worker/terminate": { "modified": "2019-03-23T22:19:14.265Z", "contributors": [ @@ -9401,12 +9227,6 @@ "Jorolo" ] }, - "Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests": { - "modified": "2019-03-23T22:05:30.902Z", - "contributors": [ - "Juvenal-yescas" - ] - }, "Web/API/XMLHttpRequest/Using_XMLHttpRequest": { "modified": "2020-03-17T04:09:47.273Z", "contributors": [ @@ -10624,13 +10444,6 @@ "israel-munoz" ] }, - "Web/CSS/@document": { - "modified": "2020-10-15T22:01:34.650Z", - "contributors": [ - "SphinxKnight", - "lsosa81" - ] - }, "Web/CSS/@font-face": { "modified": "2019-09-26T12:01:00.515Z", "contributors": [ @@ -11219,13 +11032,6 @@ "cristianmartinez" ] }, - "Web/CSS/Cascade": { - "modified": "2020-04-20T15:19:07.785Z", - "contributors": [ - "arjusgit", - "tw1ttt3r" - ] - }, "Web/CSS/Child_combinator": { "modified": "2019-03-23T22:17:17.663Z", "contributors": [ @@ -11284,12 +11090,6 @@ "mikelmg" ] }, - "Web/CSS/Media_Queries/Testing_media_queries": { - "modified": "2019-03-23T23:07:40.812Z", - "contributors": [ - "TibicenasDesign" - ] - }, "Web/CSS/Media_Queries/Using_media_queries": { "modified": "2019-10-03T11:52:26.928Z", "contributors": [ @@ -11675,12 +11475,6 @@ "ethertank" ] }, - "Web/CSS/background-position-x": { - "modified": "2020-10-15T22:33:04.718Z", - "contributors": [ - "Ismael_Diaz" - ] - }, "Web/CSS/background-repeat": { "modified": "2020-10-15T21:16:00.953Z", "contributors": [ @@ -12007,18 +11801,6 @@ "Wrongloop" ] }, - "Web/CSS/border-radius": { - "modified": "2019-03-23T23:37:30.234Z", - "contributors": [ - "Barleby", - "Simplexible", - "Sebastianz", - "Prinz_Rana", - "teoli", - "bytx", - "wilo" - ] - }, "Web/CSS/border-right": { "modified": "2020-10-15T22:17:02.534Z", "contributors": [ @@ -12181,15 +11963,6 @@ "nadiafaya" ] }, - "Web/CSS/clip-path": { - "modified": "2020-10-15T21:54:58.750Z", - "contributors": [ - "fscholz", - "jorgeherrera9103", - "david-velilla", - "CarlosLinares" - ] - }, "Web/CSS/color": { "modified": "2020-10-15T21:15:23.982Z", "contributors": [ @@ -13934,13 +13707,6 @@ "Nachec" ] }, - "Web/HTML/Attributes/autocomplete": { - "modified": "2019-04-06T00:39:59.162Z", - "contributors": [ - "qmarquez", - "Raulpascual2" - ] - }, "Web/HTML/Attributes/crossorigin": { "modified": "2019-03-23T22:46:11.986Z", "contributors": [ @@ -14943,12 +14709,6 @@ "AleV" ] }, - "Web/HTML/Element/shadow": { - "modified": "2019-03-23T22:06:38.273Z", - "contributors": [ - "H4isan" - ] - }, "Web/HTML/Element/slot": { "modified": "2020-10-15T22:05:53.326Z", "contributors": [ @@ -19711,16 +19471,6 @@ "Sheppy" ] }, - "Web/JavaScript/Reference/Global_Objects/encodeURIComponent": { - "modified": "2020-03-12T19:37:33.179Z", - "contributors": [ - "jazjay", - "SphinxKnight", - "teoli", - "Mgjbot", - "Sheppy" - ] - }, "Web/JavaScript/Reference/Global_Objects/escape": { "modified": "2020-10-15T21:56:14.356Z", "contributors": [ @@ -20435,13 +20185,6 @@ "Talisker" ] }, - "Web/JavaScript/Reference/Statements/with": { - "modified": "2020-03-12T19:42:08.065Z", - "contributors": [ - "MarkelCuesta", - "lokcito" - ] - }, "Web/JavaScript/Reference/Strict_mode": { "modified": "2020-08-30T21:51:49.146Z", "contributors": [ @@ -20522,16 +20265,6 @@ "maedca" ] }, - "Web/MathML/Authoring": { - "modified": "2019-03-23T23:27:02.180Z", - "contributors": [ - "rafaqtro", - "fred.wang", - "voylinux", - "robertoasq", - "maedca" - ] - }, "Web/MathML/Element": { "modified": "2019-03-23T23:37:26.121Z", "contributors": [ @@ -20570,12 +20303,6 @@ "vltamara" ] }, - "Web/Media/Formats": { - "modified": "2020-07-15T09:47:42.018Z", - "contributors": [ - "Sheppy" - ] - }, "Web/OpenSearch": { "modified": "2019-03-24T00:00:08.096Z", "contributors": [ @@ -20742,13 +20469,6 @@ "humbertaco" ] }, - "Web/SVG/Element/foreignObject": { - "modified": "2019-03-23T23:05:21.297Z", - "contributors": [ - "Sebastianz", - "THernandez03" - ] - }, "Web/SVG/Element/g": { "modified": "2019-03-23T22:54:18.875Z", "contributors": [ @@ -21330,15 +21050,6 @@ "ErickCastellanos" ] }, - "Web/XSLT/Element/number": { - "modified": "2019-03-18T20:59:21.341Z", - "contributors": [ - "SphinxKnight", - "chrisdavidmills", - "Mgjbot", - "ErickCastellanos" - ] - }, "Web/XSLT/Element/otherwise": { "modified": "2019-03-18T20:59:16.726Z", "contributors": [ diff --git a/files/es/games/anatomy/index.html b/files/es/games/anatomy/index.html deleted file mode 100644 index 799f31f931..0000000000 --- a/files/es/games/anatomy/index.html +++ /dev/null @@ -1,325 +0,0 @@ ---- -title: Anatomy of a video game -slug: Games/Anatomy -tags: - - Bucle - - JavaScript - - juegos -translation_of: Games/Anatomy ---- -
{{GamesSidebar}}

{{IncludeSubnav("/en-US/docs/Games")}}

- -
-

Este artículo es un vistazo a la anatomía y flujo de trabajo del videojuego medio desde un punto de vista técnico, en términos de cómo debería funcionar el bucle principal. Ayuda a los principiantes del desarrollo moderno de videojuegos a entender lo que hace falta al construir un juego y cómo los estándares web como JavaScript se prestan como herramientas. Los programadores de juegos experimentados que sean novatos en el desarrollo web también se pueden beneficiar.

-
- -

Presentar, aceptar, traducir, calcular, repetir

- -

El objetivo de todo videojuego es presentar al usuario una situación, aceptar su entrada, traducir esas señales a acciones, y calcular una nueva situación a partir de esos actos. Los juegos están iterando continuamente por estas etapas, una y otra vez, hasta que ocurre alguna condición final (como ganas, perder, o salirse para ir a la cama). De forma poco sorpresiva, este patrón corresponde a cómo se programa el motor de un juego.

- -

Los detalles dependen del juego.

- -

Algunos juegos dirigen este ciclo con la entrada del usuario. Imagina que estás desarrollando un juego del tipo "encuentra las diferencias entre estas dos imágenes similares". Estos juegos presentan dos imágenes al usuario; aceptan sus clics (o toques); interpretan la entrada como éxito, fallo, pausa, interacción del menú, etc; y finalmente, calculan una escena actualizada resultante de esa entrada. El bucle del juego avanza con la entrada del usuario, y se queda en espera hasta que ésta se produce. Esto es más bien un enfoque basado por turnos que no requiere una actualización constante cada frame, sólo cuando el jugador reacciona.

- -

Otros juegos requieren control sobre cada uno de los más pequeños aspectos posibles. Se aplican los mismos principios de antes, con una ligera variación: cada frame de la animación hace progresar el ciclo, y cualquier cambio en la entrada del usuario se captura en el primer turno disponible. Este modelo de una-vez-por-frame se implementa en algo llamado bucle principal. Si el bucle de tu juego está basado en tiempo, éste será una ley a la que se tendrán que atener tus simulaciones.

- -

Pero puede no necesitar de un control por-frame. El bucle de tu juego podría ser similar al ejemplo de encuentra las diferencias, y basarse en las entradas del usuario. Podría necesitar tanto entradas como tiempo simulado. Podría incluso estar totalmente basado en algo diferente.

- -

Por suerte, el JavaScript moderno (que se describe en las siguientes secciones) hace sencillo desarrollar un bucle principal eficiente, tipo ejecutar-una-vez-por-frame. Por supuesto, estará tan optimizado como tú lo hagas. Si algo parece que debería ir acoplado a un evento más infrecuente, suele ser una buena idea (aunque no siempre) sacarlo fuera del bucle principal.

- -

Crear un bucle principal en JavaScript

- -

JavaScript funciona mejor con eventos y funciones callback. Los navegadores modernos se esfuerzan en invocar los métodos sólo en cuanto se necesita, y reposar (o hacer otras tareas) en los intervalos. Es una idea excelente añadir tu código a los momentos apropiados. Considera si tu función necesita de verdad ser invocada en un intervalo estricto de tiempo, a cada frame, o sólo cuando haya ocurrido alguna otra cosa. Especificándole al navegador cuándo tiene que ser invocada tu función le permite optimizarla. Además, probablemente haga tu trabajo más fácil.

- -

Algún código necesita ejecutarse frame a frame, así que ¿por qué añadir esa función a cualquier otra cosa que al planificador de redibulado del navegador? En la web, {{ domxref("window.requestAnimationFrame()") }} será la base de la mayoría de bucles principales frame-a-frame bien programados. Al invocarla, hay que pasarle una función callback. Esa función callback se ejecutará en el momento apropiado antes del próximo redibujado. Aquí hay un ejemplo de un bucle principal sencillo:

- -
window.main = function () {
-  window.requestAnimationFrame( main );
-
-  // Lo que sea que tenga que hacer tu bucle principal
-};
-
-main(); // Empezar el ciclo
- -

Note: In each of the main() methods discussed here, we schedule a new requestAnimationFrame before performing our loop contents. That is not by accident and it is considered best practice. Calling the next requestAnimationFrame early ensures the browser receives it on time to plan accordingly even if your current frame misses its VSync window.

- -

The above chunk of code has two statements. The first statement creates a function as a global variable called main(). This function does some work and also tells the browser to call itself next frame with window.requestAnimationFrame(). The second statement calls the main() function, defined in the first statement. Because main() is called once in the second statement and every call of it places itself in the queue of things to do next frame, main() is synchronized to your framerate.

- -

Of course this loop is not perfect. Before we discuss ways to change it, let us discuss what it already does well.

- -

Timing the main loop to when the browser paints to the display allows you to run your loop as frequently as the browser wants to paint. You are given control over each frame of animation. It is also very simple because main() is the only function getting looped. A First Person Shooter (or a similar game) presents a new scene once every frame. You cannot really get more smooth and responsive than that.

- -

But do not immediately assume animations require frame-by-frame control. Simple animations can be easily performed, even GPU-accelerated, with CSS animations and other tools included in the browser. There are a lot of them and they will make your life easier.

- -

Building a better main loop in Javascript

- -

There are two obvious issues with our previous main loop: main() pollutes the {{ domxref("window") }} object (where all global variables are stored) and the example code did not leave us with a way to stop the loop unless the whole tab is closed or refreshed. For the first issue, if you want the main loop to just run and you do not need easy (direct) access to it, you could create it as an Immediately-Invoked Function Expression (IIFE).

- -
/*
-* Starting with the semicolon is in case whatever line of code above this example
-* relied on automatic semicolon insertion (ASI). The browser could accidentally
-* think this whole example continues from the previous line. The leading semicolon
-* marks the beginning of our new line if the previous one was not empty or terminated.
-*/
-
-;(function () {
-  function main() {
-    window.requestAnimationFrame( main );
-
-    // Your main loop contents.
-  }
-
-  main(); // Start the cycle
-})();
- -

When the browser comes across this IIFE, it will define your main loop and immediately queue it for the next frame. It will not be attached to any object and main (or main() for methods) will be a valid unused name in the rest of the application, free to be defined as something else.

- -

Note: In practice, it is more common to prevent the next requestAnimationFrame() with an if-statement, rather than calling cancelAnimationFrame().

- -

For the second issue, stopping the main loop, you will need to cancel the call to main() with {{ domxref("window.cancelAnimationFrame()") }}. You will need to pass cancelAnimationFrame() the ID token given by requestAnimationFrame() when it was last called. Let us assume that your game's functions and variables are built on a namespace that you called MyGame. Expanding our last example, the main loop would now look like:

- -
/*
-* Starting with the semicolon is in case whatever line of code above this example
-* relied on automatic semicolon insertion (ASI). The browser could accidentally
-* think this whole example continues from the previous line. The leading semicolon
-* marks the beginning of our new line if the previous one was not empty or terminated.
-*
-* Let us also assume that MyGame is previously defined.
-*/
-
-;(function () {
-  function main() {
-    MyGame.stopMain = window.requestAnimationFrame( main );
-
-    // Your main loop contents.
-  }
-
-  main(); // Start the cycle
-})();
- -

We now have a variable declared in our MyGame namespace, which we call stopMain, that contains the ID returned from our main loop's most recent call to requestAnimationFrame(). At any point, we can stop the main loop by telling the browser to cancel the request that corresponds to our token.

- -
window.cancelAnimationFrame( MyGame.stopMain );
- -

The key to programming a main loop, in JavaScript, is to it attach to whatever event should be driving your action and pay attention to how the different systems involved interplay. You may have multiple components driven by multiple different types of events. This feels like unnecessary complexity but it might just be good optimization (not necessarily, of course). The problem is that you are not programming a typical main loop. In Javascript, you are using the browser's main loop and you are trying to do so effectively.

- -

Building a more optimized main loop in JavaScript

- -

Ultimately, in JavaScript, the browser is running its own main loop and your code exists in some of its stages. The above sections describe main loops which try not to wrestle away control from the browser. These main methods attach themselves to window.requestAnimationFrame(), which asks the browser for control over the upcoming frame. It is up to the browser how to relate these requests to their main loop. The W3C spec for requestAnimationFrame does not really define exactly when the browsers must perform the requestAnimationFrame callbacks. This can be a benefit because it leaves browser vendors free to experiment with the solutions that they feel are best and tweak it over time.

- -

Modern versions of Firefox and Google Chrome (and probably others) attempt to connect requestAnimationFrame callbacks to their main thread at the very beginning of a frame's timeslice. The browser's main thread thus tries to look like the following:

- -
    -
  1. Start a new frame (while the previous frame is handled by the display).
  2. -
  3. Go through the list of requestAnimationFrame callbacks and invoke them.
  4. -
  5. Perform garbage collection and other per-frame tasks when the above callbacks stop controlling the main thread.
  6. -
  7. Sleep (unless an event interrupts the browser's nap) until the monitor is ready for your image (VSync) and repeat.
  8. -
- -

You can think about developing realtime applications as having a budget of time to do work. All of the above steps must take place every 16-and-a-half milliseconds to keep up with a 60 Hz display. Browsers invoke your code as early as possible to give it maximum computation time. Your main thread will often start workloads that are not even on the main thread (such as rasterization or shaders in WebGL). Long calculations can be performed on a Web Worker or a GPU at the same time as the browser uses its main thread to manage garbage collection, its other tasks, or handle asynchronous events.

- -

While we are on the topic of budgeting time, many web browsers have a tool called High Resolution Time. The {{ domxref("Date") }} object is no longer the recognised method for timing events because it is very imprecise and can be modified by the system clock. High Resolution Time, on the other hand, counts the number of milliseconds since navigationStart (when the previous document is unloaded). This value is returned as a decimal number accurate to a thousandth of a millisecond. It is known as a {{ domxref("DOMHighResTimeStamp") }} but, for all intents and purposes, consider it a floating point number.

- -

Note: Systems (hardware or software) that are not capable of microsecond accuracy are allowed to provide millisecond accuracy as a minimum. They should provide 0.001ms accuracy if they are capable of it, however.

- -

This value is not too useful alone, since it is relative to a fairly uninteresting event, but it can be subtracted from another timestamp to accurately and precisely determine how much time elapsed between those two points. To acquire one of these timestamps, you can call window.performance.now() and store the result as a variable.

- -
var tNow = window.performance.now();
-
- -

Back to the topic of the main loop. You will often want to know when your main function was invoked. Because this is common, window.requestAnimationFrame() always provides a DOMHighResTimeStamp to callbacks as an argument when they are executed. This leads to another enhancement to our previous main loops.

- -
/*
-* Starting with the semicolon is in case whatever line of code above this example
-* relied on automatic semicolon insertion (ASI). The browser could accidentally
-* think this whole example continues from the previous line. The leading semicolon
-* marks the beginning of our new line if the previous one was not empty or terminated.
-*
-* Let us also assume that MyGame is previously defined.
-*/
-
-;(function () {
-  function main( tFrame ) {
-    MyGame.stopMain = window.requestAnimationFrame( main );
-
-    // Your main loop contents.
-    // tFrame, from "function main ( tFrame )", is now a DOMHighResTimeStamp provided by rAF.
-  }
-
-  main(); // Start the cycle
-})();
- -

Several other optimizations are possible and it really depends on what your game attempts to accomplish. Your game genre will obviously make a difference but it could even be more subtle than that. You could draw every pixel individually on a canvas or you could layer DOM elements (including multiple WebGL canvases with transparent backgrounds if you want) into a complex hierarchy. Each of these paths will lead to different opportunities and constraints.

- -

It is decision... time

- -

You will need to make hard decisions about your main loop: how to simulate the accurate progress of time. If you demand per-frame control then you will need to determine how frequently your game will update and draw. You might even want update and draw to occur at different rates. You will also need to consider how gracefully your game will fail if the user's system cannot keep up with the workload. Let us start by assuming that you will handle user input and update the game state every time you draw. We will branch out later.

- -

Note: Changing how your main loop deals with time is a debugging nightmare, everywhere. Think about your needs, carefully, before working on your main loop.

- -

What most browser games should look like

- -

If your game can hit the maximum refresh rate of any hardware you support then your job is fairly easy. You can simply update, render, and then do nothing until VSync.

- -
/*
-* Starting with the semicolon is in case whatever line of code above this example
-* relied on automatic semicolon insertion (ASI). The browser could accidentally
-* think this whole example continues from the previous line. The leading semicolon
-* marks the beginning of our new line if the previous one was not empty or terminated.
-*
-* Let us also assume that MyGame is previously defined.
-*/
-
-;(function () {
-  function main( tFrame ) {
-    MyGame.stopMain = window.requestAnimationFrame( main );
-
-    update( tFrame ); //Call your update method. In our case, we give it rAF's timestamp.
-    render();
-  }
-
-  main(); // Start the cycle
-})();
- -

If the maximum refresh rate cannot be reached, quality settings could be adjusted to stay under your time budget. The most famous example of this concept is the game from id Software, RAGE. This game removed control from the user in order to keep its calculation time at roughly 16ms (or roughly 60fps). If computation took too long then rendered resolution would decrease, textures and other assets would fail to load or draw, and so forth. This (non-web) case study made a few assumptions and tradeoffs:

- - - -

Other ways to handle variable refresh rate needs

- -

Other methods of tackling the problem exist.

- -

One common technique is to update the simulation at a constant frequency and then draw as much (or as little) of the actual frames as possible. The update method can continue looping without care about what the user sees. The draw method can view the last update and when it happened. Since draw knows when it represents, and the simulation time for the last update, it can predict a plausible frame to draw for the user. It does not matter whether this is more frequent than the official update loop (or even less frequent). The update method sets checkpoints and, as frequently as the system allows, the render method draws instants of time around them. There are many ways to separate the update method in web standards:

- - - -

Each of these methods have similar tradeoffs:

- - - -

A separate update and draw method could look like the following example. For the sake of demonstration, the example is based on the third bullet point, just without using Web Workers for readability (and, let's be honest, writeability).

- -

Note: This example, specifically, is in need of technical review.

- -
/*
-* Starting with the semicolon is in case whatever line of code above this example
-* relied on automatic semicolon insertion (ASI). The browser could accidentally
-* think this whole example continues from the previous line. The leading semicolon
-* marks the beginning of our new line if the previous one was not empty or terminated.
-*
-* Let us also assume that MyGame is previously defined.
-*
-* MyGame.lastRender keeps track of the last provided requestAnimationFrame timestamp.
-* MyGame.lastTick keeps track of the last update time. Always increments by tickLength.
-* MyGame.tickLength is how frequently the game state updates. It is 20 Hz (50ms) here.
-*
-* timeSinceTick is the time between requestAnimationFrame callback and last update.
-* numTicks is how many updates should have happened between these two rendered frames.
-*
-* render() is passed tFrame because it is assumed that the render method will calculate
-*          how long it has been since the most recently passed update tick for
-*          extrapolation (purely cosmetic for fast devices). It draws the scene.
-*
-* update() calculates the game state as of a given point in time. It should always
-*          increment by tickLength. It is the authority for game state. It is passed
-*          the DOMHighResTimeStamp for the time it represents (which, again, is always
-*          last update + MyGame.tickLength unless a pause feature is added, etc.)
-*
-* setInitialState() Performs whatever tasks are leftover before the mainloop must run.
-*                   It is just a generic example function that you might have added.
-*/
-
-;(function () {
-  function main( tFrame ) {
-    MyGame.stopMain = window.requestAnimationFrame( main );
-    var nextTick = MyGame.lastTick + MyGame.tickLength;
-    var numTicks = 0;
-
-    //If tFrame < nextTick then 0 ticks need to be updated (0 is default for numTicks).
-    //If tFrame = nextTick then 1 tick needs to be updated (and so forth).
-    //Note: As we mention in summary, you should keep track of how large numTicks is.
-    //If it is large, then either your game was asleep, or the machine cannot keep up.
-    if (tFrame > nextTick) {
-      var timeSinceTick = tFrame - MyGame.lastTick;
-      numTicks = Math.floor( timeSinceTick / MyGame.tickLength );
-    }
-
-    queueUpdates( numTicks );
-    render( tFrame );
-    MyGame.lastRender = tFrame;
-  }
-
-  function queueUpdates( numTicks ) {
-    for(var i=0; i < numTicks; i++) {
-      MyGame.lastTick = MyGame.lastTick + MyGame.tickLength; //Now lastTick is this tick.
-      update( MyGame.lastTick );
-    }
-  }
-
-  MyGame.lastTick = performance.now();
-  MyGame.lastRender = MyGame.lastTick; //Pretend the first draw was on first update.
-  MyGame.tickLength = 50; //This sets your simulation to run at 20Hz (50ms)
-
-  setInitialState();
-  main(performance.now()); // Start the cycle
-})();
- -

Another alternative is to simply do certain things less often. If a portion of your update loop is difficult to compute but insensitive to time, you might consider scaling back its frequency and, ideally, spreading it out into chunks throughout that lengthened period. An implicit example of this is found over at The Artillery Blog for Artillery Games, where they adjust their rate of garbage generation to optimize garbage collection. Obviously, cleaning up resources is not time sensitive (especially if tidying is more disruptive than the garbage itself).

- -

This may also apply to some of your own tasks. Those are good candidates to throttle when available resources become a concern.

- -

Summary

- -

I want to be clear that any of the above, or none of them, could be best for your game. The correct decision entirely depends on the trade-offs that you are willing (and unwilling) to make. The concern is mostly with switching to another option. Fortunately, I do not have any experience with this but I have heard it is an excruciating game of Whack-a-Mole.

- -

An important thing to remember for managed platforms, like the web, is that your loop may stop execution for significant periods of time. This could occur when the user unselects your tab and the browser sleeps (or slows) its requestAnimationFrame callback interval. You have many ways to deal with this situation and this could depend on whether your game is single player or multiplayer. Some choices are:

- - - -

Once your main loop has been developed and you have decided on a set of assumptions and tradeoffs which suit your game, it is now just a matter of using your decisions to calculate any applicable physics, AI, sounds, network synchronization, and whatever else your game may require.

diff --git a/files/es/learn/forms/property_compatibility_table_for_form_controls/index.html b/files/es/learn/forms/property_compatibility_table_for_form_controls/index.html deleted file mode 100644 index a5c7202d69..0000000000 --- a/files/es/learn/forms/property_compatibility_table_for_form_controls/index.html +++ /dev/null @@ -1,2004 +0,0 @@ ---- -title: Tabla de compatibilidad de propiedades CSS para controles de formulario -slug: Learn/Forms/Property_compatibility_table_for_form_controls -translation_of: Learn/Forms/Property_compatibility_table_for_form_controls -original_slug: Learn/HTML/Forms/Property_compatibility_table_for_form_controls ---- -
{{learnsidebar}}
- -

Las siguientes tablas de compatibilidad intentan resumir el estado del soporte de CSS para formularios HTML. Debido a la complejidad de los formularios CSS y HTML, estas tablas no se pueden considerar una referencia perfecta. Sin embargo, le darán una buena idea de lo que se puede y no se puede hacer, lo que le ayudará al aprender a hacer las cosas.

- -

Cómo leer las tablas

- -

Valores

- -

Para cada propiedad, hay cuatro valores posibles:

- -
-
Si
-
Existe un soporte razonablemente consistente para la propiedad en todos los navegadores. Es posible que aún enfrente efectos secundarios extraños en ciertos casos extremos.
-
Parcial
-
Si bien la propiedad funciona, con frecuencia puede enfrentar efectos secundarios extraños o inconsistencias. Probablemente debería evitar estas propiedades a menos que primero domine esos efectos secundarios.
-
No
-
La propiedad simplemente no funciona o es tan inconsistente que no es confiable.
-
n.a.
-
La propiedad no tiene ningún significado para este tipo de widget.
-
- -

Representación

- -

Para cada propiedad hay dos representaciones posibles:

- -
-
N (Normal)
-
Indica que la propiedad se aplica tal cual
-
T (Retocada)
-
Indica que la propiedad se aplica con la regla adicional como se muestra a continuación:
-
- -
* {
-  /* Turn off the native look and feel */
-  -webkit-appearance: none;
-  appearance: none;
-
-/* for Internet Explorer */
-  background: none;
-}
- -

Tablas de compatibilidad

- -

Comportamientos globales

- -

Algunos comportamientos son comunes a muchos navegadores a nivel global::

- -
-
{{cssxref("border")}}, {{cssxref("background")}}, {{cssxref("border-radius")}}, {{cssxref("height")}}
-
El uso de una de estas propiedades puede desactivar parcial o totalmente la apariencia nativa de los widgets en algunos navegadores. Tenga cuidado cuando los use.
-
{{cssxref("line-height")}}
-
Esta propiedad se admite de forma inconsistente en todos los navegadores y debe evitarla.
-
{{cssxref("text-decoration")}}
-
Esta propiedad no es compatible con el navegador Opera en widgets de formulario.
-
{{cssxref("text-overflow")}}
-
Opera, Safari, y IE9 no admiten esta propiedad en widgets de formulario.
-
{{cssxref("text-shadow")}}
-
Opera no admite {{cssxref("text-shadow")}} en widgets de formularios e IE9 no lo admite en absoluto.
-
- -

Text fields

- -

See the {{htmlelement("input/text", "text")}}, {{htmlelement("input/search", "search")}}, and {{htmlelement("input/password", "password")}} input types.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}YesYes
{{cssxref("height")}}Partial[1][2]Yes -
    -
  1. WebKit browsers (mostly on Mac OSX and iOS) use the native look & feel for the search fields. Therefore, it's required to use -webkit-appearance:none to be able to apply this property to search fields.
  2. -
  3. On Windows 7, Internet Explorer 9 does not apply the border unless background:none is applied.
  4. -
-
{{cssxref("border")}}Partial[1][2]Yes -
    -
  1. WebKit browsers (mostly on Mac OSX and iOS) use the native look & feel for the search fields. Therefore, it's required to use -webkit-appearance:none to be able to apply this property to search fields.
  2. -
  3. On Windows 7, Internet Explorer 9 does not apply the border unless background:none is applied.
  4. -
-
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}Partial[1][2]Yes -
    -
  1. WebKit browsers (mostly on Mac OSX and iOS) use the native look & feel for the search fields. Therefore, it's required to use -webkit-appearance:none to be able to apply this property to search fields.
  2. -
  3. On Windows 7, Internet Explorer 9 does not apply the border unless background:none is applied.
  4. -
-
Text and font
{{cssxref("color")}}[1]YesYes -
    -
  1. If the {{cssxref("border-color")}} property is not set, some WebKit based browsers will apply the {{cssxref("color")}} property to the border as well as the font on {{htmlelement("textarea")}}s.
  2. -
-
{{cssxref("font")}}YesYesSee the note about {{cssxref("line-height")}}
{{cssxref("letter-spacing")}}YesYes
{{cssxref("text-align")}}YesYes
{{cssxref("text-decoration")}}PartialPartialSee the note about Opera
{{cssxref("text-indent")}}Partial[1]Partial[1] -
    -
  1. IE9 supports this property only on {{htmlelement("textarea")}}s, whereas Opera only supports it on single line text fields.
  2. -
-
{{cssxref("text-overflow")}}PartialPartial
{{cssxref("text-shadow")}}PartialPartial
{{cssxref("text-transform")}}YesYes
Border and background
{{cssxref("background")}}Partial[1]Yes -
    -
  1. WebKit browsers (mostly on Mac OSX and iOS) use the native look & feel for the search fields. Therefore, it's required to use -webkit-appearance:none to be able to apply this property to search fields. On Windows 7, Internet Explorer 9 does not apply the border unless background:none is applied.
  2. -
-
{{cssxref("border-radius")}}Partial[1][2]Yes -
    -
  1. WebKit browsers (mostly on Mac OSX and iOS) use the native look & feel for the search fields. Therefore, it's required to use -webkit-appearance:none to be able to apply this property to search fields. On Windows 7, Internet Explorer 9 does not apply the border unless background:none is applied.
  2. -
  3. On Opera the {{cssxref("border-radius")}} property is applied only if an explicit border is set.
  4. -
-
{{cssxref("box-shadow")}}NoPartial[1] -
    -
  1. IE9 does not support this property.
  2. -
-
- -

Buttons

- -

See the {{htmlelement("input/button", "button")}}{{htmlelement("input/submit", "submit")}}, and {{htmlelement("input/reset", "reset")}} input types and the {{htmlelement("button")}} element.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}YesYes
{{cssxref("height")}}Partial[1]Yes -
    -
  1. This property is not applied on WebKit based browsers on Mac OSX or iOS.
  2. -
-
{{cssxref("border")}}PartialYes
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}Partial[1]Yes -
    -
  1. This property is not applied on WebKit based browsers on Mac OSX or iOS.
  2. -
-
Text and font
{{cssxref("color")}}YesYes
{{cssxref("font")}}YesYesSee the note about {{cssxref("line-height")}}.
{{cssxref("letter-spacing")}}YesYes
{{cssxref("text-align")}}NoNo
{{cssxref("text-decoration")}}PartialYes
{{cssxref("text-indent")}}YesYes
{{cssxref("text-overflow")}}NoNo
{{cssxref("text-shadow")}}PartialPartial
{{cssxref("text-transform")}}YesYes
Border and background
{{cssxref("background")}}YesYes
{{cssxref("border-radius")}}Yes[1]Yes[1] -
    -
  1. On Opera the {{cssxref("border-radius")}} property is applied only if an explicit border is set.
  2. -
-
{{cssxref("box-shadow")}}NoPartial[1] -
    -
  1. IE9 does not support this property.
  2. -
-
- -

Number

- -

See the  {{htmlelement("input/number", "number")}} input type. There is no standard way to change the style of spinners used to change the value of the field, with the spinners on Safari being outside the field.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}YesYes
{{cssxref("height")}}Partial[1]Partial[1] -
    -
  1. On Opera, the spinners are zoomed in, which can hide the content of the field.
  2. -
-
{{cssxref("border")}}YesYes
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}Partial[1]Partial[1] -
    -
  1. On Opera, the spinners are zoomed in, which can hide the content of the field.
  2. -
-
Text and font
{{cssxref("color")}}YesYes
{{cssxref("font")}}YesYesSee the note about {{cssxref("line-height")}}.
{{cssxref("letter-spacing")}}YesYes
{{cssxref("text-align")}}YesYes
{{cssxref("text-decoration")}}PartialPartial
{{cssxref("text-indent")}}YesYes
{{cssxref("text-overflow")}}NoNo
{{cssxref("text-shadow")}}PartialPartial
{{cssxref("text-transform")}}N.A.N.A.
Border and background
{{cssxref("background")}}NoNo -

Supported but there is too much inconsistency between browsers to be reliable.

-
{{cssxref("border-radius")}}NoNo
{{cssxref("box-shadow")}}NoNo
- -

Check boxes and radio buttons

- -

See the {{htmlelement("input/checkbox", "checkbox")}} and {{htmlelement("input/radio", "radio")}} input types.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}No[1]No[1] -
    -
  1. Some browsers add extra margins and others stretch the widget.
  2. -
-
{{cssxref("height")}}No[1]No[1] -
    -
  1. Some browsers add extra margins and others stretch the widget.
  2. -
-
{{cssxref("border")}}NoNo
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}NoNo
Text and font
{{cssxref("color")}}N.A.N.A.
{{cssxref("font")}}N.A.N.A.
{{cssxref("letter-spacing")}}N.A.N.A.
{{cssxref("text-align")}}N.A.N.A.
{{cssxref("text-decoration")}}N.A.N.A.
{{cssxref("text-indent")}}N.A.N.A.
{{cssxref("text-overflow")}}N.A.N.A.
{{cssxref("text-shadow")}}N.A.N.A.
{{cssxref("text-transform")}}N.A.N.A.
Border and background
{{cssxref("background")}}NoNo
{{cssxref("border-radius")}}NoNo
{{cssxref("box-shadow")}}NoNo
- -

Select boxes (single line)

- -

See the {{htmlelement("select")}}{{htmlelement("optgroup")}} and  {{htmlelement("option")}} elements.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}Partial[1]Partial[1] -
    -
  1. This property is okay on the {{htmlelement("select")}} element, but it cannot be the case on the {{htmlelement("option")}} or {{htmlelement("optgroup")}} elements.
  2. -
-
{{cssxref("height")}}NoYes
{{cssxref("border")}}PartialYes
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}No[1]Partial[2] -
    -
  1. The property is applied, but in an inconsistent way between browsers on Mac OSX.
  2. -
  3. The property is well applied on the {{htmlelement("select")}} element, but is inconsistently handled on {{htmlelement("option")}} and {{htmlelement("optgroup")}} elements.
  4. -
-
Text and font
{{cssxref("color")}}Partial[1]Partial[1] -
    -
  1. On Mac OSX, WebKit based browsers do not support this property on native widgets and they, along with Opera, do not support it at all on {{htmlelement("option")}} and {{htmlelement("optgroup")}} elements.
  2. -
-
{{cssxref("font")}}Partial[1]Partial[1] -
    -
  1. On Mac OSX, WebKit based browsers do not support this property on native widgets and they, along with Opera, do not support it at all on {{htmlelement("option")}} and {{htmlelement("optgroup")}} elements.
  2. -
-
{{cssxref("letter-spacing")}}Partial[1]Partial[1] -
    -
  1. IE9 does not support this property on {{htmlelement("select")}}, {{htmlelement("option")}}, and {{htmlelement("optgroup")}} elements; WebKit based browsers on Mac OSX do not support this property on {{htmlelement("option")}} and {{htmlelement("optgroup")}} elements.
  2. -
-
{{cssxref("text-align")}}No[1]No[1] -
    -
  1. IE9 on Windows 7 and WebKit based browsers on Mac OSX do not support this property on this widget.
  2. -
-
{{cssxref("text-decoration")}}Partial[1]Partial[1] -
    -
  1. Only Firefox provides full support for this property. Opera does not support this property at all and other browsers only support it on the {{htmlelement("select")}} element.
  2. -
-
{{cssxref("text-indent")}}Partial[1][2]Partial[1][2] -
    -
  1. Most of the browsers only support this property on the {{htmlelement("select")}} element.
  2. -
  3. IE9 does not support this property.
  4. -
-
{{cssxref("text-overflow")}}NoNo
{{cssxref("text-shadow")}}Partial[1][2]Partial[1][2] -
    -
  1. Most of the browsers only support this property on the {{htmlelement("select")}} element.
  2. -
  3. IE9 does not support this property.
  4. -
-
{{cssxref("text-transform")}}Partial[1]Partial[1] -
    -
  1. Most of the browsers only support this property on the {{htmlelement("select")}} element.
  2. -
-
Border and background
{{cssxref("background")}}Partial[1]Partial[1] -
    -
  1. Most of the browsers only support this property on the {{htmlelement("select")}} element.
  2. -
-
{{cssxref("border-radius")}}Partial[1]Partial[1]
{{cssxref("box-shadow")}}NoPartial[1]
- -

Note Firefox does not provide any way to change the down arrow on the {{htmlelement("select")}} element.

- -

Select boxes (multiline)

- -

See the {{htmlelement("select")}}, {{htmlelement("optgroup")}} and  {{htmlelement("option")}} elements and the size attribute.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}YesYes
{{cssxref("height")}}YesYes
{{cssxref("border")}}YesYes
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}Partial[1]Partial[1] -
    -
  1. Opera does not support {{cssxref("padding-top")}} and {{cssxref("padding-bottom")}} on the {{htmlelement("select")}} element.
  2. -
-
Text and font
{{cssxref("color")}}YesYes
{{cssxref("font")}}YesYesSee the note about {{cssxref("line-height")}}.
{{cssxref("letter-spacing")}}Partial[1]Partial[1] -
    -
  1. IE9 does not support this property on {{htmlelement("select")}}, {{htmlelement("option")}}, and {{htmlelement("optgroup")}} elements; WebKit based browsers on Mac OSX do not support this property on {{htmlelement("option")}} and {{htmlelement("optgroup")}} elements.
  2. -
-
{{cssxref("text-align")}}No[1]No[1] -
    -
  1. IE9 on Windows 7 and WebKit based browser on Mac OSX do not support this property on this widget.
  2. -
-
{{cssxref("text-decoration")}}No[1]No[1] -
    -
  1. Only supported by Firefox and IE9+.
  2. -
-
{{cssxref("text-indent")}}NoNo
{{cssxref("text-overflow")}}NoNo
{{cssxref("text-shadow")}}NoNo
{{cssxref("text-transform")}}Partial[1]Partial[1] -
    -
  1. Most of the browsers only support this property on the {{htmlelement("select")}} element.
  2. -
-
Border and background
{{cssxref("background")}}YesYes
{{cssxref("border-radius")}}Yes[1]Yes[1] -
    -
  1. On Opera the {{cssxref("border-radius")}} property is applied only if an explicit border is set.
  2. -
-
{{cssxref("box-shadow")}}NoPartial[1] -
    -
  1. IE9 does not support this property.
  2. -
-
- -

Datalist

- -

See the {{htmlelement("datalist")}} and {{htmlelement("input")}} elements and the list attribute.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}NoNo
{{cssxref("height")}}NoNo
{{cssxref("border")}}NoNo
{{cssxref("margin")}}NoNo
{{cssxref("padding")}}NoNo
Text and font
{{cssxref("color")}}NoNo
{{cssxref("font")}}NoNo
{{cssxref("letter-spacing")}}NoNo
{{cssxref("text-align")}}NoNo
{{cssxref("text-decoration")}}NoNo
{{cssxref("text-indent")}}NoNo
{{cssxref("text-overflow")}}NoNo
{{cssxref("text-shadow")}}NoNo
{{cssxref("text-transform")}}NoNo
Border and background
{{cssxref("background")}}NoNo
{{cssxref("border-radius")}}NoNo
{{cssxref("box-shadow")}}NoNo
- -

File picker

- -

See the {{htmlelement("input/file", "file")}} input type.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}NoNo
{{cssxref("height")}}NoNo
{{cssxref("border")}}NoNo
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}NoNo
Text and font
{{cssxref("color")}}YesYes
{{cssxref("font")}}No[1]No[1] -
    -
  1. Supported, but there is too much inconsistency between browsers to be reliable.
  2. -
-
{{cssxref("letter-spacing")}}Partial[1]Partial[1] -
    -
  1. Many browsers apply this property to the select button.
  2. -
-
{{cssxref("text-align")}}NoNo
{{cssxref("text-decoration")}}NoNo
{{cssxref("text-indent")}}Partial[1]Partial[1] -
    -
  1. It acts more or less like an extra left margin outside the widget.
  2. -
-
{{cssxref("text-overflow")}}NoNo
{{cssxref("text-shadow")}}NoNo
{{cssxref("text-transform")}}NoNo
Border and background
{{cssxref("background")}}No[1]No[1] -
    -
  1. Supported, but there is too much inconsistency between browsers to be reliable.
  2. -
-
{{cssxref("border-radius")}}NoNo
{{cssxref("box-shadow")}}NoPartial[1] -
    -
  1. IE9 does not support this property.
  2. -
-
- -

Date pickers

- -

See the {{htmlelement("input/date", "date")}} and {{htmlelement("input/time", "time")}} input types. Many properties are supported, but there is too much inconstency between browsers to be reliable.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}NoNo
{{cssxref("height")}}NoNo
{{cssxref("border")}}NoNo
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}NoNo
Text and font
{{cssxref("color")}}NoNo
{{cssxref("font")}}NoNo
{{cssxref("letter-spacing")}}NoNo
{{cssxref("text-align")}}NoNo
{{cssxref("text-decoration")}}NoNo
{{cssxref("text-indent")}}NoNo
{{cssxref("text-overflow")}}NoNo
{{cssxref("text-shadow")}}NoNo
{{cssxref("text-transform")}}NoNo
Border and background
{{cssxref("background")}}NoNo
{{cssxref("border-radius")}}NoNo
{{cssxref("box-shadow")}}NoNo
- -

Color pickers

- -

See the {{htmlelement("input/color", "color")}} input type:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}YesYes
{{cssxref("height")}}No[1]Yes -
    -
  1. Opera handles this like a select widget with the same restriction.
  2. -
-
{{cssxref("border")}}YesYes
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}No[1]Yes -
    -
  1. Opera handles this like a select widget with the same restriction.
  2. -
-
Text and font
{{cssxref("color")}}N.A.N.A.
{{cssxref("font")}}N.A.N.A.
{{cssxref("letter-spacing")}}N.A.N.A.
{{cssxref("text-align")}}N.A.N.A.
{{cssxref("text-decoration")}}N.A.N.A.
{{cssxref("text-indent")}}N.A.N.A.
{{cssxref("text-overflow")}}N.A.N.A.
{{cssxref("text-shadow")}}N.A.N.A.
{{cssxref("text-transform")}}N.A.N.A.
Border and background
{{cssxref("background")}}No[1]No[1] -
    -
  1. Supported, but there is too much inconsistency between browsers to be reliable.
  2. -
-
{{cssxref("border-radius")}}No[1]No[1]
{{cssxref("box-shadow")}}No[1]No[1]
- -

Meters and progress

- -

See the {{htmlelement("meter")}} and {{htmlelement("progress")}} elements:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}YesYes
{{cssxref("height")}}YesYes
{{cssxref("border")}}PartialYes
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}YesPartial[1] -
    -
  1. Chrome hides the {{htmlelement("progress")}} and {{htmlelement("meter")}} element when the {{cssxref("padding")}} property is applied on a tweaked element.
  2. -
-
Text and font
{{cssxref("color")}}N.A.N.A.
{{cssxref("font")}}N.A.N.A.
{{cssxref("letter-spacing")}}N.A.N.A.
{{cssxref("text-align")}}N.A.N.A.
{{cssxref("text-decoration")}}N.A.N.A.
{{cssxref("text-indent")}}N.A.N.A.
{{cssxref("text-overflow")}}N.A.N.A.
{{cssxref("text-shadow")}}N.A.N.A.
{{cssxref("text-transform")}}N.A.N.A.
Border and background
{{cssxref("background")}}No[1]No[1] -
    -
  1. Supported, but there is too much inconsistency between browsers to be reliable.
  2. -
-
{{cssxref("border-radius")}}No[1]No[1]
{{cssxref("box-shadow")}}No[1]No[1]
- -

Range

- -

See the {{htmlelement("input/range", "range")}} input type. There is no standard way to change the style of the range grip and Opera has no way to tweak the default rendering of the range widget.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}YesYes
{{cssxref("height")}}Partial[1]Partial[1] -
    -
  1. Chrome and Opera add some extra space around the widget, whereas Opera on Windows 7 stretches the range grip.
  2. -
-
{{cssxref("border")}}NoYes
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}Partial[1]Yes -
    -
  1. The {{cssxref("padding")}} is applied, but has no visual effect.
  2. -
-
Text and font
{{cssxref("color")}}N.A.N.A.
{{cssxref("font")}}N.A.N.A.
{{cssxref("letter-spacing")}}N.A.N.A.
{{cssxref("text-align")}}N.A.N.A.
{{cssxref("text-decoration")}}N.A.N.A.
{{cssxref("text-indent")}}N.A.N.A.
{{cssxref("text-overflow")}}N.A.N.A.
{{cssxref("text-shadow")}}N.A.N.A.
{{cssxref("text-transform")}}N.A.N.A.
Border and background
{{cssxref("background")}}No[1]No[1] -
    -
  1. Supported, but there is too much inconsistency between browsers to be reliable.
  2. -
-
{{cssxref("border-radius")}}No[1]No[1]
{{cssxref("box-shadow")}}No[1]No[1]
- -

Image buttons

- -

See the {{htmlelement("input/image", "image")}} input type:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyNTNote
CSS box model
{{cssxref("width")}}YesYes
{{cssxref("height")}}YesYes
{{cssxref("border")}}YesYes
{{cssxref("margin")}}YesYes
{{cssxref("padding")}}YesYes
Text and font
{{cssxref("color")}}N.A.N.A.
{{cssxref("font")}}N.A.N.A.
{{cssxref("letter-spacing")}}N.A.N.A.
{{cssxref("text-align")}}N.A.N.A.
{{cssxref("text-decoration")}}N.A.N.A.
{{cssxref("text-indent")}}N.A.N.A.
{{cssxref("text-overflow")}}N.A.N.A.
{{cssxref("text-shadow")}}N.A.N.A.
{{cssxref("text-transform")}}N.A.N.A.
Border and background
{{cssxref("background")}}YesYes
{{cssxref("border-radius")}}Partial[1]Partial[1] -
    -
  1. IE9 does not support this property.
  2. -
-
{{cssxref("box-shadow")}}Partial[1]Partial[1] -
    -
  1. IE9 does not support this property.
  2. -
-
- -

See also

- -

Learning path

- - - -

Advanced Topics

- - diff --git a/files/es/learn/javascript/asynchronous/async_await/index.html b/files/es/learn/javascript/asynchronous/async_await/index.html deleted file mode 100644 index 3487b11664..0000000000 --- a/files/es/learn/javascript/asynchronous/async_await/index.html +++ /dev/null @@ -1,411 +0,0 @@ ---- -title: Haciendo la programación asíncrona más fácil con async y await -slug: Learn/JavaScript/Asynchronous/Async_await -translation_of: Learn/JavaScript/Asynchronous/Async_await ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous/Choosing_the_right_approach", "Learn/JavaScript/Asynchronous")}}
- -

Las incorporaciones más recientes al lenguaje JavaScript, son las funciones async y la palabra clave await, parte de la edición ECMAScript 2017 (véase ECMAScript Next support in Mozilla). Estas características, básicamente, actúan como azúcar sintáctico, haciendo el código asíncrono fácil de escribir y leer más tarde. Hacen que el código asíncrono se parezca más al código síncrono de la vieja escuela, por lo que merece la pena aprenderlo. 

- -

Este artículo le da lo que usted necesita saber. 

- - - - - - - - - - - - -
Requisitos previos:Conocimientos básicos de informática, entender de manera razonable los fundamentos de JavaScript y entender el código asíncrono en general y las promesas. 
Objetivo:Entender las promesas y cómo usarlas
- -

Los fundamentos de async/await

- -

Hay dos partes a la hora de usar async/await en su código.

- -

La palabra clave async

- -

Primero tenemos la palabra clave "async", que se coloca delante de la declaración de una función, para convertirla en función "async"(asíncrona). Una función "async", es una función que sabe cómo esperar la posibilidad de que la palabra clave "await" sea utilizada para invocar código asíncrono. 

- -

Intenta escribir las siguientes líneas en la consola de tu navegador. 

- -
function hello() { return "Hello" };
-hello();
- -

La función returna "Hello" — nada especial, verdad?

- -

Pero, qué pasa si convertimos esto en una función async? Trata lo siguiente:

- -
async function hello() { return "Hello" };
-hello();
- -

Ah!. Ahora cuando invocamos la función, retorna una promesa(promise). Esta es una de las características particulares de las funciones async —  los valores que retornan están garantizados para ser convertidos en promesas.

- -

También puedes crear una expresión de función async, así:

- -
let hello = async function() { return "Hello" };
-hello();
- -

Y puedes utilizar funciones flecha(arrow functions):

- -
let hello = async () => { return "Hello" };
- -

Todos estos hacen básicamente lo mismo.

- -

Para realmente consumir el valor retornado cuando la promesa se cumple, ya que se está devolviendo una promesa, podemos utilizar un bloque then()

- -
hello().then((value) => console.log(value))
- -

o incluso sólo un shorthand como

- -
hello().then(console.log)
- -

Como vimos en el último artículo.

- -

La palabra clave async se añade a las funciones para decirles que devuelvan una promesa en lugar de devolver directamente el valor. Adicionamente, esto permite que las funciones síncronas eviten cualquier potencial sobrecarga que viene con correr con el soporte por usar async. Cuando una función es declarada async con sólo añadir la manipulación necesaria, el motor de JavaScript puede optimizar su programa por usted. Dulce!

- -

So the async keyword is added to functions to tell them to return a promise rather than directly returning the value. In addition, this lets synchronous functions avoid any potential overhead that comes with running with support for using await. By only adding the necessary handling when the function is declared async, the JavaScript engine can optimize your program for you. Sweet!

- -

La palabra clave await

- -

La ventaja real de las funciones asincronas aparecen cuando las combinas con la palabra clave await — en efecto, await solo trabaja dentro de las funciones async. Esta puede ser puesta frente a cualquier funcion async basada en una promesa para pausar tu codigo en esa linea hasta que se cumpla la promesa, entonces retorna el valor resultante. Mientras tanto, otro código que puede estar esperando una oportunidad para ejecutarse, puede hacerlo.

- -

Puedes usar await cuando llames cualquier funcion que retorna una Promesa, incluyendo funciones web API.

- -

Este es un ejemplo trivial:

- -
async function hello() {
-  return greeting = await Promise.resolve("Hello");
-};
-
-hello().then(alert);
- -

Por supuesto, el ejemplo anterior no es muy util, aunque este sirve para ilustrar la syntaxis. Vamos a ver un ejemplo real.

- -

Reescribiendo el código de las promesas con async/await

- -

Let's look back at a simple fetch example that we saw in the previous article:

- -
fetch('coffee.jpg')
-.then(response => {
-  if (!response.ok) {
-    throw new Error(`HTTP error! status: ${response.status}`);
-  } else {
-    return response.blob();
-  }
-})
-.then(myBlob => {
-  let objectURL = URL.createObjectURL(myBlob);
-  let image = document.createElement('img');
-  image.src = objectURL;
-  document.body.appendChild(image);
-})
-.catch(e => {
-  console.log('There has been a problem with your fetch operation: ' + e.message);
-});
- -

By now, you should have a reasonable understanding of promises and how they work, but let's convert this to use async/await to see how much simpler it makes things:

- -
async function myFetch() {
-  let response = await fetch('coffee.jpg');
-
-  if (!response.ok) {
-    throw new Error(`HTTP error! status: ${response.status}`);
-  } else {
-    let myBlob = await response.blob();
-
-    let objectURL = URL.createObjectURL(myBlob);
-    let image = document.createElement('img');
-    image.src = objectURL;
-    document.body.appendChild(image);
-  }
-}
-
-myFetch()
-.catch(e => {
-  console.log('There has been a problem with your fetch operation: ' + e.message);
-});
- -

It makes code much simpler and easier to understand — no more .then() blocks everywhere!

- -

Since an async keyword turns a function into a promise, you could refactor your code to use a hybrid approach of promises and await, bringing the second half of the function out into a new block to make it more flexible:

- -
async function myFetch() {
-  let response = await fetch('coffee.jpg');
-  if (!response.ok) {
-    throw new Error(`HTTP error! status: ${response.status}`);
-  } else {
-    return await response.blob();
-  }
-}
-
-myFetch().then((blob) => {
-  let objectURL = URL.createObjectURL(blob);
-  let image = document.createElement('img');
-  image.src = objectURL;
-  document.body.appendChild(image);
-}).catch(e => console.log(e));
- -

You can try typing in the example yourself, or running our live example (see also the source code).

- -

But how does it work?

- -

You'll note that we've wrapped the code inside a function, and we've included the async keyword before the function keyword. This is necessary — you have to create an async function to define a block of code in which you'll run your async code; as we said earlier, await only works inside of async functions.

- -

Inside the myFetch() function definition you can see that the code closely resembles the previous promise version, but there are some differences. Instead of needing to chain a .then() block on to the end of each promise-based method, you just need to add an await keyword before the method call, and then assign the result to a variable. The await keyword causes the JavaScript runtime to pause your code on this line, allowing other code to execute in the meantime, until the async function call has returned its result. Once that's complete, your code continues to execute starting on the next line. For example:

- -
let response = await fetch('coffee.jpg');
- -

The response returned by the fulfilled fetch() promise is assigned to the response variable when that response becomes available, and the parser pauses on this line until that occurs. Once the response is available, the parser moves to the next line, which creates a Blob out of it. This line also invokes an async promise-based method, so we use await here as well. When the result of operation returns, we return it out of the myFetch() function.

- -

This means that when we call the myFetch() function, it returns a promise, so we can chain a .then() onto the end of it inside which we handle displaying the blob onscreen.

- -

You are probably already thinking "this is really cool!", and you are right — fewer .then() blocks to wrap around code, and it mostly just looks like synchronous code, so it is really intuitive.

- -

Adding error handling

- -

And if you want to add error handling, you've got a couple of options.

- -

You can use a synchronous try...catch structure with async/await. This example expands on the first version of the code we showed above:

- -
async function myFetch() {
-  try {
-    let response = await fetch('coffee.jpg');
-
-    if (!response.ok) {
-      throw new Error(`HTTP error! status: ${response.status}`);
-    } else {
-      let myBlob = await response.blob();
-      let objectURL = URL.createObjectURL(myBlob);
-      let image = document.createElement('img');
-      image.src = objectURL;
-      document.body.appendChild(image);
-    }
-  } catch(e) {
-    console.log(e);
-  }
-}
-
-myFetch();
- -

The catch() {} block is passed an error object, which we've called e; we can now log that to the console, and it will give us a detailed error message showing where in the code the error was thrown.

- -

If you wanted to use the second (refactored) version of the code that we showed above, you would be better off just continuing the hybrid approach and chaining a .catch() block onto the end of the .then() call, like this:

- -
async function myFetch() {
-  let response = await fetch('coffee.jpg');
-  if (!response.ok) {
-    throw new Error(`HTTP error! status: ${response.status}`);
-  } else {
-    return await response.blob();
-  }
-}
-
-myFetch().then((blob) => {
-  let objectURL = URL.createObjectURL(blob);
-  let image = document.createElement('img');
-  image.src = objectURL;
-  document.body.appendChild(image);
-})
-.catch((e) =>
-  console.log(e)
-);
- -

This is because the .catch() block will catch errors occurring in both the async function call and the promise chain. If you used the try/catch block here, you might still get unhandled errors in the myFetch() function when it's called.

- -

You can find both of these examples on GitHub:

- - - -

Awaiting a Promise.all()

- -

async/await is built on top of promises, so it's compatible with all the features offered by promises. This includes Promise.all() — you can quite happily await a Promise.all() call to get all the results returned into a variable in a way that looks like simple synchronous code. Again, let's return to an example we saw in our previous article. Keep it open in a separate tab so you can compare and contrast with the new version shown below.

- -

Converting this to async/await (see live demo and source code), this now looks like so:

- -
async function fetchAndDecode(url, type) {
-  let response = await fetch(url);
-
-  let content;
-
-  if (!response.ok) {
-    throw new Error(`HTTP error! status: ${response.status}`);
-  } else {
-    if(type === 'blob') {
-      content = await response.blob();
-    } else if(type === 'text') {
-      content = await response.text();
-    }
-
-    return content;
-  }
-
-}
-
-async function displayContent() {
-  let coffee = fetchAndDecode('coffee.jpg', 'blob');
-  let tea = fetchAndDecode('tea.jpg', 'blob');
-  let description = fetchAndDecode('description.txt', 'text');
-
-  let values = await Promise.all([coffee, tea, description]);
-
-  let objectURL1 = URL.createObjectURL(values[0]);
-  let objectURL2 = URL.createObjectURL(values[1]);
-  let descText = values[2];
-
-  let image1 = document.createElement('img');
-  let image2 = document.createElement('img');
-  image1.src = objectURL1;
-  image2.src = objectURL2;
-  document.body.appendChild(image1);
-  document.body.appendChild(image2);
-
-  let para = document.createElement('p');
-  para.textContent = descText;
-  document.body.appendChild(para);
-}
-
-displayContent()
-.catch((e) =>
-  console.log(e)
-);
- -

You'll see that the fetchAndDecode() function has been converted easily into an async function with just a few changes. See the Promise.all() line:

- -
let values = await Promise.all([coffee, tea, description]);
- -

By using await here we are able to get all the results of the three promises returned into the values array, when they are all available, in a way that looks very much like sync code. We've had to wrap all the code in a new async function, displayContent(), and we've not reduced the code by a lot of lines, but being able to move the bulk of the code out of the .then() block provides a nice, useful simplification, leaving us with a much more readable program.

- -

For error handling, we've included a .catch() block on our displayContent() call; this will handle errors ocurring in both functions.

- -
-

Note: It is also possible to use a sync finally block within an async function, in place of a .finally() async block, to show a final report on how the operation went — you can see this in action in our live example (see also the source code).

-
- -

The downsides of async/await

- -

Async/await is really useful to know about, but there are a couple of downsides to consider.

- -

Async/await makes your code look synchronous, and in a way it makes it behave more synchronously. The await keyword blocks execution of all the code that follows until the promise fulfills, exactly as it would with a synchronous operation. It does allow other tasks to continue to run in the meantime, but your own code is blocked.

- -

This means that your code could be slowed down by a significant number of awaited promises happening straight after one another. Each await will wait for the previous one to finish, whereas actually what you want is for the promises to begin processing simultaneously, like they would do if we weren't using async/await.

- -

There is a pattern that can mitigate this problem — setting off all the promise processes by storing the Promise objects in variables, and then awaiting them all afterwards. Let's have a look at some examples that prove the concept.

- -

We've got two examples available — slow-async-await.html (see source code) and fast-async-await.html (see source code). Both of them start off with a custom promise function that fakes an async process with a setTimeout() call:

- -
function timeoutPromise(interval) {
-  return new Promise((resolve, reject) => {
-    setTimeout(function(){
-      resolve("done");
-    }, interval);
-  });
-};
- -

Then each one includes a timeTest() async function that awaits three timeoutPromise() calls:

- -
async function timeTest() {
-  ...
-}
- -

Each one ends by recording a start time, seeing how long the timeTest() promise takes to fulfill, then recording an end time and reporting how long the operation took in total:

- -
let startTime = Date.now();
-timeTest().then(() => {
-  let finishTime = Date.now();
-  let timeTaken = finishTime - startTime;
-  alert("Time taken in milliseconds: " + timeTaken);
-})
- -

It is the timeTest() function that differs in each case.

- -

In the slow-async-await.html example, timeTest() looks like this:

- -
async function timeTest() {
-  await timeoutPromise(3000);
-  await timeoutPromise(3000);
-  await timeoutPromise(3000);
-}
- -

Here we simply await all three timeoutPromise() calls directly, making each one alert for 3 seconds. Each subsequent one is forced to wait until the last one finished — if you run the first example, you'll see the alert box reporting a total run time of around 9 seconds.

- -

In the fast-async-await.html example, timeTest() looks like this:

- -
async function timeTest() {
-  const timeoutPromise1 = timeoutPromise(3000);
-  const timeoutPromise2 = timeoutPromise(3000);
-  const timeoutPromise3 = timeoutPromise(3000);
-
-  await timeoutPromise1;
-  await timeoutPromise2;
-  await timeoutPromise3;
-}
- -

Here we store the three Promise objects in variables, which has the effect of setting off their associated processes all running simultaneously.

- -

Next, we await their results — because the promises all started processing at essentially the same time, the promises will all fulfill at the same time; when you run the second example, you'll see the alert box reporting a total run time of just over 3 seconds!

- -

You'll have to test your code carefully, and bear this in mind if performance starts to suffer.

- -

Another minor inconvenience is that you have to wrap your awaited promises inside an async function.

- -

Async/await class methods

- -

As a final note before we move on, you can even add async in front of class/object methods to make them return promises, and await promises inside them. Take a look at the ES class code we saw in our object-oriented JavaScript article, and then look at our modified version with an async method:

- -
class Person {
-  constructor(first, last, age, gender, interests) {
-    this.name = {
-      first,
-      last
-    };
-    this.age = age;
-    this.gender = gender;
-    this.interests = interests;
-  }
-
-  async greeting() {
-    return await Promise.resolve(`Hi! I'm ${this.name.first}`);
-  };
-
-  farewell() {
-    console.log(`${this.name.first} has left the building. Bye for now!`);
-  };
-}
-
-let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
- -

The first class method could now be used something like this:

- -
han.greeting().then(console.log);
- -

Browser support

- -

One consideration when deciding whether to use async/await is support for older browsers. They are available in modern versions of most browsers, the same as promises; the main support problems come with Internet Explorer and Opera Mini.

- -

If you want to use async/await but are concerned about older browser support, you could consider using the BabelJS library — this allows you to write your applications using the latest JavaScript and let Babel figure out what changes if any are needed for your user’s browsers. On encountering a browser that does not support async/await, Babel's polyfill can automatically provide fallbacks that work in older browsers.

- -

Conclusion

- -

And there you have it — async/await provide a nice, simplified way to write async code that is simpler to read and maintain. Even with browser support being more limited than other async code mechanisms at the time of writing, it is well worth learning and considering for use, both for now and in the future.

- -

{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous/Choosing_the_right_approach", "Learn/JavaScript/Asynchronous")}}

- -

In this module

- - diff --git a/files/es/learn/javascript/building_blocks/events/index.html b/files/es/learn/javascript/building_blocks/events/index.html deleted file mode 100644 index 5fc7ee8df5..0000000000 --- a/files/es/learn/javascript/building_blocks/events/index.html +++ /dev/null @@ -1,579 +0,0 @@ ---- -title: Introducción a eventos -slug: Learn/JavaScript/Building_blocks/Events -translation_of: Learn/JavaScript/Building_blocks/Events -original_slug: Learn/JavaScript/Building_blocks/Eventos ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}
- -

Los eventos son acciones u ocurrencias que suceden en el sistema que está programando y que el sistema le informa para que pueda responder de alguna manera si lo desea. Por ejemplo, si el usuario hace clic en un botón en una página web, es posible que desee responder a esa acción mostrando un cuadro de información. En este artículo, discutiremos algunos conceptos importantes que rodean los eventos y veremos cómo funcionan en los navegadores. Este no será un estudio exhaustivo; solo lo que necesitas saber en esta etapa.

- - - - - - - - - - - - -
Prerrequisitos:Conocimientos básicos de informática, entendimiento básico de HTML y CSS, Primeros pasos con JavaScript.
Objetivo:Comprender la teoría fundamental de los eventos, cómo funcionan en los navegadores y cómo los eventos pueden diferir en distintos entornos de programación.
- -

Una serie de eventos afortunados

- -

Como se mencionó anteriormente, los eventos son acciones u ocurrencias que suceden en el sistema que está programando — el sistema disparará una señal de algún tipo cuando un evento ocurra y también proporcionará un mecanismo por el cual se puede tomar algún tipo de acción automáticamente (p.e., ejecutando algún código) cuando se produce el evento. Por ejemplo, en un aeropuerto cuando la pista está despejada para que despegue un avión, se comunica una señal al piloto y, como resultado, comienzan a pilotar el avión.

- -

- -

En el caso de la Web, los eventos se desencadenan dentro de la ventana del navegador y tienden a estar unidos a un elemento específico que reside en ella — podría ser un solo elemento, un conjunto de elementos, el documento HTML cargado en la pestaña actual o toda la ventana del navegador. Hay muchos tipos diferentes de eventos que pueden ocurrir, por ejemplo:

- - - -

Se deducirá de esto (y echar un vistazo a MDN Referencia de eventos) que hay muchos eventos a los que se puede responder.

- -

Cada evento disponible tiene un controlador de eventos, que es un bloque de código (generalmente una función JavaScript definida por el usuario) que se ejecutará cuando se active el evento. Cuando dicho bloque de código se define para ejecutarse en respuesta a un disparo de evento, decimos que estamos registrando un controlador de eventos. Tenga en cuenta que los controladores de eventos a veces se llaman oyentes de eventos — son bastante intercambiables para nuestros propósitos, aunque estrictamente hablando, trabajan juntos. El oyente escucha si ocurre el evento y el controlador es el código que se ejecuta en respuesta a que ocurra.

- -
-

Nota: Es útil tener en cuenta que los eventos web no son parte del lenguaje central de JavaScript: se definen como parte de las API integradas en el navegador.

-
- -

Un ejemplo simple

- -

Veamos un ejemplo simple para explicar lo que queremos decir aquí. Ya has visto eventos y controladores de eventos en muchos de los ejemplos de este curso, pero vamos a recapitular solo para consolidar nuestro conocimiento. En el siguiente ejemplo, tenemos un solo {{htmlelement ("button")}}, que cuando se presiona, hará que el fondo cambie a un color aleatorio:

- -
<button>Cambiar color</button>
- - - -

El JavaScript se ve así:

- -
const btn = document.querySelector('button');
-
-function random(number) {
-  return Math.floor(Math.random() * (number+1));
-}
-
-btn.onclick = function() {
-  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-}
- -

En este código, almacenamos una referencia al botón dentro de una variable llamada btn, usando la función {{domxref ("Document.querySelector ()")}}. También definimos una función que devuelve un número aleatorio. La tercera parte del código es el controlador de eventos. La variable btn apunta a un elemento <button>, y este tipo de objeto tiene una serie de eventos que pueden activarse y, por lo tanto, los controladores de eventos están disponibles. Estamos escuchando el disparo del evento "click", estableciendo la propiedad del controlador de eventos onclick para que sea igual a una función anónima que contiene código que generó un color RGB aleatorio y establece el <body> color de fondo igual a este.

- -

Este código ahora se ejecutará cada vez que se active el evento "click" en el elemento <button>, es decir, cada vez que un usuario haga clic en él.

- -

El resultado de ejemplo es el siguiente:

- -

{{ EmbedLiveSample('A_simple_example', '100%', 200, "", "", "hide-codepen-jsfiddle") }}

- -

No son solo páginas web

- -

Otra cosa que vale la pena mencionar en este punto es que los eventos no son particulares de JavaScript — la mayoría de los lenguajes de programación tienen algún tipo de modelo de eventos, y la forma en que funciona a menudo diferirá de la forma en que funciona en JavaScript. De hecho, el modelo de eventos en JavaScript para páginas web difiere del modelo de eventos para JavaScript, ya que se utiliza en otros entornos.

- -

Por ejemplo, Node.js es un entorno en tiempo de ejecución de JavaScript muy popular que permite a los desarrolladores usar JavaScript para crear aplicaciones de red y del lado del servidor. El modelo de eventos de Node.js se basa en que los oyentes (listeners) escuchen eventos y los emisores (emitters) emitan eventos periódicamente — no suena tan diferentes, pero el código es bastante diferente, haciendo uso de funciones como on() para registrar un oyente de eventos, y once() para registrar un oyente de eventos que anula el registro después de que se haya ejecutado una vez. The documentos de eventos de conexión HTTP proporcionan un buen ejemplo de uso.

- -

Como otro ejemplo, ahora también puede usar JavaScript para crear complementos de navegadores — mejoras de funcionalidad del navegador — utilizando una tecnología llamada WebExtensions. El modelo de eventos es similar al modelo de eventos web, pero un poco diferente — las propiedades de los oyentes de eventos se escriben en camel-case (ej. onMessage en lugar de onmessage), y deben combinarse con la función addListener. Consulte la página runtime.onMessage para ver un ejemplo.

- -

No necesita comprender nada sobre otros entornos en esta etapa de su aprendizaje; solo queríamos dejar en claro que los eventos pueden diferir en diferentes entornos de programación.

- -

Diferentes formas de uso de eventos

- -

Hay muchas maneras distintas en las que puedes agregar event listeners a los sitios web, que se ejecutara cuando el evento asociado se dispare. En esta sección, revisaremos los diferentes mecanismos y discutiremos cuales deberias usar..

- -

Propiedades de manejadores de eventos

- -

Estas son las propiedades que existen, que contienen codigo de manejadores de eventos(Event Handler)  que vemos frecuentemente durante el curso.. Volviendo al ejemplo de arriba:

- -
var btn = document.querySelector('button');
-
-btn.onclick = function() {
-  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-}
- -

La propiedad onclick es la propiedad del manejador de eventos que está siendo usada en esta situación. Es escencialmente una propiedad como cualquier otra disponible en el botón (por ejemplo: btn.textContent, or btn.style), pero es de un tipo especial — cuando lo configura para ser igual a algún código, ese código se ejecutará cuando el evento se dispare en el botón.

- -

You could also set the handler property to be equal to a named function name (like we saw in Build your own function). The following would work just the same:

- -
var btn = document.querySelector('button');
-
-function bgChange() {
-  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-}
-
-btn.onclick = bgChange;
- -

There are many different event handler properties available. Let's do an experiment.

- -

First of all, make a local copy of random-color-eventhandlerproperty.html, and open it in your browser. It's just a copy of the simple random color example we've been playing with already in this article. Now try changing btn.onclick to the following different values in turn, and observing the results in the example:

- - - -

Some events are very general and available nearly anywhere (for example an onclick handler can be registered on nearly any element), whereas some are more specific and only useful in certain situations (for example it makes sense to use onplay only on specific elements, such as {{htmlelement("video")}}).

- -

Inline event handlers — don't use these

- -

You might also see a pattern like this in your code:

- -
<button onclick="bgChange()">Press me</button>
-
- -
function bgChange() {
-  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-}
- -
-

Note: You can find the full source code for this example on GitHub (also see it running live).

-
- -

The earliest method of registering event handlers found on the Web involved event handler HTML attributes (aka inline event handlers) like the one shown above — the attribute value is literally the JavaScript code you want to run when the event occurs. The above example invokes a function defined inside a {{htmlelement("script")}} element on the same page, but you could also insert JavaScript directly inside the attribute, for example:

- -
<button onclick="alert('Hello, this is my old-fashioned event handler!');">Press me</button>
- -

You'll find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are just doing something really quick, but they very quickly become unmanageable and inefficient.

- -

For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to parse — keeping your JavaScript all in one place is better; if it is in a separate file you can apply it to multiple HTML documents.

- -

Even in a single file, inline event handlers are not a good idea. One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would very quickly turn into a maintenance nightmare. With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:

- -
var buttons = document.querySelectorAll('button');
-
-for (var i = 0; i < buttons.length; i++) {
-  buttons[i].onclick = bgChange;
-}
- -

Note that another option here would be to use the forEach() built-in method available on all Array objects:

- -
buttons.forEach(function(button) {
-  button.onclick = bgChange;
-});
- -
-

Note: Separating your programming logic from your content also makes your site more friendly to search engines.

-
- -

addEventListener() and removeEventListener()

- -

The newest type of event mechanism is defined in the Document Object Model (DOM) Level 2 Events Specification, which provides browsers with a new function — addEventListener(). This functions in a similar way to the event handler properties, but the syntax is obviously different. We could rewrite our random color example to look like this:

- -
var btn = document.querySelector('button');
-
-function bgChange() {
-  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-}
-
-btn.addEventListener('click', bgChange);
- -
-

Note: You can find the full source code for this example on GitHub (also see it running live).

-
- -

Inside the addEventListener() function, we specify two parameters — the name of the event we want to register this handler for, and the code that comprises the handler function we want to run in response to it. Note that it is perfectly appropriate to put all the code inside the addEventListener() function, in an anonymous function, like this:

- -
btn.addEventListener('click', function() {
-  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-});
- -

This mechanism has some advantages over the older mechanisms discussed earlier. For a start, there is a counterpart function, removeEventListener(), which removes a previously added listener. For example, this would remove the listener set in the first code block in this section:

- -
btn.removeEventListener('click', bgChange);
- -

This isn't significant for simple, small programs, but for larger, more complex programs it can improve efficiency to clean up old unused event handlers. Plus, for example, this allows you to have the same button performing different actions in different circumstances — all you've got to do is add/remove event handlers as appropriate.

- -

Second, you can also register multiple handlers for the same listener. The following two handlers would not be applied:

- -
myElement.onclick = functionA;
-myElement.onclick = functionB;
- -

As the second line would overwrite the value of onclick set by the first. This would work, however:

- -
myElement.addEventListener('click', functionA);
-myElement.addEventListener('click', functionB);
- -

Both functions would now run when the element is clicked.

- -

In addition, there are a number of other powerful features and options available with this event mechanism. These are a little out of scope for this article, but if you want to read up on them, have a look at the addEventListener() and removeEventListener() reference pages.

- -

What mechanism should I use?

- -

Of the three mechanisms, you definitely shouldn't use the HTML event handler attributes — these are outdated, and bad practice, as mentioned above.

- -

The other two are relatively interchangeable, at least for simple uses:

- - - -

The main advantages of the third mechanism are that you can remove event handler code if needed, using removeEventListener(), and you can add multiple listeners of the same type to elements if required. For example, you can call addEventListener('click', function() { ... }) on an element multiple times, with different functions specified in the second argument. This is impossible with event handler properties because any subsequent attempts to set a property will overwrite earlier ones, e.g.:

- -
element.onclick = function1;
-element.onclick = function2;
-etc.
- -
-

Note: If you are called upon to support browsers older than Internet Explorer 8 in your work, you may run into difficulties, as such ancient browsers use different event models from newer browsers. But never fear, most JavaScript libraries (for example jQuery) have built-in functions that abstract away cross-browser differences. Don't worry about this too much at this stage in your learning journey.

-
- -

Other event concepts

- -

In this section, we will briefly cover some advanced concepts that are relevant to events. It is not important to understand these fully at this point, but it might serve to explain some code patterns you'll likely come across from time to time.

- -

Event objects

- -

Sometimes inside an event handler function, you might see a parameter specified with a name such as event, evt, or simply e. This is called the event object, and it is automatically passed to event handlers to provide extra features and information. For example, let's rewrite our random color example again slightly:

- -
function bgChange(e) {
-  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  e.target.style.backgroundColor = rndCol;
-  console.log(e);
-}
-
-btn.addEventListener('click', bgChange);
- -
-

Note: You can find the full source code for this example on GitHub (also see it running live).

-
- -

Here you can see that we are including an event object, e, in the function, and in the function setting a background color style on e.target — which is the button itself. The target property of the event object is always a reference to the element that the event has just occurred upon. So in this example, we are setting a random background color on the button, not the page.

- -
-

Note: You can use any name you like for the event object — you just need to choose a name that you can then use to reference it inside the event handler function. e/evt/event are most commonly used by developers because they are short and easy to remember. It's always good to stick to a standard.

-
- -

e.target is incredibly useful when you want to set the same event handler on multiple elements and do something to all of them when an event occurs on them. You might, for example, have a set of 16 tiles that disappear when they are clicked on. It is useful to always be able to just set the thing to disappear as e.target, rather than having to select it in some more difficult way. In the following example (see useful-eventtarget.html for the full source code; also see it running live here), we create 16 {{htmlelement("div")}} elements using JavaScript. We then select all of them using {{domxref("document.querySelectorAll()")}}, then loop through each one, adding an onclick handler to each that makes it so that a random color is applied to each one when clicked:

- -
var divs = document.querySelectorAll('div');
-
-for (var i = 0; i < divs.length; i++) {
-  divs[i].onclick = function(e) {
-    e.target.style.backgroundColor = bgChange();
-  }
-}
- -

The output is as follows (try clicking around on it — have fun):

- - - -

{{ EmbedLiveSample('Hidden_example', '100%', 400, "", "", "hide-codepen-jsfiddle") }}

- -

Most event handlers you'll encounter just have a standard set of properties and functions (methods) available on the event object (see the {{domxref("Event")}} object reference for a full list). Some more advanced handlers, however, add specialist properties containing extra data that they need to function. The Media Recorder API, for example, has a dataavailable event, which fires when some audio or video has been recorded and is available for doing something with (for example saving it, or playing it back). The corresponding ondataavailable handler's event object has a data property available containing the recorded audio or video data to allow you to access it and do something with it.

- -

Preventing default behavior

- -

Sometimes, you'll come across a situation where you want to stop an event doing what it does by default. The most common example is that of a web form, for example, a custom registration form. When you fill in the details and press the submit button, the natural behaviour is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to a "success message" page of some kind (or the same page, if another is not specified.)

- -

The trouble comes when the user has not submitted the data correctly — as a developer, you'll want to stop the submission to the server and give them an error message telling them what's wrong and what needs to be done to put things right. Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks. Let's look at a simple example.

- -

First, a simple HTML form that requires you to enter your first and last name:

- -
<form>
-  <div>
-    <label for="fname">First name: </label>
-    <input id="fname" type="text">
-  </div>
-  <div>
-    <label for="lname">Last name: </label>
-    <input id="lname" type="text">
-  </div>
-  <div>
-     <input id="submit" type="submit">
-  </div>
-</form>
-<p></p>
- - - -

Now some JavaScript — here we implement a very simple check inside an onsubmit event handler (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty. If they are, we call the preventDefault() function on the event object — which stops the form submission — and then display an error message in the paragraph below our form to tell the user what's wrong:

- -
var form = document.querySelector('form');
-var fname = document.getElementById('fname');
-var lname = document.getElementById('lname');
-var submit = document.getElementById('submit');
-var para = document.querySelector('p');
-
-form.onsubmit = function(e) {
-  if (fname.value === '' || lname.value === '') {
-    e.preventDefault();
-    para.textContent = 'You need to fill in both names!';
-  }
-}
- -

Obviously, this is pretty weak form validation — it wouldn't stop the user validating the form with spaces or numbers entered into the fields, for example — but it is ok for example purposes. The output is as follows:

- -

{{ EmbedLiveSample('Preventing_default_behavior', '100%', 140, "", "", "hide-codepen-jsfiddle") }}

- -
-

Note: for the full source code, see preventdefault-validation.html (also see it running live here.)

-
- -

Event bubbling and capture

- -

The final subject to cover here is something that you'll not come across often, but it can be a real pain if you don't understand it. Event bubbling and capture are two mechanisms that describe what happens when two handlers of the same event type are activated on one element. Let's look at an example to make this easier — open up the show-video-box.html example in a new tab (and the source code in another tab.) It is also available live below:

- - - -

{{ EmbedLiveSample('Hidden_video_example', '100%', 500, "", "", "hide-codepen-jsfiddle") }}

- -

This is a pretty simple example that shows and hides a {{htmlelement("div")}} with a {{htmlelement("video")}} element inside it:

- -
<button>Display video</button>
-
-<div class="hidden">
-  <video>
-    <source src="rabbit320.mp4" type="video/mp4">
-    <source src="rabbit320.webm" type="video/webm">
-    <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
-  </video>
-</div>
- -

When the {{htmlelement("button")}} is clicked, the video is displayed, by changing the class attribute on the <div> from hidden to showing (the example's CSS contains these two classes, which position the box off the screen and on the screen, respectively):

- -
btn.onclick = function() {
-  videoBox.setAttribute('class', 'showing');
-}
- -

We then add a couple more onclick event handlers — the first one to the <div> and the second one to the <video>. The idea is that when the area of the <div> outside the video is clicked, the box should be hidden again; when the video itself is clicked, the video should start to play.

- -
videoBox.onclick = function() {
-  videoBox.setAttribute('class', 'hidden');
-};
-
-video.onclick = function() {
-  video.play();
-};
- -

But there's a problem — currently, when you click the video it starts to play, but it causes the <div> to also be hidden at the same time. This is because the video is inside the <div> — it is part of it — so clicking on the video actually runs both the above event handlers.

- -

Bubbling and capturing explained

- -

When an event is fired on an element that has parent elements (e.g. the {{htmlelement("video")}} in our case), modern browsers run two different phases — the capturing phase and the bubbling phase.

- -

In the capturing phase:

- - - -

In the bubbling phase, the exact opposite occurs:

- - - -

- -

(Click on image for bigger diagram)

- -

In modern browsers, by default, all event handlers are registered in the bubbling phase. So in our current example, when you click the video, the click event bubbles from the <video> element outwards to the <html> element. Along the way:

- - - -

Fixing the problem with stopPropagation()

- -

This is annoying behavior, but there is a way to fix it! The standard event object has a function available on it called stopPropagation(), which when invoked on a handler's event object makes it so that handler is run, but the event doesn't bubble any further up the chain, so no more handlers will be run.

- -

We can, therefore, fix our current problem by changing the second handler function in the previous code block to this:

- -
video.onclick = function(e) {
-  e.stopPropagation();
-  video.play();
-};
- -

You can try making a local copy of the show-video-box.html source code and having a go at fixing it yourself, or looking at the fixed result in show-video-box-fixed.html (also see the source code here).

- -
-

Note: Why bother with both capturing and bubbling? Well, in the bad old days when browsers were much less cross-compatible than they are now, Netscape only used event capturing, and Internet Explorer used only event bubbling. When the W3C decided to try to standardize the behavior and reach a consensus, they ended up with this system that included both, which is the one modern browsers implemented.

-
- -
-

Note: As mentioned above, by default all event handlers are registered in the bubbling phase, and this makes more sense most of the time. If you really want to register an event in the capturing phase instead, you can do so by registering your handler using addEventListener(), and setting the optional third property to true.

-
- -

Event delegation

- -

Bubbling also allows us to take advantage of event delegation — this concept relies on the fact that if you want some code to run when you click on any one of a large number of child elements, you can set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually. Remember earlier that we said bubbling involves checking the element the event is fired on for an event handler first, then moving up to the element's parent, etc.?

- -

A good example is a series of list items — if you want each one of them to pop up a message when clicked, you can set the click event listener on the parent <ul>, and events will bubble from the list items to the <ul>.

- -

This concept is explained further on David Walsh's blog, with multiple examples — see How JavaScript Event Delegation Works.

- -

Conclusion

- -

You should now know all you need to know about web events at this early stage. As mentioned above, events are not really part of the core JavaScript — they are defined in browser Web APIs.

- -

Also, it is important to understand that the different contexts in which JavaScript is used tend to have different event models — from Web APIs to other areas such as browser WebExtensions and Node.js (server-side JavaScript). We are not expecting you to understand all these areas now, but it certainly helps to understand the basics of events as you forge ahead with learning web development.

- -

If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

- -

See also

- - - -

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}

- -

In this module

- - diff --git a/files/es/learn/javascript/building_blocks/functions/index.html b/files/es/learn/javascript/building_blocks/functions/index.html deleted file mode 100644 index d05ae34969..0000000000 --- a/files/es/learn/javascript/building_blocks/functions/index.html +++ /dev/null @@ -1,400 +0,0 @@ ---- -title: Funciones — bloques de código reutilizables -slug: Learn/JavaScript/Building_blocks/Functions -tags: - - API - - Funciones - - JavaScript - - Métodos - - Navegador -translation_of: Learn/JavaScript/Building_blocks/Functions ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Looping_code","Learn/JavaScript/Building_blocks/Build_your_own_function", "Learn/JavaScript/Building_blocks")}}
- -

Otro concepto esencial en la codificación son las funciones, que te permiten almacenar un fragmento de código que realiza una única tarea dentro de un bloque definido, y luego llamar a ese código siempre que lo necesites utilizando un único comando breve -- en lugar de tener que escribir el mismo codigo varias veces. En este artículo exploraremos conceptos fundamentales detrás de funciones tales como sintaxis básica, cómo invocarlas y definirlas, alcance(scope) y parámetros.

- - - - - - - - - - - - -
Prerequisites:Conocimientos basicos de informatica, conocimiento basico de   HTML y CSS, JavaScript first steps.
Objective:Entender los conceptos fundamentales detras de las funciones JavaScript.
- -

¿Dónde encuentro las funciones? 

- -

En JavaScript vas a encontrar funciones por todos lados. De hecho, nosotros hemos usados funciones todo el tiempo a lo largo del curso; solo que no hemos hablado mucho sobre ellas. Ahora es el momento, igual, para comenzar a hablar explicitamente sobre las funciones y explorar su sintaxis.

- -

Básicamente cada vez que haces uso de código JavaScript que contiene parentesis como () y no estás usando estructuras de lenguaje como for loop, while, do, do while, estás usando una función! 

- -

Funciones incluídas en los navegadores

- -

A lo largo de este curso hemos usado muchas funciones incluídas del navegador. Por ejemplo, cuando manipulamos una cadena de texto o string:

- -
let miTexto = 'Soy una cadena de texto!';
-let nuevaCadena = miTexto.replace('cadena', 'ensalada');
-console.log(nuevaCadena);
-// la función de cadena de texto replace() toma una cadena,
-// reemplaza una palabra por otra, y devuelve
-// una nueva cadena con el reemplazo hecho.
- -

O cada vez que manipulamos un array:

- -
let miArray = ['Yo', 'amo', 'el', 'chocolate', 'y', 'las', 'ranas'];
-let armarCadena = miArray.join(' ');
-console.log(armarCadena);
-// La función join() toma un array,
-// une todos sus elementos en una cadena o string
-// y devuelve esta nueva cadena.
- -

O cada vez que generamos un número al azar:

- -
var miNumero = Math.random();
-console.log(miNumero);
-// La función Math.random() genera un número aleatorio
-// entre 0 and 1 y devuelve ese número.
-
- -

...estamos usando una función!

- -
-

Nota: Sientase libre de ingresar esas líneas de código en la consola JavaScript de su navegador, para familiarizarse con sus funcionalidades. 

-
- -

El lenguaje JavaScript contiene muchas funciones integradas que te permiten realizar cosas muy utilies sin escribir el código tu mismo. De hecho, parte del código que llamas (una palabra elegante para decir correr o ejecutar) cuando invocas una función integrada puede no estar escrita en JavaScript —muchas de estas funciones están llamando partes del código del navegador de fondo, que está escrito principalmente en lenguajes de sistema de bajo nivel como C ++, no en lenguajes web como JavaScript.

- -

Bear in mind that some built-in browser functions are not part of the core JavaScript language — some are defined as part of browser APIs, which build on top of the default language to provide even more functionality (refer to this early section of our course for more descriptions). We'll look at using browser APIs in more detail in a later module.

- -

Functions versus methods

- -

One thing we need to clear up before we move on — technically speaking, built in browser functions are not functions — they are methods. This sounds a bit scary and confusing, but don't worry — the words function and method are largely interchangeable, at least for our purposes, at this stage in your learning.

- -

The distinction is that methods are functions defined inside objects. Built-in browser functions (methods) and variables (which are called properties) are stored inside structured objects, to make the code more efficient and easier to handle.

- -

You don't need to learn about the inner workings of structured JavaScript objects yet — you can wait until our later module that will teach you all about the inner workings of objects, and how to create your own. For now, we just wanted to clear up any possible confusion of method versus function — you are likely to meet both terms as you look at the available related resources across the Web.

- -

Custom functions

- -

You've also seen a lot of custom functions in the course so far — functions defined in your code, not inside the browser. Anytime you saw a custom name with parentheses straight after it, you were using a custom function. In our random-canvas-circles.html example (see also the full source code) from our loops article, we included a custom draw() function that looked like this:

- -
function draw() {
-  ctx.clearRect(0,0,WIDTH,HEIGHT);
-  for (var i = 0; i < 100; i++) {
-    ctx.beginPath();
-    ctx.fillStyle = 'rgba(255,0,0,0.5)';
-    ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
-    ctx.fill();
-  }
-}
- -

This function draws 100 random circles inside an {{htmlelement("canvas")}} element. Every time we want to do that, we can just invoke the function with this

- -
draw();
- -

rather than having to write all that code out again every time we want to repeat it. And functions can contain whatever code you like — you can even call other functions from inside functions. The above function for example calls the random() function three times, which is defined by the following code:

- -
function random(number) {
-  return Math.floor(Math.random()*number);
-}
- -

We needed this function because the browser's built-in Math.random() function only generates a random decimal number between 0 and 1. We wanted a random whole number between 0 and a specified number.

- -

Invoking functions

- -

You are probably clear on this by now, but just in case ... to actually use a function after it has been defined, you've got to run — or invoke — it. This is done by including the name of the function in the code somewhere, followed by parentheses.

- -
function myFunction() {
-  alert('hello');
-}
-
-myFunction()
-// calls the function once
- -

Anonymous functions

- -

You may see functions defined and invoked in slightly different ways. So far we have just created a function like so:

- -
function myFunction() {
-  alert('hello');
-}
- -

But you can also create a function that doesn't have a name:

- -
function() {
-  alert('hello');
-}
- -

This is called an anonymous function — it has no name! It also won't do anything on its own. You generally use an anonymous function along with an event handler, for example the following would run the code inside the function whenever the associated button is clicked:

- -
var myButton = document.querySelector('button');
-
-myButton.onclick = function() {
-  alert('hello');
-}
- -

The above example would require there to be a {{htmlelement("button")}} element available on the page to select and click. You've already seen this structure a few times throughout the course, and you'll learn more about and see it in use in the next article.

- -

You can also assign an anonymous function to be the value of a variable, for example:

- -
var myGreeting = function() {
-  alert('hello');
-}
- -

This function could now be invoked using:

- -
myGreeting();
- -

This effectively gives the function a name; you can also assign the function to be the value of multiple variables, for example:

- -
var anotherGreeting = function() {
-  alert('hello');
-}
- -

This function could now be invoked using either of

- -
myGreeting();
-anotherGreeting();
- -

But this would just be confusing, so don't do it! When creating functions, it is better to just stick to this form:

- -
function myGreeting() {
-  alert('hello');
-}
- -

You will mainly use anonymous functions to just run a load of code in response to an event firing — like a button being clicked — using an event handler. Again, this looks something like this:

- -
myButton.onclick = function() {
-  alert('hello');
-  // I can put as much code
-  // inside here as I want
-}
- -

Function parameters

- -

Some functions require parameters to be specified when you are invoking them — these are values that need to be included inside the function parentheses, which it needs to do its job properly.

- -
-

Note: Parameters are sometimes called arguments, properties, or even attributes.

-
- -

As an example, the browser's built-in Math.random() function doesn't require any parameters. When called, it always returns a random number between 0 and 1:

- -
var myNumber = Math.random();
- -

The browser's built-in string replace() function however needs two parameters — the substring to find in the main string, and the substring to replace that string with:

- -
var myText = 'I am a string';
-var newString = myText.replace('string', 'sausage');
- -
-

Note: When you need to specify multiple parameters, they are separated by commas.

-
- -

It should also be noted that sometimes parameters are optional — you don't have to specify them. If you don't, the function will generally adopt some kind of default behavior. As an example, the array join() function's parameter is optional:

- -
var myArray = ['I', 'love', 'chocolate', 'frogs'];
-var madeAString = myArray.join(' ');
-// returns 'I love chocolate frogs'
-var madeAString = myArray.join();
-// returns 'I,love,chocolate,frogs'
- -

If no parameter is included to specify a joining/delimiting character, a comma is used by default.

- -

Function scope and conflicts

- -

Let's talk a bit about {{glossary("scope")}} — a very important concept when dealing with functions. When you create a function, the variables and other things defined inside the function are inside their own separate scope, meaning that they are locked away in their own separate compartments, unreachable from inside other functions or from code outside the functions.

- -

The top level outside all your functions is called the global scope. Values defined in the global scope are accessible from everywhere in the code.

- -

JavaScript is set up like this for various reasons — but mainly because of security and organization. Sometimes you don't want variables to be accessible from everywhere in the code — external scripts that you call in from elsewhere could start to mess with your code and cause problems because they happen to be using the same variable names as other parts of the code, causing conflicts. This might be done maliciously, or just by accident.

- -

For example, say you have an HTML file that is calling in two external JavaScript files, and both of them have a variable and a function defined that use the same name:

- -
<!-- Excerpt from my HTML -->
-<script src="first.js"></script>
-<script src="second.js"></script>
-<script>
-  greeting();
-</script>
- -
// first.js
-var name = 'Chris';
-function greeting() {
-  alert('Hello ' + name + ': welcome to our company.');
-}
- -
// second.js
-var name = 'Zaptec';
-function greeting() {
-  alert('Our company is called ' + name + '.');
-}
- -

Both functions you want to call are called greeting(), but you can only ever access the second.js file's greeting() function — it is applied to the HTML later on in the source code, so its variable and function overwrite the ones in first.js.

- -
-

Note: You can see this example running live on GitHub (see also the source code).

-
- -

Keeping parts of your code locked away in functions avoids such problems, and is considered best practice.

- -

It is a bit like a zoo. The lions, zebras, tigers, and penguins are kept in their own enclosures, and only have access to the things inside their enclosures — in the same manner as the function scopes. If they were able to get into other enclosures, problems would occur. At best, different animals would feel really uncomfortable inside unfamiliar habitats — a lion or tiger would feel terrible inside the penguins' watery, icy domain. At worst, the lions and tigers might try to eat the penguins!

- -

- -

The zoo keeper is like the global scope — he or she has the keys to access every enclosure, to restock food, tend to sick animals, etc.

- -

Active learning: Playing with scope

- -

Let's look at a real example to demonstrate scoping.

- -
    -
  1. First, make a local copy of our function-scope.html example. This contains two functions called a() and b(), and three variables — x, y, and z — two of which are defined inside the functions, and one in the global scope. It also contains a third function called output(), which takes a single parameter and outputs it in a paragraph on the page.
  2. -
  3. Open the example up in a browser and in your text editor.
  4. -
  5. Open the JavaScript console in your browser developer tools. In the JavaScript console, enter the following command: -
    output(x);
    - You should see the value of variable x output to the screen.
  6. -
  7. Now try entering the following in your console -
    output(y);
    -output(z);
    - Both of these should return an error along the lines of "ReferenceError: y is not defined". Why is that? Because of function scope — y and z are locked inside the a() and b() functions, so output() can't access them when called from the global scope.
  8. -
  9. However, what about when it's called from inside another function? Try editing a() and b() so they look like this: -
    function a() {
    -  var y = 2;
    -  output(y);
    -}
    -
    -function b() {
    -  var z = 3;
    -  output(z);
    -}
    - Save the code and reload it in your browser, then try calling the a() and b() functions from the JavaScript console: - -
    a();
    -b();
    - You should see the y and z values output in the page. This works fine, as the output() function is being called inside the other functions — in the same scope as the variables it is printing are defined in, in each case. output() itself is available from anywhere, as it is defined in the global scope.
  10. -
  11. Now try updating your code like this: -
    function a() {
    -  var y = 2;
    -  output(x);
    -}
    -
    -function b() {
    -  var z = 3;
    -  output(x);
    -}
    - Save and reload again, and try this again in your JavaScript console: - -
    a();
    -b();
    - Both the a() and b() call should output the value of x — 1. These work fine because even though the output() calls are not in the same scope as x is defined in, x is a global variable so is available inside all code, everywhere.
  12. -
  13. Finally, try updating your code like this: -
    function a() {
    -  var y = 2;
    -  output(z);
    -}
    -
    -function b() {
    -  var z = 3;
    -  output(y);
    -}
    - Save and reload again, and try this again in your JavaScript console: - -
    a();
    -b();
    - This time the a() and b() calls will both return that annoying "ReferenceError: z is not defined" error — this is because the output() calls and the variables they are trying to print are not defined inside the same function scopes — the variables are effectively invisible to those function calls.
  14. -
- -
-

Note: The same scoping rules do not apply to loop (e.g. for() { ... }) and conditional blocks (e.g. if() { ... }) — they look very similar, but they are not the same thing! Take care not to get these confused.

-
- -
-

Note: The ReferenceError: "x" is not defined error is one of the most common you'll encounter. If you get this error and you are sure that you have defined the variable in question, check what scope it is in.

-
- - - -

Functions inside functions

- -

Keep in mind that you can call a function from anywhere, even inside another function.  This is often used as a way to keep code tidy — if you have a big complex function, it is easier to understand if you break it down into several sub-functions:

- -
function myBigFunction() {
-  var myValue;
-
-  subFunction1();
-  subFunction2();
-  subFunction3();
-}
-
-function subFunction1() {
-  console.log(myValue);
-}
-
-function subFunction2() {
-  console.log(myValue);
-}
-
-function subFunction3() {
-  console.log(myValue);
-}
-
- -

Just make sure that the values being used inside the function are properly in scope. The example above would throw an error ReferenceError: myValue is not defined, because although the myValue variable is defined in the same scope as the function calls, it is not defined inside the function definitions — the actual code that is run when the functions are called. To make this work, you'd have to pass the value into the function as a parameter, like this:

- -
function myBigFunction() {
-  var myValue = 1;
-
-  subFunction1(myValue);
-  subFunction2(myValue);
-  subFunction3(myValue);
-}
-
-function subFunction1(value) {
-  console.log(value);
-}
-
-function subFunction2(value) {
-  console.log(value);
-}
-
-function subFunction3(value) {
-  console.log(value);
-}
- -

Conclusion

- -

This article has explored the fundamental concepts behind functions, paving the way for the next one in which we get practical and take you through the steps to building up your own custom function.

- -

See also

- - - - - -

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Looping_code","Learn/JavaScript/Building_blocks/Build_your_own_function", "Learn/JavaScript/Building_blocks")}}

- -

In this module

- - -<gdiv></gdiv> diff --git a/files/es/learn/javascript/building_blocks/image_gallery/index.html b/files/es/learn/javascript/building_blocks/image_gallery/index.html deleted file mode 100644 index a4bad1842e..0000000000 --- a/files/es/learn/javascript/building_blocks/image_gallery/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Galería de imágenes -slug: Learn/JavaScript/Building_blocks/Image_gallery -translation_of: Learn/JavaScript/Building_blocks/Image_gallery -original_slug: Learn/JavaScript/Building_blocks/Galeria_de_imagenes ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}
- -

Ahora que hemos analizado los bloques de construcción fundamentales de JavaScript, pongamos a prueba tu conocimiento de bucles, funciones, condicionales y eventos, creando un elemento que comumente vemos en muchos sitios web, una Galería de imágenes "motorizada" por JavaScript .

- - - - - - - - - - - - -
Prerequisitos:Antes de intentar esta evaluación deberías de haber trabajado con todos los artículos en éste módulo.
Objetivo:Evaluar la comprensión de los bucles, funciones, condicionales y eventos de JavaScript..
- -

Punto de partida

- -

Para realizar esta evaluación, debería descárgarse archivoZip para el ejemplo, descomprímalo en algún lugar de su computadora y haga el ejercicio localmente para empezar.

- -

Opcionalmente, puedes usar un sitio como JSBin o Glitch para realizar tu evaluación. Puede pegar el HTML, CSS y JavaScript dentro de uno de estos editores online. Si el editor en línea que está utilizando no tiene paneles JavaScript / CSS separados, siéntase libre de ponerlos en línea <script> / <style> elementos dentro de la página HTML.

- -
-

Nota: Si se atascascas con algo, entonces pregúntenos para ayudarlo — vea la sección de {{anch("evaluación o ayuda adicional")}} al final de esta página.

-
- -

Resumen del proyecto

- -

Ha sido provisto con algún contenido de HTML, CSS e imágenes, también algunas líneas de código en JavaScript; necesitas escribir las líneas de código en JavaScript necesatio para transformarse en un programa funcional. El  HTML body luce así:

- -
<h1>Image gallery example</h1>
-
-<div class="full-img">
-  <img class="displayed-img" src="images/pic1.jpg">
-  <div class="overlay"></div>
-  <button class="dark">Darken</button>
-</div>
-
-<div class="thumb-bar">
-
-</div>
- -

El ejemplo se ve así:

- -

- - - -

Las partes más interesantes del archivo example's CSS :

- - - -

Your JavaScript needs to:

- - - -

To give you more of an idea, have a look at the finished example (no peeking at the source code!)

- -

Steps to complete

- -

The following sections describe what you need to do.

- -

Looping through the images

- -

We've already provided you with lines that store a reference to the thumb-bar <div> inside a constant called thumbBar, create a new <img> element, set its src attribute to a placeholder value xxx, and append this new <img> element inside thumbBar.

- -

You need to:

- -
    -
  1. Put the section of code below the "Looping through images" comment inside a loop that loops through all 5 images — you just need to loop through five numbers, one representing each image.
  2. -
  3. In each loop iteration, replace the xxx placeholder value with a string that will equal the path to the image in each case. We are setting the value of the src attribute to this value in each case. Bear in mind that in each case, the image is inside the images directory and its name is pic1.jpg, pic2.jpg, etc.
  4. -
- -

Adding an onclick handler to each thumbnail image

- -

In each loop iteration, you need to add an onclick handler to the current newImage — this handler should find the value of the src attribute of the current image. Set the src attribute value of the displayed-img <img> to the src value passed in as a parameter.

- -

Writing a handler that runs the darken/lighten button

- -

That just leaves our darken/lighten <button> — we've already provided a line that stores a reference to the <button> in a constant called btn. You need to add an onclick handler that:

- -
    -
  1. Checks the current class name set on the <button> — you can again achieve this by using getAttribute().
  2. -
  3. If the class name is "dark", changes the <button> class to "light" (using setAttribute()), its text content to "Lighten", and the {{cssxref("background-color")}} of the overlay <div> to "rgba(0,0,0,0.5)".
  4. -
  5. If the class name not "dark", changes the <button> class to "dark", its text content back to "Darken", and the {{cssxref("background-color")}} of the overlay <div> to "rgba(0,0,0,0)".
  6. -
- -

The following lines provide a basis for achieving the changes stipulated in points 2 and 3 above.

- -
btn.setAttribute('class', xxx);
-btn.textContent = xxx;
-overlay.style.backgroundColor = xxx;
- -

Hints and tips

- - - -

Assessment or further help

- -

If you would like your work assessed, or are stuck and want to ask for help:

- -
    -
  1. Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch.
  2. -
  3. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: -
      -
    • A descriptive title such as "Assessment wanted for Image gallery".
    • -
    • Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment.
    • -
    • A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code.
    • -
    • A link to the actual task or assessment page, so we can find the question you want help with.
    • -
    -
  4. -
- -

{{PreviousMenu("Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}

- -

In this module

- - diff --git a/files/es/learn/server-side/django/django_assessment_blog/index.html b/files/es/learn/server-side/django/django_assessment_blog/index.html deleted file mode 100644 index cb5ac7ad88..0000000000 --- a/files/es/learn/server-side/django/django_assessment_blog/index.html +++ /dev/null @@ -1,307 +0,0 @@ ---- -title: 'Evaluación: DIY Django mini blog' -slug: Learn/Server-side/Django/django_assessment_blog -translation_of: Learn/Server-side/Django/django_assessment_blog ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}}
- -

En esta evaluación usarás el conocimiento de Django que has adquirido en el módulo Framework Web Django (Python) para crear un blog muy básico.

- - - - - - - - - - - - -
Requisitos Previos:Before attempting this assessment you should have already worked through all the articles in this module.
Objetivo:Comprender los fundamentos de Django , incluidos las configuraciones de URL , modelos, vistas, formularios y  templates.
- -

Resumen del proyecto

- -

Las paginas que necesitan ser mostradas, sus URLs, y otros requisitos son listados debajo: 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PaginaURLRequisitos
Home page/ and /blog/Una pagina inicial que describa el sitio
Lista de todos las publicaciones del blog/blog/blogs/ -

Lista de todos las publicaciones del blog:

- -
    -
  • Accessible to all users from a sidebar link.
  • -
  • List sorted by post date (newest to oldest).
  • -
  • List paginated in groups of 5 articles.
  • -
  • List items display the blog title, post date, and author.
  • -
  • Blog post names are linked to blog detail pages.
  • -
  • Blogger (author names) are linked to blog author detail pages.
  • -
-
Blog autor (blogger) pagina de detalles/blog/blogger/<author-id> -

Information for a specified author (by id) and list of their blog posts:

- -
    -
  • Accessible to all users from author links in blog posts etc.
  • -
  • Contains some biographical information about the blogger/author.
  • -
  • List sorted by post date (newest to oldest).
  • -
  • Not paginated.
  • -
  • List items display just the blog post name and post date.
  • -
  • Blog post names are linked to blog detail pages.
  • -
-
Blog post detail page/blog/<blog-id> -

Blog post details.

- -
    -
  • Accessible to all users from blog post lists.
  • -
  • Page contains the blog post: name, author, post date, and content.
  • -
  • Comments for the blog post should be displayed at bottom.
  • -
  • Comments should be sorted in order: oldest to most recent.
  • -
  • Contains link to add comments at end for logged in users (see Comment form page)
  • -
  • Blog posts and comments need only display plain text. There is no need to support any sort of HTML markup (e.g. links, images, bold/italic, etc).
  • -
-
List of all bloggers/blog/bloggers/ -

List of bloggers on system:

- -
    -
  • Accessible to all users from site sidebar
  • -
  • Blogger names are linked to Blog author detail pages.
  • -
-
Comment form page/blog/<blog-id>/create -

Create comment for blog post:

- -
    -
  • Accessible to logged-in users (only) from link at bottom of blog post detail pages.
  • -
  • Displays form with description for entering comments (post date and blog is not editable).
  • -
  • After a comment has been posted, the page will redirect back to the associated blog post page.
  • -
  • Users cannot edit or delete their posts.
  • -
  • Logged out users will be directed to the login page to log in, before they can add comments. After logging in, they will be redirected back to the blog page they wanted to comment on.
  • -
  • Comment pages should include the name/link to the blogpost being commented on.
  • -
-
User authentication pages/accounts/<standard urls> -

Standard Django authentication pages for logging in, out and setting the password:

- -
    -
  • Login/out should be accessible via sidebar links.
  • -
-
Admin site/admin/<standard urls> -

Admin site should be enabled to allow create/edit/delete of blog posts, blog authors and blog comments (this is the mechanism for bloggers to create new blog posts):

- -
    -
  • Admin site blog posts records should display the list of associated comments inline (below each blog post).
  • -
  • Comment names in the Admin site are created by truncating the comment description to 75 characters.
  • -
  • Other types of records can use basic registration.
  • -
-
- -

In addition you should write some basic tests to verify:

- - - -
-

Note: There are of course many other tests you can run. Use your discretion, but we'll expect you to do at least the tests above.

-
- -

The following section shows screenshots of a site that implements the requirements above.

- -

Screenshots

- -

The following screenshot provide an example of what the finished program should output.

- -

List of all blog posts

- -

This displays the list of all blog posts (accessible from the "All blogs" link in the sidebar). Things to note:

- - - -

List of all blogs

- -

List of all bloggers

- -

This provides links to all bloggers, as linked from the "All bloggers" link in the sidebar. In this case we can see from the sidebar that no user is logged in.

- -

List of all bloggers

- -

Blog detail page

- -

This shows the detail page for a particular blog.

- -

Blog detail with add comment link

- -

Note that the comments have a date and time, and are ordered from oldest to newest (opposite of blog ordering). At the end we have a link for accessing the form to add a new comment. If a user is not logged in we'd instead see a suggestion to log in.

- -

Comment link when not logged in

- -

Add comment form

- -

This is the form to add comments. Note that we're logged in. When this succeeds we should be taken back to the associated blog post page.

- -

Add comment form

- -

Author bio

- -

This displays bio information for a blogger along with their blog posts list.

- -

Blogger detail page

- -

Steps to complete

- -

The following sections describe what you need to do.

- -
    -
  1. Create a skeleton project and web application for the site (as described in Django Tutorial Part 2: Creating a skeleton website). You might use 'diyblog' for the project name and 'blog' for the application name.
  2. -
  3. Create models for the Blog posts, Comments, and any other objects needed. When thinking about your design, remember: -
      -
    • Each comment will have only one blog, but a blog may have many comments.
    • -
    • Blog posts and comments must be sorted by post date.
    • -
    • Not every user will necessarily be a blog author though any user may be a commenter.
    • -
    • Blog authors must also include bio information.
    • -
    -
  4. -
  5. Run migrations for your new models and create a superuser.
  6. -
  7. Use the admin site to create some example blog posts and blog comments.
  8. -
  9. Create views, templates, and URL configurations for blog post and blogger list pages.
  10. -
  11. Create views, templates, and URL configurations for blog post and blogger detail pages.
  12. -
  13. Create a page with a form for adding new comments (remember to make this only available to logged in users!)
  14. -
- -

Hints and tips

- -

This project is very similar to the LocalLibrary tutorial. You will be able to set up the skeleton, user login/logout behaviour, support for static files, views, URLs, forms, base templates and admin site configuration using almost all the same approaches.

- -

Some general hints:

- -
    -
  1. The index page can be implemented as a basic function view and template (just like for the locallibrary).
  2. -
  3. The list view for blog posts and bloggers, and the detail view for blog posts can be created using the generic list and detail views.
  4. -
  5. The list of blog posts for a particular author can be created by using a generic list Blog list view and filtering for blog object that match the specified author. -
      -
    • You will have to implement get_queryset(self) to do the filtering (much like in our library class LoanedBooksAllListView) and get the author information from the URL.
    • -
    • You will also need to pass the name of the author to the page in the context. To do this in a class-based view you need to implement get_context_data() (discussed below).
    • -
    -
  6. -
  7. The add comment form can be created using a function-based view (and associated model and form) or using a generic CreateView. If you use a CreateView (recommended) then: -
      -
    • You will also need to pass the name of the blog post to the comment page in the context (implement get_context_data() as discussed below).
    • -
    • The form should only display the comment "description" for user entry (date and associated blog post should not be editable). Since they won't be in the form itself, your code will need to set the comment's author in the form_valid() function so it can be saved into the model (as described here — Django docs). In that same function we set the associated blog. A possible implementation is shown below (pk is a blog id passed in from the URL/URL configuration). -
          def form_valid(self, form):
      -        """
      -        Add author and associated blog to form data before setting it as valid (so it is saved to model)
      -        """
      -        #Add logged-in user as author of comment
      -        form.instance.author = self.request.user
      -        #Associate comment with blog based on passed id
      -        form.instance.blog=get_object_or_404(Blog, pk = self.kwargs['pk'])
      -        # Call super-class form validation behaviour
      -        return super(BlogCommentCreate, self).form_valid(form)
      -
      -
    • -
    • You will need to provide a success URL to redirect to after the form validates; this should be the original blog. To do this you will need to override get_success_url() and "reverse" the URL for the original blog. You can get the required blog ID using the self.kwargs attribute, as shown in the form_valid() method above.
    • -
    -
  8. -
- -

We briefly talked about passing a context to the template in a class-based view in the Django Tutorial Part 6: Generic list and detail views topic. To do this you need to override get_queryset() (first getting the existing context, updating it with whatever additional variables you want to pass to the template, and then returning the updated context. For example, the code fragment below shows how you can add a blogger object to the context based on their BlogAuthor id.

- -
class SomeView(generic.ListView):
-    ...
-
-    def get_context_data(self, **kwargs):
-        # Call the base implementation first to get a context
-        context = super(SomeView, self).get_context_data(**kwargs)
-        # Get the blogger object from the "pk" URL parameter and add it to the context
-        context['blogger'] = get_object_or_404(BlogAuthor, pk = self.kwargs['pk'])
-        return context
-
- -

Assessment

- -

The assessment for this task is available on Github here. This assessment is primarily based on how well your application meets the requirements we listed above, though there are some parts of the assessment that check your code uses appropriate models, and that you have written at least some test code. When you're done, you can check out our the finished example which reflects a "full marks" project.

- -

Once you've completed this module you've also finished all the MDN content for learning basic Django server-side website programming! We hope you enjoyed this module and feel you have a good grasp of the basics!

- -

{{PreviousMenu("Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}}

- -

 

- -

En este modulo

- - diff --git a/files/es/learn/server-side/django/web_application_security/index.html b/files/es/learn/server-side/django/web_application_security/index.html deleted file mode 100644 index e00a1771bb..0000000000 --- a/files/es/learn/server-side/django/web_application_security/index.html +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Seguridad de las aplicaciones web Django -slug: Learn/Server-side/Django/web_application_security -translation_of: Learn/Server-side/Django/web_application_security ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Django/Deployment", "Learn/Server-side/Django/django_assessment_blog", "Learn/Server-side/Django")}}
- -

Proteger los datos de los usuarios es una parte esencial de cualquier diseño de un sitio web. Previamente ya explicamos algunas de las amenazas de seguridad más comunes en el artículo Seguridad Web — este artículo proporciona una demostración práctica de cómo las protecciones integradas de Django gestionan estas amenazas.

- - - - - - - - - - - - -
Prerrequisitos:Lee la documentación de la Programación del Lado del servidor "Seguridad de la aplicación web de Django". Completa todos los temas del Tutorial de Django (incluyendo este) o por lo menos el Tutorial de Django Parte 9: Trabajar con formularios web.
Objetivo:Comprender las cosas principales que debes hacer (y las que no debes) para proteger su aplicación web de Django.
- -

Overview

- -

The Website security topic provides an overview of what website security means for server-side design, and some of the more common threats that you may need to protect against. One of the key messages in that article is that almost all attacks are successful when the web application trusts data from the browser.

- -
-

Important: The single most important lesson you can learn about website security is to never trust data from the browser. This includes GET request data in URL parameters, POST data, HTTP headers and cookies, user-uploaded files, etc. Always check and sanitize all incoming data. Always assume the worst.

-
- -

The good news for Django users is that many of the more common threats are handled by the framework! The Security in Django (Django docs) article explains Django's security features and how to secure a Django-powered website.

- -

Common threats/protections

- -

Rather than duplicate the Django documentation here, in this article we'll demonstrate just a few of the security features in the context of our Django LocalLibrary tutorial.

- -

Cross site scripting (XSS)

- -

XSS is a term used to describe a class of attacks that allow an attacker to inject client-side scripts through the website into the browsers of other users. This is usually achieved by storing malicious scripts in the database where they can be retrieved and displayed to other users, or by getting users to click a link that will cause the attacker’s JavaScript to be executed by the user’s browser.

- -

Django's template system protects you against the majority of XSS attacks by escaping specific characters that are "dangerous" in HTML. We can demonstrate this by attempting to inject some JavaScript into our LocalLibrary website using the Create-author form we set up in Django Tutorial Part 9: Working with forms.

- -
    -
  1. Start the website using the development server (python3 manage.py runserver).
  2. -
  3. Open the site in your local browser and login to your superuser account.
  4. -
  5. Navigate to the author-creation page (which should be at URL: http://127.0.0.1:8000/catalog/author/create/).
  6. -
  7. Enter names and date details for a new user, and then append the following text to the Last Name field:
    - <script>alert('Test alert');</script>.
    - Author Form XSS test -
    -

    Note: This is a harmless script that, if executed, will display an alert box in your browser. If the alert is displayed when you submit the record then the site is vulnerable to XSS threats.

    -
    -
  8. -
  9. Press Submit to save the record.
  10. -
  11. When you save the author it will be displayed as shown below. Because of the XSS protections the alert() should not be run. Instead the script is displayed as plain text.Author detail view XSS test
  12. -
- -

If you view the page HTML source code, you can see that the dangerous characters for the script tags have been turned into their harmless escape code equivalents (e.g. > is now &gt;)

- -
<h1>Author: Boon&lt;script&gt;alert(&#39;Test alert&#39;);&lt;/script&gt;, David (Boonie) </h1>
-
- -

Using Django templates protects you against the majority of XSS attacks. However it is possible to turn off this protection, and the protection isn't automatically applied to all tags that wouldn't normally be populated by user input (for example, the help_text in a form field is usually not user-supplied, so Django doesn't escape those values).

- -

It is also possible for XSS attacks to originate from other untrusted source of data, such as cookies, Web services or uploaded files (whenever the data is not sufficiently sanitized before including in a page). If you're displaying data from these sources, then you may need to add your own sanitisation code.

- -

Cross site request forgery (CSRF) protection

- -

CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user’s knowledge or consent. For example consider the case where we have a hacker who wants to create additional authors for our LocalLibrary.

- -
-

Note: Obviously our hacker isn't in this for the money! A more ambitious hacker could use the same approach on other sites to perform much more harmful tasks (e.g. transfer money to their own accounts, etc.)

-
- -

In order to do this, they might create an HTML file like the one below, which contains an author-creation form (like the one we used in the previous section) that is submitted as soon as the file is loaded. They would then send the file to all the Librarians and suggest that they open the file (it contains some harmless information, honest!). If the file is opened by any logged in librarian, then the form would be submitted with their credentials and a new author would be created.

- -
<html>
-<body onload='document.EvilForm.submit()'>
-
-<form action="http://127.0.0.1:8000/catalog/author/create/" method="post" name='EvilForm'>
-  <table>
-    <tr><th><label for="id_first_name">First name:</label></th><td><input id="id_first_name" maxlength="100" name="first_name" type="text" value="Mad" required /></td></tr>
-    <tr><th><label for="id_last_name">Last name:</label></th><td><input id="id_last_name" maxlength="100" name="last_name" type="text" value="Man" required /></td></tr>
-    <tr><th><label for="id_date_of_birth">Date of birth:</label></th><td><input id="id_date_of_birth" name="date_of_birth" type="text" /></td></tr>
-    <tr><th><label for="id_date_of_death">Died:</label></th><td><input id="id_date_of_death" name="date_of_death" type="text" value="12/10/2016" /></td></tr>
-  </table>
-  <input type="submit" value="Submit" />
-</form>
-
-</body>
-</html>
-
- -

Run the development web server, and log in with your superuser account. Copy the text above into a file and then open it in the browser. You should get a CSRF error, because Django has protection against this kind of thing!

- -

The way the protection is enabled is that you include the {% csrf_token %} template tag in your form definition. This token is then rendered in your HTML as shown below, with a value that is specific to the user on the current browser.

- -
<input type='hidden' name='csrfmiddlewaretoken' value='0QRWHnYVg776y2l66mcvZqp8alrv4lb8S8lZ4ZJUWGZFA5VHrVfL2mpH29YZ39PW' />
-
- -

Django generates a user/browser specific key and will reject forms that do not contain the field, or that contain an incorrect field value for the user/browser.

- -

To use this type of attack the hacker now has to discover and include the CSRF key for the specific target user. They also can't use the "scattergun" approach of sending a malicious file to all librarians and hoping that one of them will open it, since the CSRF key is browser specific.

- -

Django's CSRF protection is turned on by default. You should always use the {% csrf_token %} template tag in your forms and use POST for requests that might change or add data to the database.

- -

Other protections

- -

Django also provides other forms of protection (most of which would be hard or not particularly useful to demonstrate):

- -
-
SQL injection protection
-
SQL injection vulnerabilities enable malicious users to execute arbitrary SQL code on a database, allowing data to be accessed, modified, or deleted irrespective of the user's permissions. In almost every case you'll be accessing the database using Django’s querysets/models, so the resulting SQL will be properly escaped by the underlying database driver. If you do need to write raw queries or custom SQL then you'll need to explicitly think about preventing SQL injection.
-
Clickjacking protection
-
In this attack a malicious user hijacks clicks meant for a visible top level site and routes them to a hidden page beneath. This technique might be used, for example, to display a legitimate bank site but capture the login credentials in an invisible <iframe> controlled by the attacker. Django contains clickjacking protection in the form of the X-Frame-Options middleware which, in a supporting browser, can prevent a site from being rendered inside a frame.
-
Enforcing SSL/HTTPS
-
SSL/HTTPS can be enabled on the web server in order to encrypt all traffic between the site and browser, including authentication credentials that would otherwise be sent in plain text (enabling HTTPS is highly recommended). If HTTPS is enabled then Django provides a number of other protections you can use:
-
- - - -
-
Host header validation
-
Use ALLOWED_HOSTS to only accept requests from trusted hosts.
-
- -

There are many other protections, and caveats to the usage of the above mechanisms. While we hope that this has given you an overview of what Django offers, you should still read the Django security documentation.

- - - -

Summary

- -

Django has effective protections against a number of common threats, including XSS and CSRF attacks. In this article we've demonstrated how those particular threats are handled by Django in our LocalLibrary website. We've also provided a brief overview of some of the other protections.

- -

This has been a very brief foray into web security. We strongly recommend that you read Security in Django to gain a deeper understanding.

- -

The next and final step in this module about Django is to complete the assessment task.

- -

See also

- - - -

{{PreviousMenuNext("Learn/Server-side/Django/Deployment", "Learn/Server-side/Django/django_assessment_blog", "Learn/Server-side/Django")}}

- -

En este módulo

- - diff --git a/files/es/mozilla/firefox/releases/19/index.html b/files/es/mozilla/firefox/releases/19/index.html deleted file mode 100644 index c5ebfd438a..0000000000 --- a/files/es/mozilla/firefox/releases/19/index.html +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Firefox 19 para Desarrolladores -slug: Mozilla/Firefox/Releases/19 -translation_of: Mozilla/Firefox/Releases/19 -original_slug: Firefox_19_para_desarrolladores ---- -
{{FirefoxSidebar}}
- -

-

Quieres ayudar a documentar Firefox 19? Visita la lista de bugs que necesitan ser revisados e inicia!

-

- -

Cambios para desarrolladores

- -

JavaScript

- - - -

CSS

- - - -

DOM

- - - -

XForms

- -

Support for XForms has been removed in Firefox 19.

- -

Changes for add-on and Mozilla developers

- -
-

Note: A key change in Firefox 19 is that nsresult is now strongly typed. This will help make it easier to detect bugs that are caused by mishandling of return values, but may cause existing code to break if it's making incorrect assumptions in this regard.

-
- - - -

See also

- - - -

Older versions

- -

{{Firefox_for_developers('18')}}

diff --git a/files/es/mozilla/firefox/releases/63/index.html b/files/es/mozilla/firefox/releases/63/index.html deleted file mode 100644 index cd63bb1eac..0000000000 --- a/files/es/mozilla/firefox/releases/63/index.html +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: Firefox 63 para desarrolladores -slug: Mozilla/Firefox/Releases/63 -tags: - - Firefox - - Mozilla - - Release -translation_of: Mozilla/Firefox/Releases/63 ---- -
{{FirefoxSidebar}}
- -

Este articulo proporciona información sobre los cambios en Firefox 63, que afectara a los desarrolladores. La versión de Firefox 63 fue publicada el 23 de octubre del 2018.

- -

Cambios para los desarrolladores web

- -

Herramientas de desarrollo

- - - -

HTML

- - - -

Removals

- - - -

CSS

- - - -

Removals

- - - -

SVG

- -

No changes.

- -

JavaScript

- - - -

Removals

- - - -

APIs

- -

New APIs

- - - -

DOM

- - - -

DOM events

- - - -

Media, Web Audio, and WebRTC

- - - -

Canvas and WebGL

- - - -

Removals

- - - -

CSSOM

- -

No changes.

- -

HTTP

- - - -

Security

- - - -

Plugins

- -

No changes.

- -

WebDriver conformance (Marionette)

- -

New features

- - - -

API changes

- - - -

Bug fixes

- - - -

Other

- - - -

Changes for add-on developers

- -

API changes

- -

Theming

- - - - - - - -

Tabs

- - - - - - - -

Other

- - - -

See also

- - - -

Older versions

- -

{{Firefox_for_developers(62)}}

diff --git a/files/es/tools/3d_view/index.html b/files/es/tools/3d_view/index.html deleted file mode 100644 index d394e5de81..0000000000 --- a/files/es/tools/3d_view/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: 3D view -slug: Tools/3D_View -translation_of: Tools/3D_View ---- -

Cuando das click sobre el botón ver 3D view, la página entra en modo de vista 3D; en este modo, usted puede ver su página en vista 3D en la cual se anidan bloques de HTML que van sobreponiendose, se proyecta desde la parte inferior de la página. Esta vista hace fácil de visualizar como se anida su contenido.

-

-

By clicking and dragging the view, you can rotate and re-orient the 3D presentation of the DOM hierarchy of your page to see it from different angles, to better examine its structure. Off-screen elements become visible, so that you can see where your elements are located in relation to the visible content. You can click on elements to see their HTML in the HTML panel or or Style panel. Conversely, you can click on elements in the breadcrumb bar to change which element is selected in the 3D view.

-

If you do not see the 3D button in the page inspector, it is possible that your graphics driver needs to be updated. See the blocklisted drivers page for more information.

-

Controlling the 3D view

-

There are keyboard shortcuts and mouse controls available for the 3D view.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FunctionKeyboardMouse
Zoom in/out+ / -Scroll wheel up/down
Rotate left/righta / dMouse left/right
Rotate up/downw / sMouse up/down
Pan left/right← / →Mouse left/right
Pan up/down↑ / ↓Mouse up/down
Reset zoom level0Resets the zoom level to the default
Focus on selected nodefMakes sure the currently selected node is visible
Reset viewrResets zoom, rotation, and panning to the default
Hide current nodexMakes the currently selected node invisible; this can be helpful if you need to get at a node that's obscured
-

Use cases for the 3D view

-

There are a variety of ways the 3D view is useful:

- -

See also

- -

{{ languages( { "ja": "ja/Tools/Page_Inspector/3D_view", "zh-cn": "zh-cn/Tools/Page_Inspector/3D_view"} ) }}

diff --git a/files/es/tools/debugger/how_to/set_a_breakpoint/index.html b/files/es/tools/debugger/how_to/set_a_breakpoint/index.html deleted file mode 100644 index 49376ffc9e..0000000000 --- a/files/es/tools/debugger/how_to/set_a_breakpoint/index.html +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Set a breakpoint -slug: Tools/Debugger/How_to/Set_a_breakpoint -translation_of: Tools/Debugger/How_to/Set_a_breakpoint ---- -
{{ToolsSidebar}}
- -

Puedes establecer una interrupción incondicional en una de las siguientes maneras:

- - - -

When you display the context menu, you have a choice of setting either a breakpoint that will pause code execution when it reaches that line, an unconditional breakpoint, or a conditional breakpoint that will only pause the code if the conditions you define are met:

- -

- -

If you choose to set a conditional breakpoint, you will be able to add the condition:

- -

- -

Each breakpoint is shown in two places in the debugger:

- - - -

Starting in Firefox 67, you can set a column breakpoint on a complex line of code, such as one that makes multiple function calls. For example, if you try to set a breakpoint on the following line, you will have three possible locations for a breakpoint: at the point where the variable value is set, at the call to parse, or at the call to getItem.

- -
tasks = JSON.parse(localStorage.getItem('todoList'));
- -

Possible breakpoints are shown with indicators. The following image shows the line in the debugger. As soon as you click on the line, the three indicators show the possible breakpoints. The default breakpoint is set to the first column. In the image, the second column breakpoint was chosen which you can confirm in the Breakpoints section on the right where it shows that the breakpoint is on the call to parse.

- -

- -

Column breakpoints allow you to break at multiple points on the same line. In the previous example, you could have selected both the call to parse and the call to getItem, or even all three columns to break at each of the possible locations.

- -

In cases where you set breakpoints on multiple columns, the currently active columns breakpoint will be highlighted in the Breakpoints side panel.

diff --git a/files/es/tools/page_inspector/how_to/work_with_animations/index.html b/files/es/tools/page_inspector/how_to/work_with_animations/index.html deleted file mode 100644 index 2d855f1785..0000000000 --- a/files/es/tools/page_inspector/how_to/work_with_animations/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Trabajar con animaciones -slug: Tools/Page_Inspector/How_to/Work_with_animations -tags: - - Guia(2) - - Herramientas - - Inspector -translation_of: Tools/Page_Inspector/How_to/Work_with_animations ---- -

Este artículo cubre tres herramientas que puede usar para visualizar y editar animaciones:

- - - -

Inspector de Animación

- -
-

Aunque esta herramienta se introdujo en Forefox 41, el interface de usuario se rediseñó en Forefox 43. This article describes the animation inspector as it appears in Firefox 43 and subsequent releases. If you want to see what the animation inspector looks like in Firefox 41 and 42, see this separate page.

-
- -

Desde Firefox 41, el Inspector de Página incluye una vista extra etiquetada "Animaciones".

- -

Esta vista muestra las transiciones CSS y las animaciones CSS sincronizadas en la linea de tiempo, puede usar el widget dragueable para moverse a cualquier punto en la linea de tiempo y ver la página en ese punto.

- -

To see how it works, we'll walk through an example. The box below contains three grayscale icons, each representing a different Firefox channel. If you click an icon, the icon enlarges and changes to color, and the name of the channel appears. Click the icon again to reverse the effect. These animations are made by applying transitions to several CSS properties.

- -

{{ EmbedLiveSample('firefox-logo-animation', 500, 250, "", "Tools/Page_Inspector/How_to/Work_with_animations/Animations_examples") }}

- -

Let's use the animation inspector to see what's going on in this example.

- - - -

{{EmbedYouTube("U2eJYacf5XY")}}

- -

Now play the animation:

- -

{{EmbedYouTube("CwXXXEllB3o")}}

- -

Let's take a closer look at the contents of the animation inspector here:

- -

- -

It shows a synchronized timeline for every CSS property transition involved in the animation. The timeline starts at the start of the first transition, and ends at the end of the last transition, and is labeled with markers every 100 milliseconds (this depends on the time scale of the animations currently displayed). You can see that the example above takes 735 milliseconds to run.

- -

Each animation or transition is shown as a horizontal bar laid across the timeline:

- - - -

To the left of each bar is a selector for the node that the animation applies to. If you hover over this selector, the node is highlighted in the page. Click the selector to select the node in the inspector.

- -

To the left of the selector is a "target" icon (). From Firefox 44, clicking this icon will lock the highlighter on the element.

- -

Applying all this to our example, we can see that:

- - - -

Animation playback

- -

At the top of the animation inspector:

- - - -

Finally, if you click inside the bar at the top of the timeline, you get a scrubber that you can drag left and right to move backwards and forwards through the animation, and pinpoint exactly what's happening when:

- -

{{EmbedYouTube("1hqNaMsB48g")}}

- -

Edit @keyframes

- -

Any @keyframes rules associated with the currently selected element are displayed in the Rules view and are editable:

- -

{{EmbedYouTube("mDHtLK88ZW4")}}

- -

Edit timing functions

- -

When you create a CSS animation you can specify a timing function: this determines the rate at which the animation progresses. One way to specify the timing function is with a cubic Bézier curve.

- -

Timing functions defined as cubic Bézier curves get an icon in the Rules view. If you click the icon you get a visual editor for the curve, enabling you to drag P1 and P2, and see the results in the page:

- -

{{EmbedYouTube("GW5-R2ewaqA")}}

- -

This feature uses open source code from Lea Verou’s cubic-bezier.com.

- -

The cubic Bézier editor includes a number of presets, grouped under "Ease-in", "Ease-out", and "Ease-in-out":

- -

{{EmbedYouTube("Jx-J2Yy0aSg")}}

diff --git a/files/es/tools/settings/index.html b/files/es/tools/settings/index.html deleted file mode 100644 index e502957541..0000000000 --- a/files/es/tools/settings/index.html +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: Configuración -slug: Tools/Settings -translation_of: Tools/Settings ---- -

Configuraciones

- -

Al hacer clic en el botón "Configuraciones" le permite acceder a la configuración de la propia caja de herramientas y de las herramientas que alberga:

- -

- -

Por defecto Firefox Herramientas de Desarrollo

- -

Este grupo de casillas de verificación determina qué herramientas están habilitadas en la caja de herramientas. Las nuevas herramientas se incluyen con frecuencia en Firefox, pero no está activado de forma predeterminada.

- -

Elija DevTools tema

- -

Esto le permite cambiar entre tema claro u oscuro:

- -

- -

- -

Inspector

- -
-

Este ajuste está disponible en Firefox 27 en adelante

-
- -

Unidad de color por defecto: un valor para controlar cómo se representan los colores de la inspección: Hex, HSL(A), RGB(A), y por su nombre.

- -

Consola Web

- -

Habilitar registros persistentes: una configuración para controlar si la consola borra la salida cuando se navega a una página nueva..

- -

Analizador JavaScript

- -

Mostrar datos de la plataforma Gecko: una opción para controlar si los perfiles deben incluir Gecko símbolos de plataforma.

- -

Configuraciones avanzadas

- - - - - - -

Opening Settings

- -

To see the Developer Tools Settings pane, open any of the Developer Tools, and then:

- - - -

The Settings pane looks something like this:

- -

Depicts the Toolbox options

- -

Categories

- -

Default Firefox Developer Tools

- -

This group of checkboxes determines which tools are enabled in the toolbox. New tools are often included in Firefox but not enabled by default.

- -

Available Toolbox Buttons

- -

This group of checkboxes determines which tools get an icon in the Toolbox's toolbar.

- -

Note that in Firefox 52 we removed the checkbox to toggle the "Select element" button. The "Select element" button is now always shown.

- -

Themes

- -

This enables you to choose one of three different themes.

- -

There's a light theme, which is the default:

- -

Light theme for DevTools

- -

A dark theme (the default on Firefox Developer Edition):

- -

Dark theme for DevTools

- -

There's also a Firebug theme that looks like the Firebug extension, letting you feel at home if you're used to Firebug:

- -

Firebug theme for DevTools

- -

Common preferences

- -

Settings that apply to more than one tool. There's just one of these:

- -
-
Enable persistent logs
-
A setting to control whether or not the Web Console and Network Monitor clear their output when you navigate to a new page.
-
- -

Inspector

- -
-
Show browser styles
-
A setting to control whether styles applied by the browser (user-agent styles) should be displayed in the Inspector's Rules view. Note that this setting is independent of the "Browser styles" checkbox in the Inspector's Computed view.
-
Truncate DOM attributes
-
By default, the Inspector truncates DOM attributes that are more than 120 characters long. Uncheck this box to prevent this behavior. This setting works by toggling the about:config preference "devtools.markup.collapseAttributes". To change the threshold at which attributes are truncated, you can edit the about:config preference "devtools.markup.collapseAttributeLength".
-
Default color unit
-
A setting to control how colors are represented in the inspector: -
    -
  • Hex
  • -
  • HSL(A)
  • -
  • RGB(A)
  • -
  • color name
  • -
  • As authored.
  • -
-
-
Enable layout panel
-
Enable the experimental layout panel. This setting only exists in Firefox Nightly.
-
- -

Web Console

- -
-
Enable timestamps
-
Controls whether the Web Console displays timestamps. The Web Console defaults to hiding timestamps.
-
Enable new console frontend
-
Switch to the experimental new console. This setting only exists in Firefox Nightly.
-
- -

Debugger

- -
-
Enable Source Maps
-
Enable source map support in the debugger.
-
Enable new debugger frontend
-
Enable the new debugger. This setting only exists in Firefox Nightly.
-
- -

Style Editor

- -
-
Show original sources
-
When a CSS preprocessor supporting source maps is used, this enables the Style Editor to display the original, preprocessor, sources rather than the generated CSS. Learn more about Style Editor support for CSS source maps. With this setting checked, the Page Inspector Rules view will also provide links to the original sources.
-
Autocomplete CSS
-
Enable the Style Editor to offer autocomplete suggestions.
-
- -

Screenshot Behavior

- -
-
Screenshot to clipboard
-
When you click the icon for the Screenshot tool, copy the screenshot image to the clipboard (the image will still be saved to your Downloads directory). New in Firefox 53.
-
Play camera shutter sound
-
When you click the icon for the Screenshot tool, play a shutter sound. New in Firefox 53.
-
- -

Editor Preferences

- -

Preferences for the CodeMirror source editor, which is included in Firefox and used by several developer tools, including Scratchpad and the Style Editor.

- -
-
Detect indentation
-
Auto-indent new lines based on the current indentation.
-
Autoclose brackets
-
 
-
Indent using spaces
-
 
-
Tab size
-
 
-
Keybindings
-
Choose the default CodeMirror keybindings or keybindings from one of several popular editors: -
    -
  • Vim
  • -
  • Emacs
  • -
  • Sublime Text
  • -
-
-
- -

Advanced settings

- -
-
Show Gecko platform data
-
A setting to control whether or not profiles should include Gecko platform symbols.
-
- -
-
Disable HTTP Cache
-
Disable the browser HTTP cache to simulate first-load performance in all tabs that have the Toolbox open. This setting persists, meaning that if it is set, caching will be disabled whenever you reopen the devtools. Caching is re-enabled when the devtools are closed. Note that service workers are not affected by this option. -
Note that this option was called "Disable Cache" in Firefox versions previous to 49, but it was renamed to make it clearer that this affects the HTTP cache, and not Service Workers/the Cache API.
-
-
Disable JavaScript
-
Reload the current tab with JavaScript disabled.
-
Enable Service Workers over HTTP
-
Enable Service Worker registrations from insecure websites.
-
Enable browser chrome and add-on debugging toolboxes
-
Enable you to use developer tools in the context of the browser itself, and not only web content.
-
Enable remote debugging
-
Enable the developer tools to debug remote Firefox instances.
-
Enable worker debugging
-
Enable a panel within the debugger to debug workers. -

Note: This option got removed from the UI in Firefox 56, because this version ships with a new Debugger UI, but it can still be enabled for the old UI by setting the preference devtools.debugger.workers to true.

-
-
diff --git a/files/es/web/api/audionode/index.html b/files/es/web/api/audionode/index.html deleted file mode 100644 index ea6ff34406..0000000000 --- a/files/es/web/api/audionode/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: AudioNode -slug: Web/API/AudioNode -translation_of: Web/API/AudioNode ---- -
{{APIRef("Web Audio API")}}
- -

La interfaz AudioNode es una interfaz genérica para representar un módulo de procesamiento de audio. Ejemplos:

- - - -

{{InheritanceDiagram}}

- -

Note: An AudioNode can be target of events, por lo tanto este implementa  {{domxref("EventTarget")}} interface.

- -

Descripción

- -

The audio routing graph

- -

AudioNodes participating in an AudioContext create a audio routing graph.

- -

Cada AudioNode posee entradas y salidas, y múltiples nodos de audio son conectados para construir un processing graph. Este graph es contenido en {{domxref("AudioContext")}}, y cada nodo de audio solo puede pertecener a un audio context.

- -

Un source node tiene cero entradas pero una o muchas salidas, y puede ser usado para generar sonido. Por otro lado, un destination node no tiene salidas; instead, all its inputs are directly played back on the speakers (or whatever audio output device the audio context uses). In addition, there are processing nodes which have inputs and outputs. The exact processing done varies from one AudioNode to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or simply lets the audio pass through (for example in the {{domxref("AnalyserNode")}}, where the result of the processing is accessed separately).

- -

The more nodes in a graph, the higher the latency will be. Por ejemplo, si tu graph tiene una latencia de 500ms, Cuando el source node reproduzca un sonido, este va a tomar la mitad de un segundo hasta que el sonido pueda ser escuchado en tus altavoces. (or even longer because of latency in the underlying audio device). Por lo tanto, si tu necesitas tener un audio interactivo, keep the graph as small as possible, and put user-controlled audio nodes at the end of a graph. For example, a volume control (GainNode) should be the last node so that volume changes take immediate effect.

- -

Each input and output has a given amount of channels. For example, mono audio has one channel, while stereo audio has two channels. The Web Audio API will up-mix or down-mix the number of channels as required; check the Web Audio spec for details.

- -

For a list of all audio nodes, see the Web Audio API homepage.

- -

Creating an AudioNode

- -

There are two ways to create an AudioNode: via the constuctor and via the factory method.

- -
// constructor
-const analyserNode = new AnalyserNode(audioCtx, {
-  fftSize: 2048,
-  maxDecibels: -25,
-  minDecibels: -60,
-  smoothingTimeConstant: 0.5,
-});
-
-// factory method
-const analyserNode = audioCtx.createAnalyser();
-analyserNode.fftSize = 2048;
-analyserNode.maxDecibels = -25;
-analyserNode.minDecibels = -60;
-analyserNode.smoothingTimeConstant = 0.5;
- -

Eres libre de usar cualquiera de los constructors o factory methods, o una mezcla de ambos, sin embargo hay ventajas al usar contructores:

- - - -

Tener en cuenta que Microsoft Edge does not yet appear to support the constructors; it will throw a "Function expected" error when you use the constructors.

- -

Brief history: The first version of the Web Audio spec only defined the factory methods. After a design review in October 2013, it was decided to add constructors because they have numerous benefits over factory methods. The constructors were added to the spec from August to October 2016. Factory methods continue to be included in the spec and are not deprecated.

- -

Properties

- -
-
{{domxref("AudioNode.context")}} {{readonlyInline}}
-
Returns the associated {{domxref("BaseAudioContext")}}, that is the object representing the processing graph the node is participating in.
-
- -
-
{{domxref("AudioNode.numberOfInputs")}} {{readonlyInline}}
-
Returns the number of inputs feeding the node. Source nodes are defined as nodes having a numberOfInputs property with a value of 0.
-
- -
-
{{domxref("AudioNode.numberOfOutputs")}} {{readonlyInline}}
-
Returns the number of outputs coming out of the node. Destination nodes — like {{ domxref("AudioDestinationNode") }} — have a value of 0 for this attribute.
-
- -
-
{{domxref("AudioNode.channelCount")}}
-
Represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. Its usage and precise definition depend on the value of {{domxref("AudioNode.channelCountMode")}}.
-
- -
-
{{domxref("AudioNode.channelCountMode")}}
-
Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs.
-
{{domxref("AudioNode.channelInterpretation")}}
-
Represents an enumerated value describing the meaning of the channels. This interpretation will define how audio up-mixing and down-mixing will happen.
- The possible values are "speakers" or "discrete".
-
- -

Methods

- -

Also implements methods from the interface {{domxref("EventTarget")}}.

- -
-
{{domxref("AudioNode.connect()")}}
-
Allows us to connect the output of this node to be input into another node, either as audio data or as the value of an {{domxref("AudioParam")}}.
-
{{domxref("AudioNode.disconnect()")}}
-
Allows us to disconnect the current node from another one it is already connected to.
-
- -

Example

- -

This simple snippet of code shows the creation of some audio nodes, and how the AudioNode properties and methods can be used. You can find examples of such usage on any of the examples linked to on the Web Audio API landing page (for example Violent Theremin.)

- -
const audioCtx = new AudioContext();
-
-const oscillator = new OscillatorNode(audioCtx);
-const gainNode = new GainNode(audioCtx);
-
-oscillator.connect(gainNode).connect(audioCtx.destination);
-
-oscillator.context;
-oscillator.numberOfInputs;
-oscillator.numberOfOutputs;
-oscillator.channelCount;
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-audionode-interface', 'AudioNode')}}{{Spec2('Web Audio API')}} 
- -

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html b/files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html deleted file mode 100644 index 1f2a93dbae..0000000000 --- a/files/es/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Hit regions and accessibility -slug: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility -translation_of: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility -original_slug: Web/Guide/HTML/Canvas_tutorial/Hit_regions_and_accessibility ---- -
{{CanvasSidebar}} {{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
- -
The {{HTMLElement("canvas")}} element on its own is just a bitmap and does not provide information about any drawn objects. Canvas content is not exposed to accessibility tools like semantic HTML is. In general, you should avoid using canvas in an accessible website or app. The following guidelines can help to make it more accessible.
- -
El elemento {{HTMLElement ("canvas")}} por sí solo es solo un mapa de bits y no proporciona información sobre ningún objeto dibujado. El contenido del lienzo no está expuesto a herramientas de accesibilidad como el HTML semántico. En general, debe evitar usar canvas en un sitio web o aplicación accesible. Las siguientes pautas pueden ayudar a que sea más accesible.
- -

Fallback content

- -

The content inside the <canvas> ... </canvas> tags can be used as a fallback for browsers which don't support canvas rendering. It's also very useful for assistive technology users (like screen readers) which can read and interpret the sub DOM in it. A good example at html5accessibility.com demonstrates how this can be done:

- -
<canvas>
-  <h2>Shapes</h2>
-  <p>A rectangle with a black border.
-   In the background is a pink circle.
-   Partially overlaying the <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>.
-   Partially overlaying the circle is a green
-   <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();">square</a>
-   and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle();" onblur="drawPicture();">triangle</a>,
-   both of which are semi-opaque, so the full circle can be seen underneath.</p>
-</canvas> 
- -

See the video how NVDA reads this example by Steve Faulkner.

- -

ARIA rules

- -

Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications more accessible to people with disabilities. You can use ARIA attributes to describe the behavior and purpose of the canvas element. See ARIA and ARIA techniques for more information.

- -
<canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="Start game"></canvas>
-
- -

Hit regions

- -

Whether the mouse coordinates are within a particular area on the canvas, is a common problem to solve. The hit region API allows you to define an area of your canvas and provides another possibility to expose interactive content on a canvas to accessibility tools. It allows you to make hit detection easier and lets you route events to DOM elements. The API has the following three methods (which are still experimental in current web browsers; check the browser compatibility tables).

- -
-
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
-
Adds a hit region to the canvas.
-
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
-
Removes the hit region with the specified id from the canvas.
-
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
-
Removes all hit regions from the canvas.
-
- -

You can add a hit region to your path and check for the {{domxref("MouseEvent.region")}} property to test if your mouse is hitting your region, for example.

- -
<canvas id="canvas"></canvas>
-<script>
-var canvas = document.getElementById('canvas');
-var ctx = canvas.getContext('2d');
-
-ctx.beginPath();
-ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
-ctx.fill();
-ctx.addHitRegion({id: 'circle'});
-
-canvas.addEventListener('mousemove', function(event) {
-  if (event.region) {
-    alert('hit region: ' + event.region);
-  }
-});
-</script>
- -

The addHitRegion() method also takes a control option to route events to an element (that is a descendant of the canvas):

- -
ctx.addHitRegion({control: element});
- -

This can be useful for routing to {{HTMLElement("input")}} elements, for example. See also this codepen demo.

- -

Focus rings

- -

When working with the keyboard, focus rings are a handy indicator to help navigating on a page. To draw focus rings on a canvas drawing, the drawFocusIfNeeded property can be used.

- -
-
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}} {{experimental_inline}}
-
If a given element is focused, this method draws a focus ring around the current path.
-
- -

Additionally, the scrollPathIntoView() method can be used to make an element visible on the screen if focused, for example.

- -
-
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{experimental_inline}}
-
Scrolls the current path or a given path into the view.
-
- -

See also

- - - -
{{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
diff --git a/files/es/web/api/filesystem/index.html b/files/es/web/api/filesystem/index.html deleted file mode 100644 index 62f5e91b4b..0000000000 --- a/files/es/web/api/filesystem/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: FileSystem -slug: Web/API/FileSystem -translation_of: Web/API/FileSystem ---- -

{{APIRef("File System API")}} {{non-standard_header}}

- -

La interfaz de la API FileSystem  para la entrada de archivos y directorios es usada para representar un sistema de archivos.  Estos objetos pueden ser obtenidos desde la propiedad {{domxref("FileSystemEntry.filesystem", "filesystem")}} en cualquier entrada del sistema de archivos . Algunos navegadores ofrecen APIs adicionales para crear y administrar el sistema de archivos , como el metodo de Chrome {{domxref("Window.requestFileSystem", "requestFileSystem()")}}.

- -

This interface will not grant you access to the users filesystem. Instead you will have a "virtual drive" within the browser sandbox. If you want to gain access to the users filesystem you need to invoke the user by eg. installing a Chrome extension. The relevant Chrome API can be found here.

- -
-

Because this is a non-standard API, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. Check the {{anch("Browser compatibility")}} section for details.

-
- -

Conceptos Basicos

- -

Hay dos formas de acceder a un objeto FileSystem :

- -
    -
  1. You can directly ask for one representing a sandboxed file system created just for your web app directly by calling window.requestFileSystem().  If that call is successful, it executes a callback handler, which receives as a parameter a FileSystem object describing the file system.
  2. -
  3. You can get it from a file system entry object, through its {{domxref("FileSystemEntry.filesystem", "filesystem")}} property.
  4. -
- -

Propiedades

- -
-
{{domxref("FileSystem.name")}} {{ReadOnlyInline}}
-
A {{domxref("USVString")}} representing the file system's name. This name is unique among the entire list of exposed file systems.
-
{{domxref("FileSystem.root")}} {{ReadOnlyInline}}
-
A {{domxref("FileSystemDirectoryEntry")}} object which represents the file system's root directory. Through this object, you can gain access to all files and directories in the file system.
-
- -

Especificaciones

- - - - - - - - - - - - - - - - -
EspecificaciónEstadoComentario
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
- -

This API has no official W3C or WHATWG specification.

- -

Compatibilidad entre navegadores 

- -

{{ CompatibilityTable }}

- -
- - - - - - - - - - - - - - - - - - - - - -
CaracteristicaChromeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Soporte basico13{{ property_prefix("webkit") }}{{ CompatGeckoDesktop(50) }}{{ CompatNo }}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}} {{ property_prefix("webkit") }}{{ CompatNo }}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo }}0.16{{ property_prefix("webkit") }}{{ CompatGeckoMobile(50) }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -

[1] Microsoft Edge implements this interface under the name WebKitFileSystem, and supports its use only in drag-and-drop scenarios using the {{domxref("DataTransferItem.webkitGetAsEntry()")}} method. It's not available for use in file or folder picker panels (such as when you use an {{HTMLElement("input")}} element with the {{domxref("HTMLInputElement.webkitdirectory")}} attribute.

- -

See also

- - diff --git a/files/es/web/api/headers/index.html b/files/es/web/api/headers/index.html deleted file mode 100644 index cb65b6aa11..0000000000 --- a/files/es/web/api/headers/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Headers -slug: Web/API/Headers -tags: - - API - - Experimental - - Fetch - - Headers - - Interface - - Reference -translation_of: Web/API/Headers ---- -
{{ APIRef("Fetch") }}
- -
La interfaz Headers de la Fetch API permite realizar diversas acciones en los Headers de solicitud y respuesta HTTP.Estas acciones incluyen recuperar, establecer, agregar y eliminar. Un objeto Header tiene una lista  asociada que inicialmente está vacía, y consta de cero o más pares de nombre y valor.
- -
Es posible añadir metodos de uso como {{domxref("Headers.append","append()")}} (ver{{anch(" ejemplos")}}.) En todos los métodos de esta interfaz, los nombres de los encabezados se relacionan con una secuencia de bytes sensible a mayúsculas y minúsculas.
- -
Por razones de seguridad, algunos headers pueden ser controlados unicamente por el user agent. Estos headers incluyen los {{Glossary("Forbidden_header_name", "nombres prohibidos para headers", 1)}}  y {{Glossary("Forbidden_response_header_name", "nombres prohibidos de Headers response", 1)}}.
- -

A Headers object also has an associated guard, which takes a value of immutable, request, request-no-cors, response, or none. This affects whether the {{domxref("Headers.set","set()")}}, {{domxref("Headers.delete","delete()")}}, and {{domxref("Headers.append","append()")}} methods will mutate the header. For more information see {{Glossary("Guard")}}.

- -

You can retrieve a Headers object via the {{domxref("Request.headers")}} and {{domxref("Response.headers")}} properties, and create a new Headers object using the {{domxref("Headers.Headers()")}} constructor.

- -

An object implementing Headers can directly be used in a {{jsxref("Statements/for...of", "for...of")}} structure, instead of {{domxref('Headers.entries()', 'entries()')}}: for (var p of myHeaders) is equivalent to for (var p of myHeaders.entries()).

- -
-

Note: you can find more out about the available headers by reading our HTTP headers reference.

-
- -

Constructor

- -
-
{{domxref("Headers.Headers()")}}
-
Creates a new Headers object.
-
- -

Methods

- -
-
{{domxref("Headers.append()")}}
-
Appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist.
-
{{domxref("Headers.delete()")}}
-
Deletes a header from a Headers object.
-
{{domxref("Headers.entries()")}}
-
Returns an {{jsxref("Iteration_protocols","iterator")}} allowing to go through all key/value pairs contained in this object.
-
{{domxref("Headers.forEach()")}}
-
Executes a provided function once for each array element.
-
{{domxref("Headers.get()")}}
-
Returns a {{domxref("ByteString")}} sequence of all the values of a header within a Headers object with a given name.
-
{{domxref("Headers.has()")}}
-
Returns a boolean stating whether a Headers object contains a certain header.
-
{{domxref("Headers.keys()")}}
-
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing you to go through all keys of the key/value pairs contained in this object.
-
{{domxref("Headers.set()")}}
-
Sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
-
{{domxref("Headers.values()")}}
-
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing you to go through all values of the key/value pairs contained in this object.
-
- -
-

Note: To be clear, the difference between {{domxref("Headers.set()")}} and {{domxref("Headers.append()")}} is that if the specified header does already exist and does accept multiple values, {{domxref("Headers.set()")}} will overwrite the existing value with the new one, whereas {{domxref("Headers.append()")}} will append the new value onto the end of the set of values. See their dedicated pages for example code.

-
- -
-

Note: All of the Headers methods will throw a TypeError if you try to pass in a reference to a name that isn't a valid HTTP Header name. The mutation operations will throw a TypeError if the header has an immutable {{Glossary("Guard")}}. In any other failure case they fail silently.

-
- -
-

Note: When Header values are iterated over, they are automatically sorted in lexicographical order, and values from duplicate header names are combined.

-
- -

Obsolete methods

- -
-
{{domxref("Headers.getAll()")}}
-
Used to return an array of all the values of a header within a Headers object with a given name; this method has now been deleted from the spec, and {{domxref("Headers.get()")}} now returns all values instead of just one.
-
- -

Examples

- -

In the following snippet, we create a new header using the Headers() constructor, add a new header to it using append(), then return that header value using get():

- -
var myHeaders = new Headers();
-
-myHeaders.append('Content-Type', 'text/xml');
-myHeaders.get('Content-Type') // should return 'text/xml'
-
- -

The same can be achieved by passing an array of arrays or an object literal to the constructor:

- -
var myHeaders = new Headers({
-    'Content-Type': 'text/xml'
-});
-
-// or, using an array of arrays:
-myHeaders = new Headers([
-    ['Content-Type', 'text/xml']
-]);
-
-myHeaders.get('Content-Type') // should return 'text/xml'
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#headers-class','Headers')}}{{Spec2('Fetch')}} 
- -

Browser compatibility

- - - -

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

- -

See also

- - - -

 

diff --git a/files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html b/files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html deleted file mode 100644 index 84b04854fa..0000000000 --- a/files/es/web/api/html_drag_and_drop_api/recommended_drag_types/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Tipos de Drag recomendados -slug: Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types -translation_of: Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types -original_slug: DragDrop/Recommended_Drag_Types ---- -

A continuación se describe la mejor practica para utilizar los datos a ser arrastrado.

-

Arrastramdo Texto

-

Al arrastrar el texto, utilice el texto / texto normal. Los datos deben ser la cadena de arrastre. Por ejemplo:

-
event.dataTransfer.setData("text/plain", "This is text to drag")
-
-

Arrastrar texto en cuadros de texto y las selecciones de las páginas web se realiza de forma automática, por lo que no es necesario para manejar dragging.

-

Se recomienda que siempre se agrega datos del tipo  text/plain  como un mensaje para las aplicaciones o los destinos que no soportan otros tipos, a menos que no hay alternativa de texto lógico. Siempre agregue el tipo de texto sin formato pasado, ya que es el menos específico.

-

En códigos más viejo, encontrara text/unicode o el tipo Text.Estos equivalen text/plain,que guardara y recibia los datos del texto plano en ese lugar.

- -

Los enlaces deben incluir los datos de los dos tipos, el primero debe ser  URL utilizando el tipo text/uri-list,y el segundo es URL utilizando el tipo text/plain. Ambos tipos deben utilizar los mismos datos, la URL del enlace. Por ejemplo:

-
var dt = event.dataTransfer;
-dt.setData("text/uri-list", "http://www.mozilla.org");
-dt.setData("text/plain", "http://www.mozilla.org");
-
-

Es constumbre, establecer el tipo text/plain de ultimo, , ya que es menos específico que el tipo de URI.

-

Note que el tipo de URL uri-list es con una "i", no una "L"

-

Note that the URL type is uri-list with an 'I', not with an 'L'.

-

To drag multiple links, you can also separate each link with a linebreak. A line that begins with a number sign (#) is a comment and should not be considered a valid URL. You can use a comment to indicate the purpose of a link, or to hold the title associated with a link. The text/plain version of the drag data should include all links but should not include the comments.

-

For example:

-
http://www.mozilla.org
-#A second link
-http://www.xulplanet.com
-
-

This sample text/uri-list data contains two links and a comment.

-

When retrieving a dropped link, you should ensure you handle the case where multiple links may have been dragged, and any comments that appear in the data. For convenience, the special type URL may be used to refer to the first valid link within the data for the text/uri-list type. You should not add data using the URL type; attempting to do so will just set the value of the text/uri-list type instead.

-
var url = event.dataTransfer.getData("URL");
-
-

You may also see data using the text/x-moz-url type which is a Mozilla specific type. If it appears, it should be used before the text/uri-list type. It holds the URL of the link followed by the title of the link, separated by a linebreak. For example:

-
http://www.mozilla.org
-Mozilla
-http://www.xulplanet.com
-XUL Planet
-
-

Dragging HTML and XML

-

HTML content may use the text/html type. The data for this type should be the serialized HTML to drag. For instance, it would be suitable to set the data value for this type to the value of the innerHTML property of an element.

-

XML content may use the text/xml type, but you should ensure that the data value is well-formed XML.

-

You may also include a plain text representation of the HTML or XML data using the text/plain type. The data should be just the text and should not include any of the source tags or attributes. For instance:

-
var dt = event.dataTransfer;
-dt.setData("text/html", "Hello there, <strong>stranger</strong>");
-dt.setData("text/plain", "Hello there, stranger");
-
-

Dragging Files

-

A local file is dragged using the application/x-moz-file type with a data value that is an nsIFile object. Non-privileged web pages are not able to retrieve or modify data of this type. Because a file is not a string, you must use the mozSetDataAt method to assign the data. Similarly, when retrieving the data, you must use the mozGetDataAt method.

-
event.dataTransfer.mozSetDataAt("application/x-moz-file", file, 0);
-
-

If possible, you may also include the file URL of the file using both the text/uri-list and/or text/plain types. These types should be added last so that the more specific application/x-moz-file type has higher priority.

-

Multiple files will be received during a drop as mutliple items in the data transfer. See Dragging and Dropping Multiple Items for more details about this.

-

The following example shows how to create an area for receiving dropped files:

-
<listbox ondragenter="return checkDrag(event)"
-         ondragover="return checkDrag(event)"
-         ondrop="doDrop(event)"/>
-
-<script>
-function checkDrag(event)
-{
-  return event.dataTransfer.types.contains("application/x-moz-file");
-}
-
-function doDrop(event)
-{
-  var file = event.dataTransfer.mozGetDataAt("application/x-moz-file", 0);
-  if (file instanceof Components.interfaces.nsIFile)
-    event.currentTarget.appendItem(file.leafName);
-}
-</script>
-
-

In this example, the event returns false only if the data transfer contains the application/x-moz-file type. During the drop event, the data associated with the file type is retrieved, and the filename of the file is added to the listbox. Note that the instanceof operator is used here as the mozGetDataAt method will return an nsISupports that needs to be checked and converted into an nsIFile. This is also a good extra check in case someone made a mistake and added a non-file for this type.

-

Dragging Images

-

Direct image dragging is not commonly done. In fact, Mozilla does not support direct image dragging on Mac or Linux platforms. Instead, images are usually dragged only by their URLs. To do this, use the text/uri-list type as with other URL links. The data should be the URL of the image or a data URL if the image is not stored on a web site or disk. For more information about data URLs, see the data URL scheme.

-

As with other links, the data for the text/plain type should also contain the URL. However, a data URL is not usually as useful in a text context, so you may wish to exclude the text/plain data in this situation.

-

In chrome or other privileged code, you may also use the image/jpeg, image/png or image/gif types, depending on the type of image. The data should be an object which implements the nsIInputStream interface. When this stream is read, it should provide the data bits for the image, as if the image was a file of that type.

-

You should also include the application/x-moz-file type if the image is located on disk. In fact, this a common way in which image files are dragged.

-

It is important to set the data in the right order, from most specific to least specific. The image type such as image/jpeg should come first, followed by the application/x-moz-file type. Next, you should set the text/uri-list data and finally the text/plain data. For example:

-
var dt = event.dataTransfer;
-dt.mozSetDataAt("image/png", stream, 0);
-dt.mozSetDataAt("application/x-moz-file", file, 0);
-dt.setData("text/uri-list", imageurl);
-dt.setData("text/plain", imageurl);
-
-

Note that the mozGetDataAt method is used for non-text data. As some contexts may only include some of these types, it is important to check which type is made available when receiving dropped images.

-

Dragging Nodes

-

Nodes and elements in a document may be dragged using the application/x-moz-node type. This data for the type should be a DOM node. This allows the drop target to receive the actual node where the drag was started from. Note that callers from a different domain will not be able to access the node even when it has been dropped.

-

You should always include a plain text alternative for the node.

-

Dragging Custom Data

-

You can also use other types that you make up for custom purposes. You should strive to always include a plain text alternative unless that object being dragged is specific to a particular site or application. In this case, the custom type ensures that the data cannot be dropped elsewhere.

-

Dragging files to an operating system folder

-

There are cases in which you may want to add a file to an existing drag event session, and you may also want to write the file to disk when the drop operation happens over a folder in the operating system when your code receives notification of the target folder's location. This only works in extensions (or other privileged code) and the data flavor "application/moz-file-promise" should be used. The following sample offers an overview of this advanced case:

-
// currentEvent is a given existing drag operation event
-
-currentEvent.dataTransfer.setData("text/x-moz-url", URL);
-currentEvent.dataTransfer.setData("application/x-moz-file-promise-url", URL);
-currentEvent.dataTransfer.setData("application/x-moz-file-promise-filename", leafName);
-currentEvent.dataTransfer.mozSetDataAt('application/x-moz-file-promise',
-                  new dataProvider(success,error),
-                  0, Components.interfaces.nsISupports);
-
-function dataProvider(){}
-
-dataProvider.prototype = {
-  QueryInterface : function(iid) {
-    if (iid.equals(Components.interfaces.nsIFlavorDataProvider)
-                  || iid.equals(Components.interfaces.nsISupports))
-      return this;
-    throw Components.results.NS_NOINTERFACE;
-  },
-  getFlavorData : function(aTransferable, aFlavor, aData, aDataLen) {
-    if (aFlavor == 'application/x-moz-file-promise') {
-
-       var urlPrimitive = {};
-       var dataSize = {};
-
-       aTransferable.getTransferData('application/x-moz-file-promise-url', urlPrimitive, dataSize);
-       var url = new String(urlPrimitive.value.QueryInterface(Components.interfaces.nsISupportsString));
-       console.log("URL file orignal is = " + url);
-
-       var namePrimitive = {};
-       aTransferable.getTransferData('application/x-moz-file-promise-filename', namePrimitive, dataSize);
-       var name = new String(namePrimitive.value.QueryInterface(Components.interfaces.nsISupportsString));
-
-       console.log("target filename is = " + name);
-
-       var dirPrimitive = {};
-       aTransferable.getTransferData('application/x-moz-file-promise-dir', dirPrimitive, dataSize);
-       var dir = dirPrimitive.value.QueryInterface(Components.interfaces.nsILocalFile);
-
-       console.log("target folder is = " + dir.path);
-
-       var file = Cc['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
-       file.initWithPath(dir.path);
-       file.appendRelativePath(name);
-
-       console.log("output final path is =" + file.path);
-
-       // now you can write or copy the file yourself...
-    }
-  }
-}
-
-

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

diff --git a/files/es/web/api/htmlcanvaselement/toblob/index.html b/files/es/web/api/htmlcanvaselement/toblob/index.html deleted file mode 100644 index 4759cd6250..0000000000 --- a/files/es/web/api/htmlcanvaselement/toblob/index.html +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: HTMLCanvasElement.toBlob() -slug: Web/API/HTMLCanvasElement/toBlob -translation_of: Web/API/HTMLCanvasElement/toBlob ---- -
-
-
{{APIRef("Canvas API")}}
-
-
- -

EL metodo HTMLCanvasElement.toBlob() crea un objeto {{domxref("Blob")}} que representa la imagen contenida en el canvas; este archivo puede ser cacheado en el disco oo guardado en la memoria a desicion del  user agent. Si la propiedad type no se especifica el tipo de la imagen será image/png. La imagen creada tiene una resolución de 96dpi.
- El tercer argumento es usado con las imagenes  image/jpeg para especificar la calidad de salida.

- -

Syntax

- -
void canvas.toBlob(callback, type, encoderOptions);
-
- -

Parameters

- -
-
callback
-
A callback function with the resulting {{domxref("Blob")}} object as a single argument.
-
type {{optional_inline}}
-
A {{domxref("DOMString")}} indicating the image format. The default type is image/png.
-
encoderOptions {{optional_inline}}
-
A {{jsxref("Number")}} between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored.
-
- -

Return value

- -

None.

- -

Examples

- -

Getting a file representing the canvas

- -

Once you have drawn content into a canvas, you can convert it into a file of any supported image format. The code snippet below, for example, takes the image in the {{HTMLElement("canvas")}} element whose ID is "canvas", obtains a copy of it as a PNG image, then appends a new {{HTMLElement("img")}} element to the document, whose source image is the one created using the canvas.

- -
var canvas = document.getElementById("canvas");
-
-canvas.toBlob(function(blob) {
-  var newImg = document.createElement("img"),
-      url = URL.createObjectURL(blob);
-
-  newImg.onload = function() {
-    // no longer need to read the blob so it's revoked
-    URL.revokeObjectURL(url);
-  };
-
-  newImg.src = url;
-  document.body.appendChild(newImg);
-});
-
- -

Note that here we're creating a PNG image; if you add a second parameter to the toBlob() call, you can specify the image type. For example, to get the image in JPEG format:

- -
 canvas.toBlob(function(blob){...}, "image/jpeg", 0.95); // JPEG at 95% quality
- -
-

A way to convert a canvas to an ico (Mozilla only)

- -

This uses -moz-parse to convert the canvas to ico. Windows XP doesn't support converting from PNG to ico, so it uses bmp instead. A download link is created by setting the download attribute. The value of the download attribute is the name it will use as the file name.

- -
var canvas = document.getElementById("canvas");
-var d = canvas.width;
-ctx = canvas.getContext("2d");
-ctx.beginPath();
-ctx.moveTo(d / 2, 0);
-ctx.lineTo(d, d);
-ctx.lineTo(0, d);
-ctx.closePath();
-ctx.fillStyle = "yellow";
-ctx.fill();
-
-function blobCallback(iconName) {
-  return function(b) {
-    var a = document.createElement("a");
-    a.textContent = "Download";
-    document.body.appendChild(a);
-    a.style.display = "block";
-    a.download = iconName + ".ico";
-    a.href = window.URL.createObjectURL(b);
-  }
-}
-canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon',
-              '-moz-parse-options:format=bmp;bpp=32');
-
- -

Save toBlob to disk with OS.File (chrome/add-on context only)

- -
-

This technique saves it to the desktop and is only useful in Firefox chrome context or add-on code as OS APIs are not present on web sites.

-
- -
var canvas = document.getElementById("canvas");
-var d = canvas.width;
-ctx = canvas.getContext("2d");
-ctx.beginPath();
-ctx.moveTo(d / 2, 0);
-ctx.lineTo(d, d);
-ctx.lineTo(0, d);
-ctx.closePath();
-ctx.fillStyle = "yellow";
-ctx.fill();
-
-function blobCallback(iconName) {
-  return function(b) {
-    var r = new FileReader();
-    r.onloadend = function () {
-    // r.result contains the ArrayBuffer.
-    Cu.import('resource://gre/modules/osfile.jsm');
-    var writePath = OS.Path.join(OS.Constants.Path.desktopDir,
-                                 iconName + '.ico');
-    var promise = OS.File.writeAtomic(writePath, new Uint8Array(r.result),
-                                      {tmpPath:writePath + '.tmp'});
-    promise.then(
-      function() {
-        console.log('successfully wrote file');
-      },
-      function() {
-        console.log('failure writing file')
-      }
-    );
-  };
-  r.readAsArrayBuffer(b);
-  }
-}
-
-canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon',
-              '-moz-parse-options:format=bmp;bpp=32');
- -

Polyfill

- -

A low performance polyfill based on toDataURL.

- -
if (!HTMLCanvasElement.prototype.toBlob) {
- Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
-  value: function (callback, type, quality) {
-
-    var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
-        len = binStr.length,
-        arr = new Uint8Array(len);
-
-    for (var i=0; i<len; i++ ) {
-     arr[i] = binStr.charCodeAt(i);
-    }
-
-    callback( new Blob( [arr], {type: type || 'image/png'} ) );
-  }
- });
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML5.1')}}No change
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}[1]{{CompatGeckoDesktop('19')}}{{CompatIE(10)}}{{property_prefix("ms")}}{{CompatNo}}{{CompatNo}}[2]
Image quality parameter (jpeg){{CompatNo}}{{CompatGeckoDesktop('25')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("19")}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
Image quality parameter (jpeg){{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25")}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
-
- -

[1] Chrome does not implement this feature yet. See bug 67587.

- -

[2] WebKit does not implement this feature yet. See {{WebKitBug("71270")}}.

- -

See also

- - diff --git a/files/es/web/api/mediasource/index.html b/files/es/web/api/mediasource/index.html deleted file mode 100644 index 2f5ff914c9..0000000000 --- a/files/es/web/api/mediasource/index.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: MediaSource -slug: Web/API/MediaSource -translation_of: Web/API/MediaSource ---- -

{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}

- -

El MediaSource interfaz representa un recurso de media en datos por un {{domxref("HTMLMediaElement")}} objeto. Un MediaSource objeto puede ser atribuido a un {{domxref("HTMLMediaElement")}} para ser reproducido por el usuario.

- -

Constructor

- -
-
{{domxref("MediaSource.MediaSource", "MediaSource()")}}
-
construye y retorna un MediaSource objeto sin asociar un recurso con buffers.
-
- -

Propiedades

- -

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

- -
-
{{domxref("MediaSource.sourceBuffers")}} {{readonlyInline}}
-
Returns a {{domxref("SourceBufferList")}} object containing the list of {{domxref("SourceBuffer")}} objects associated with this MediaSource.
-
{{domxref("MediaSource.activeSourceBuffers")}} {{readonlyInline}}
-
Returns a {{domxref("SourceBufferList")}} object containing a subset of the {{domxref("SourceBuffer")}} objects contained within {{domxref("SourceBuffers")}} — the list of objects providing the selected video track,  enabled audio tracks, and shown/hidden text tracks.
-
{{domxref("MediaSource.readyState")}} {{readonlyInline}}
-
Returns an enum representing the state of the current MediaSource, whether it is not currently attached to a media element (closed), attached and ready to receive {{domxref("SourceBuffer")}} objects (open), or attached but the stream has been ended via {{domxref("MediaSource.endOfStream()")}} (ended.)
-
{{domxref("MediaSource.duration")}}
-
Gets and sets the duration of the current media being presented.
-
- -
-
- -
-
- -

Methods

- -

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

- -
-
{{domxref("MediaSource.addSourceBuffer()")}}
-
Creates a new {{domxref("SourceBuffer")}} of the given MIME type and adds it to the MediaSource's {{domxref("SourceBuffers")}} list.
-
{{domxref("MediaSource.removeSourceBuffer()")}}
-
Removes the given {{domxref("SourceBuffer")}} from the {{domxref("SourceBuffers")}} list associated with this MediaSource object.
-
{{domxref("MediaSource.endOfStream()")}}
-
Signals the end of the stream.
-
-

Static methods

-
-
{{domxref("MediaSource.isTypeSupported()")}}
-
Returns a {{domxref("Boolean")}} value indicating if the given MIME type is supported by the current user agent — this is, if it can successfully create {{domxref("SourceBuffer")}} objects for that MIME type.
-
- -

Examples

- -

The following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can. This example was written by Nick Desaulniers and can be viewed live here (you can also download the source for further investigation.)

- -
var video = document.querySelector('video');
-
-var assetURL = 'frag_bunny.mp4';
-// Need to be specific for Blink regarding codecs
-// ./mp4info frag_bunny.mp4 | grep Codec
-var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
-
-if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
-  var mediaSource = new MediaSource;
-  //console.log(mediaSource.readyState); // closed
-  video.src = URL.createObjectURL(mediaSource);
-  mediaSource.addEventListener('sourceopen', sourceOpen);
-} else {
-  console.error('Unsupported MIME type or codec: ', mimeCodec);
-}
-
-function sourceOpen (_) {
-  //console.log(this.readyState); // open
-  var mediaSource = this;
-  var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
-  fetchAB(assetURL, function (buf) {
-    sourceBuffer.addEventListener('updateend', function (_) {
-      mediaSource.endOfStream();
-      video.play();
-      //console.log(mediaSource.readyState); // ended
-    });
-    sourceBuffer.appendBuffer(buf);
-  });
-};
-
-function fetchAB (url, cb) {
-  console.log(url);
-  var xhr = new XMLHttpRequest;
-  xhr.open('get', url);
-  xhr.responseType = 'arraybuffer';
-  xhr.onload = function () {
-    cb(xhr.response);
-  };
-  xhr.send();
-};
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Media Source Extensions', '#mediasource', 'MediaSource')}}{{Spec2('Media Source Extensions')}}Initial definition.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{CompatGeckoDesktop("25.0")}}[1]
- {{CompatGeckoDesktop("42.0")}}
11[2]158
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.4.4 -

{{CompatNo}}

-
{{CompatNo}}1130{{CompatNo}}
-
- -

[1] Available after switching the about:config preference media.mediasource.enabled to true. In addition, support was limited to a whitelist of sites, for example YouTube, Netflix, and other popular streaming sites. The whitelist was removed and Media Source Extensions was enabled by default in 42+ for all sites.

- -

[2] Only works on Windows 8+.

- -

See also

- - diff --git a/files/es/web/api/webvtt_api/index.html b/files/es/web/api/webvtt_api/index.html deleted file mode 100644 index 7a54969a31..0000000000 --- a/files/es/web/api/webvtt_api/index.html +++ /dev/null @@ -1,903 +0,0 @@ ---- -title: Formato de pistas de texto para la web (WebVTT) -slug: Web/API/WebVTT_API -translation_of: Web/API/WebVTT_API ---- -
{{DefaultAPISidebar("WebVTT")}}
- -

El formato de pistas de texto para la web (WebVTT) es un formato para mostrar pistas de texto en le tiempo (como subtítulos) usando el elemento {{HTMLElement("track")}}. El propósito principal de los archivos de WebVTT es superponer pistas de texto a un elemento {{HTMLElement("video")}}. WebVTT es un formato basado en el texto, que debe de ser codificado usando {{Glossary("UTF-8")}}. Donde puedes usar espacios también puedes usar tabulaciones. También hay una pequeña API disponible para representar y manejar estas pistas de texto y los datos necesarios para realizar la reproducción del texto en los momentos correctos.

- -

Archivos WebVTT

- -

El tipo MIME de los archivos WebVTT es text/vtt.

- -

Un archivo WebVTT (.vtt) contiene apuntes, que pueden ser tanto de una línea como de varias, como se muestra debajo:

- -
WEBVTT
-
-00:01.000 --> 00:04.000
-- Nunca bebas nitrógeno líquido.
-
-00:05.000 --> 00:09.000
-- Podría perforar tu estómago.
-- Podrías morir.
-
-NOTE Esta es la última línea en el archivo
-
- -

Estructura WebVTT

- -

La estructura de un archivo WevWTT consiste de los siguientes componentes, algunos de ellos opcionales, en este orden:

- - - -
Ejemplo 1 - El archivo WebVTT más simple posible
- -
WEBVTT
-
- -
Ejemplo 2 - Archivo WebVTT muy simple con un encabezado de texto
- -
WEBVTT - Este archivo no tiene anotaciones.
-
- -
Ejemplo 3 - Ejemplo de un archivo WebVTT común con encabezado y anotaciones
- -
WEBVTT - Este archivo tiene anotaciones.
-
-14
-00:01:14.815 --> 00:01:18.114
-- ¿Qué?
-- ¿Dónde estamos ahora?
-
-15
-00:01:18.171 --> 00:01:20.991
-- Este es el país de los murciélagos grandes.
-
-16
-00:01:21.058 --> 00:01:23.868
-- [ Murciélagos chillando ]
-- Ellos no se pondrán entu pelo. Ellos están persiguiendo a los bichos.
-
- -

Estructura interna de un archivo WebVTT

- -

Vamos a reexaminar uno de nuestros ejemplos previos, y mirar la estructura de las anotaciones con un poco más de detalle.

- -
WEBVTT
-
-00:01.000 --> 00:04.000
-- Nunca bebas nitrógeno líquido.
-
-00:05.000 --> 00:09.000
-- Podría perforar tu estómago.
-- Podrías morir.
-
-NOTE Esta es la última línea en el archivo
- -

En el caso de cada anotación:

- - - -

También podemos poner comentarios en nuestro archivo .vtt, para ayudarnos a recorddar información importante sobre las partes de nuestro archivo. Estas deben estar en líneas separadas empezando con la cadena NOTE. Aprenderas más sobre eso en la siguiente sección.

- -

Es importante no usar líneas en blanco extras dentro de una anotación, por ejemplo entre las líneas de tiempo y las anotaciones. WebVTT está basado en líneas, una línea en blanco finalizará la anotación.

- -

Comentarios en WebVTT

- -

Los comentarios son un componente opcional que se puede usar para añadir informacion a un archivo WebVTT. Los comentarios estan pensados para aquellos que leen el archivo y no se muestran con las pistas de texto. Los comentarios pueden contener saltos de línea pero no una línea en blanco, que es equivalente a dos saltos de línea consecutivos. Una línea en blanco indica el fin de un comentario.

- -

Un comentario no puede contener la cadena de texto "-->", el símbolo &, o el signo de menor que (<). Si quisieses usar esos caracteres necesitarías hacer un escape usando por ejemplo &amp; para el símbolo &, y &lt; para menor que (<). Tambien es recomendado que uses la secuencia de escape de mayor que &gt; en vez de el simbo de mayor que (>) para evitar la confusión con etiquetas.

- -

Un comentario consiste en tres partes:

- - - -
Ejemplo 4 - Ejemplo común de WebVTT
- -
NOTE Esto es un comentario
-
- -
Ejemplo 5 - Comentario multilínea
- -
NOTE
-Un comentario que está ocupando
-más de una línea.
-
-NOTE También puedes hacer un comentario
-que ocupe más de una línea de esta manera.
-
- -
Ejemplo 6 - Uso común de comentarios
- -
WEBVTT - Traducción de la película que me gusta
-
-NOTE
-Esta traducción esta hecha por Kyle para que
-Algunos amigos puedan verla con sus padres.
-
-1
-00:02:15.000 --> 00:02:20.000
-- Ta en kopp varmt te.
-- Det är inte varmt.
-
-2
-00:02:20.000 --> 00:02:25.000
-- Har en kopp te.
-- Det smakar som te.
-
-NOTE Esta ultima línea puede no estar bien traducida.
-
-3
-00:02:25.000 --> 00:02:30.000
-- Ta en kopp
-
- -

Estilizando anotaciones WebVTT

- -

Tu puedes estilizar anotaciones WebVTT buscado elementos que coincidan con el pseudoelemento {{cssxref("::cue")}}.

- -

Dentro del CSS del sitio

- -
video::cue {
-  background-image: linear-gradient(to bottom, dimgray, lightgray);
-  color: papayawhip;
-}
-
-video::cue(b) {
-  color: peachpuff;
-}
-
- -

Aquí, todos los elementos de video estan estilizados para usar un gradiente gris como fondo, con "papayawhip" como color principal. Además el texto en negrita usando el elemento {{HTMLElement("b")}} tiene el color "peachpuff".

- -

El ejemplo HTML de abajo actualemte se encarga de mostrar los archivos multimedia él solo.

- -
<video controls autoplay src="video.webm">
- <track default src="track.vtt">
-</video>
-
- -

Within the WebVTT file itself

- -

You can also define the style directly in the WebVTT file. In this case, you insert your CSS rules into the file with each rule preceded by the string "STYLE" all by itelf on a line of text, as shown below:

- -
WEBVTT
-
-STYLE
-::cue {
-  background-image: linear-gradient(to bottom, dimgray, lightgray);
-  color: papayawhip;
-}
-/* Style blocks cannot use blank lines nor "dash dash greater than" */
-
-NOTE comment blocks can be used between style blocks.
-
-STYLE
-::cue(b) {
-  color: peachpuff;
-}
-
-00:00:00.000 --> 00:00:10.000
-- Hello <b>world</b>.
-
-NOTE style blocks cannot appear after the first cue.
- -

We can also use identifiers inside WebVTT file, which can be used for defining a new style for some particular cues in the file. The example where we wanted the transcription text to be red highlighted and the other part to remain normal, we can define it as follows using CSS. Where it must be noted that the CSS uses escape sequences the way they are used in HTML pages:

- -
WEBVTT
-
-1
-00:00.000 --> 00:02.000
-That’s an, an, that’s an L!
-
-crédit de transcription
-00:04.000 --> 00:05.000
-Transcrit par Célestes™
-
- -
::cue(#\31) { color: lime; }
-::cue(#crédit\ de\ transcription) { color: red; }
- -

Positioning of text tracks is also supported, by including positioning information after the timings in a cue, as seen below (see {{anch("Cue settings")}} for more information):

- -
WEBVTT
-
-00:00:00.000 --> 00:00:04.000 position:10%,line-left align:left size:35%
-Where did he go?
-
-00:00:03.000 --> 00:00:06.500 position:90% align:right size:35%
-I think he went down this lane.
-
-00:00:04.000 --> 00:00:06.500 position:45%,line-right align:center size:35%
-What are you waiting for?
- -

WebVTT cues

- -

A cue is a single subtitle block that has a single start time, end time, and textual payload. Example 6 consists of the header, a blank line, and then five cues separated by blank lines. A cue consists of five components:

- - - -
Example 7 - Example of a cue
- -
1 - Title Crawl
-00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
-Some time ago in a place rather distant....
- -

Cue identifier

- -

The identifier is a name that identifies the cue. It can be used to reference the cue from a script. It must not contain a newline and cannot contain the string "-->". It must end with a single newline. They do not have to be unique, although it is common to number them (e.g., 1, 2, 3, ...).

- -
Example 8 - Cue identifier from Example 7
- -
1 - Title Crawl
- -
Example 9 - Common usage of identifiers
- -
WEBVTT
-
-1
-00:00:22.230 --> 00:00:24.606
-This is the first subtitle.
-
-2
-00:00:30.739 --> 00:00:34.074
-This is the second.
-
-3
-00:00:34.159 --> 00:00:35.743
-Third
-
- -

Cue timings

- -

A cue timing indicates when the cue is shown. It has a start and end time which are represented by timestamps. The end time must be greater than the start time, and the start time must be greater than or equal to all previous start times. Cues may have overlapping timings.

- -

If the WebVTT file is being used for chapters ({{HTMLElement("track")}} {{htmlattrxref("kind")}} is chapters) then the file cannot have overlapping timings.

- -

Each cue timing contains five components:

- - - -

The timestamps must be in one of two formats:

- - - -

Where the components are defined as follows:

- - - -
Example 10 - Basic cue timing examples
- -
00:00:22.230 --> 00:00:24.606
-00:00:30.739 --> 00:00:34.074
-00:00:34.159 --> 00:00:35.743
-00:00:35.827 --> 00:00:40.122
- -
Example 11 - Overlapping cue timing examples
- -
00:00:00.000 --> 00:00:10.000
-00:00:05.000 --> 00:01:00.000
-00:00:30.000 --> 00:00:50.000
- -
Example 12 - Non-overlapping cue timing examples
- -
00:00:00.000 --> 00:00:10.000
-00:00:10.000 --> 00:01:00.581
-00:01:00.581 --> 00:02:00.100
-00:02:01.000 --> 00:02:01.000
- -

Cue settings

- -

Cue settings are optional components used to position where the cue payload text will be displayed over the video. This includes whether the text is displayed horizontally or vertically. There can be zero or more of them, and they can be used in any order so long as each setting is used no more than once.

- -

The cue settings are added to the right of the cue timings. There must be one or more spaces between the cue timing and the first setting and between each setting. A setting's name and value are separated by a colon. The settings are case sensitive so use lower case as shown. There are five cue settings:

- - - -
Example 13 - Cue setting examples
- -

The first line demonstrates no settings. The second line might be used to overlay text on a sign or label. The third line might be used for a title. The last line might be used for an Asian language.

- -
00:00:05.000 --> 00:00:10.000
-00:00:05.000 --> 00:00:10.000 line:63% position:72% align:start
-00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
-00:00:05.000 --> 00:00:10.000 vertical:rt line:-1 align:end
-
- -

Cue payload

- -

The payload is where the main information or content is located. In normal usage the payload contains the subtitles to be displayed. The payload text may contain newlines but it cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a cue.

- -

A cue text payload cannot contain the string "-->", the ampersand character (&), or the less-than sign (<). Instead use the escape sequence "&amp;" for ampersand and "&lt;" for less-than. It is also recommended that you use the greater-than escape sequence "&gt;" instead of the greater-than character (>) to avoid confusion with tags. If you are using the WebVTT file for metadata these restrictions do not apply.

- -

In addition to the three escape sequences mentioned above, there are fours others. They are listed in the table below.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 6 - Escape sequences
NameCharacterEscape Sequence
Ampersand&&amp;
Less-than<&lt;
Greater-than>&gt;
Left-to-right mark&lrm;
Right-to-left mark&rlm;
Non-breaking space &nbsp;
- -

Cue payload text tags

- -

There are a number of tags, such as <bold>, that can be used. However, if the WebVTT file is used in a {{HTMLElement("track")}} element where the attribute {{htmlattrxref("kind")}} is chapters then you cannot use tags.

- - - -

The following tags are the HTML tags allowed in a cue and require opening and closing tags (e.g., <b>text</b>).

- - - -

Interfaces

- -

There are two interfaces or APIs used in WebVTT which are:

- -

VTTCue interface

- -

It is used for providing an interface in Document Object Model API, where different attributes supported by it can be used to prepare and alter the cues in number of ways.

- -

Constructor is the first point for starting the Cue which is defined using the default constructor VTTCue(startTime, endTime, text) where starting time, ending time and text for cue can be adjusted. After that we can set the region for that particular cue to which this cue belongs using cue.region. Vertical, horizontal, line, lineAlign, Position, positionAlign, text, size and Align can be used to alter the cue and its formation, just like we can alter the objects form, shape and visibility in HTML using CSS. But the VTTCue interface is within the WebVTT provides the vast range of adjustment variables which can be used directly to alter the Cue. Following interface can be used to expose WebVTT cues in DOM API:

- -
enum AutoKeyword { "auto" };
-enum DirectionSetting { "" /* horizontal */, "rl", "lr" };
-enum LineAlignSetting { "start", "center", "end" };
-enum PositionAlignSetting { "line-left", "center", "line-right", "auto" };
-enum AlignSetting { "start", "center", "end", "left", "right" };
-[Constructor(double startTime, double endTime, DOMString text)]
-interface VTTCue : TextTrackCue {
-  attribute VTTRegion? region;
-  attribute DirectionSetting vertical;
-  attribute boolean snapToLines;
-  attribute (double or AutoKeyword) line;
-  attribute LineAlignSetting lineAlign;
-  attribute (double or AutoKeyword) position;
-  attribute PositionAlignSetting positionAlign;
-  attribute double size;
-  attribute AlignSetting align;
-  attribute DOMString text;
-  DocumentFragment getCueAsHTML();
-};
- -

VTT Region interface

- -

This is the second interface in WebVTT API.

- -

The new keyword can be used for defining a new VTTRegion object which can then be used for containing the multiple cues. There are several properties of VTTRegion which are width, lines, regionAnchorX, RegionAnchorY, viewportAnchorX, viewportAnchorY and scroll that can be used to specify the look and feel of this VTT region. The interface code is given below which can be used to expose the WebVTT regions in DOM API:

- -
enum ScrollSetting { "" /* none */, "up" };
-[Constructor]
-interface VTTRegion {
-  attribute double width;
-  attribute long lines;
-  attribute double regionAnchorX;
-  attribute double regionAnchorY;
-  attribute double viewportAnchorX;
-  attribute double viewportAnchorY;
-  attribute ScrollSetting scroll;
-};
- -

Methods and properties

- -

The methods used in WebVTT are those which are used to alter the cue or region as the attributes for both interfaces are different. We can categorize them for better understanding relating to each interface in WebVTT:

- - - -

Tutorial on how to write a WebVTT file

- -

There are few steps that can be followed to write a simple webVTT file. Before start, it must be noted that you can make use of a notepad and then save the file as ‘.vtt’ file. Steps are given below:

- -
    -
  1. Open a notepad.
  2. -
  3. The first line of WebVTT is standardized similar to the way some other languages require you to put headers as the file starts to indicate the file type. On the very first line you have to write:
  4. -
- -
WEBVTT
- -

      3. Leave the second line blank, and on the third line the time for first cue is to be specified. For example, for a first cue starting at time 1 second and ending at 5 seconds, it is written as:

- -
00:01.000 --> 00:05.000
- -
    -
  1. On the next line you can write the caption for this cue which will run from 1st second to the 5th second, inclusive.
  2. -
  3. Following the similar steps, a complete WebVTT file for specific video or audio file can be made.
  4. -
- -

CSS pseudo-classes

- -

CSS pseudo classes allow us to classify the type of object which we want to differentiate from other types of objects. It works in similar manner in WebVTT files as it works in HTML file.

- -

It is one of the good features supported by WebVTT is the localization and use of class elements which can be used in same way they are used in HTML and CSS to classify the style for particular type of objects, but here these are used for styling and classifying the Cues as shown below:

- -
WEBVTT
-
-04:02.500 --> 04:05.000
-J’ai commencé le basket à l'âge de 13, 14 ans
-
-04:05.001 --> 04:07.800
-Sur les <i.foreignphrase><lang en>playground</lang></i>, ici à Montpellier
- -

In the above example it can be observed that we can use the identifier and pseudo class name for defining the language of caption, where <i> tag is for italics.

- -

The type of pseudo class is determined by the selector it is using and working is similar in nature as it works in HTML. Following CSS pseudo classes can be used:

- - - -

Where p and a are the tags which are used in HTML for paragraph and link, respectively and they can be replaced by identifiers which are used for Cues in WebVTT file.

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("WebVTT")}}{{Spec2("WebVTT")}}Initial definition
- -

Browser compatibility

- -

VTTCue interface

- -
- - -

{{Compat("api.VTTCue", 0)}}

- -

TextTrack interface

- -
- - -

{{Compat("api.TextTrack", 0)}}

- -

Notes

-
-
- -

Prior to Firefox 50, the AlignSetting enum (representing possible values for {{domxref("VTTCue.align")}}) incorrectly included the value "middle" instead of "center". This has been corrected.

- -

WebVTT was implemented in Firefox 24 behind the preference {{pref("media.webvtt.enabled")}}, which is disabled by default; you can enable it by setting this preference to true. WebVTT is enabled by default starting in Firefox 31 and can be disabled by setting the preference to false.

- -

Prior to Firefox 58, the REGION keyword was creating {{domxref("VTTRegion")}} objects, but they were not being used. Firefox 58 now fully supports VTTRegion and its use; however, this feature is disabled by default behind the preference media.webvtt.regions.enabled; set it to true to enable region support in Firefox 58. Regions are enabled by default starting in Firefox 59 (see bugs {{bug(1338030)}} and {{bug(1415805)}}).

diff --git a/files/es/web/api/window/domcontentloaded_event/index.html b/files/es/web/api/window/domcontentloaded_event/index.html deleted file mode 100644 index 0659abde6f..0000000000 --- a/files/es/web/api/window/domcontentloaded_event/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: DOMContentLoaded -slug: Web/API/Window/DOMContentLoaded_event -translation_of: Web/API/Window/DOMContentLoaded_event -original_slug: Web/Events/DOMContentLoaded ---- -

El evento DOMContentLoaded es disparado cuando el documento HTML ha sido completamente cargado y parseado, sin esperar hojas de estilo, images y subframes para  finalizar la carga. Un evento muy diferente - load - debería ser usado solo para detectar una carga completa de la página. Es un error increíblemente popular usar load cuando DOMContentLoaded sería mucho más apropiado, así que úsalo con cuidado.

- -

JavaScript síncrono pausa el parseo del DOM.

- -

También hay mucho propósito general y bibliotecas autónomas que ofrecen métodos de navegador cruzado para detectar que el DOM está preparado.

- -

Speeding up

- -

If you want DOM to get parsed as fast as possible after the user had requested the page, some things you could do is turn your JavaScript asynchronous and to optimize loading of stylesheets which if used as usual, slow down page load due to being loaded in parallel, "stealing" traffic from the main html document.

- -

General info

- -
-
Specification
-
HTML5
-
Interface
-
Event
-
Bubbles
-
Yes
-
Cancelable
-
Yes (although specified as a simple event that isn't cancelable)
-
Target
-
Document
-
Default Action
-
None.
-
- -

Properties

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The event target (the topmost target in the DOM tree).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
- -

Example

- -
<script>
-  document.addEventListener("DOMContentLoaded", function(event) {
-    console.log("DOM fully loaded and parsed");
-  });
-</script>
-
- -
<script>
-  document.addEventListener("DOMContentLoaded", function(event) {
-    console.log("DOM fully loaded and parsed");
-  });
-
-for(var i=0; i<1000000000; i++)
-{} // this synchronous script is going to delay parsing of the DOM. So the DOMContentLoaded event is going to launch later.
-</script>
-
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0[1]{{CompatGeckoDesktop("1")}}[1]9.0[2]9.03.1[1]
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}[1]{{CompatGeckoMobile("1")}}[1]{{CompatUnknown}}[2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]
-
- -

[1] Bubbling for this event is supported by at least Gecko 1.9.2, Chrome 6, and Safari 4.

- -

[2] Internet Explorer 8 supports the readystatechange event, which can be used to detect when the DOM is ready. In earlier versions of Internet Explorer, this state can be detected by repeatedly trying to execute document.documentElement.doScroll("left");, as this snippet will throw an error until the DOM is ready.

- - - - diff --git a/files/es/web/api/worker/postmessage/index.html b/files/es/web/api/worker/postmessage/index.html deleted file mode 100644 index c47fe400fc..0000000000 --- a/files/es/web/api/worker/postmessage/index.html +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: Worker.postMessage() -slug: Web/API/Worker/postMessage -translation_of: Web/API/Worker/postMessage ---- -

{{APIRef("Web Workers API")}}

- -

Web Workers API posee un metodo llamado postMessage() el cual envia un mensaje al ambito del worker. Este metodo acepta un parametro, el cual es un dato enviado al worker. El dato puede ser un valor o objeto controlado por el algoritmo strctured clone (incluye referencias ciclicas).

- -

El Worker puede enviar de vuelta información al hilo que lo genero usando el metodo {{domxref("DedicatedWorkerGlobalScope.postMessage")}}.

- -

Syntax

- -
myWorker.postMessage(aMessage, transferList);
- -

Parameters

- -
-
aMessage
-
The object to deliver to the worker; this will be in the data field in the event delivered to the {{domxref("DedicatedWorkerGlobalScope.onmessage")}} handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references.
-
transferList {{optional_inline}}
-
An optional array of {{domxref("Transferable")}} objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and it becomes available only to the worker it was sent to.
-
Only {{domxref("MessagePort")}} and {{domxref("ArrayBuffer")}} objects can be transferred.
-
- -

Returns

- -

Void.

- -

Example

- -

The following code snippet shows creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor. When either of two form inputs (first and second) have their values changed, {{event("change")}} events invoke postMessage() to send the value of both inputs to the current worker.

- -
var myWorker = new Worker("worker.js");
-
-first.onchange = function() {
-  myWorker.postMessage([first.value,second.value]);
-  console.log('Message posted to worker');
-}
-
-second.onchange = function() {
-  myWorker.postMessage([first.value,second.value]);
-  console.log('Message posted to worker');
-}
-
- -

For a full example, see ourBasic dedicated worker example (run dedicated worker).

- -
-

Note: postMessage() can only send a single object at once. As seen above, if you want to pass multiple values you can send an array.

-
- -

Transfer Example

- -

This example is of a Firefox addon that transfers an ArrayBuffer from the main thread to the ChromeWorker, and then the ChromeWorker trasnfers it back to the main thread.

- -

Main thread code:

- -
var myWorker = new ChromeWorker(self.path + 'myWorker.js');
-
-function handleMessageFromWorker(msg) {
-    console.log('incoming message from worker, msg:', msg);
-    switch (msg.data.aTopic) {
-        case 'do_sendMainArrBuff':
-            sendMainArrBuff(msg.data.aBuf)
-            break;
-        default:
-            throw 'no aTopic on incoming message to ChromeWorker';
-    }
-}
-
-myWorker.addEventListener('message', handleMessageFromWorker);
-
-// Ok lets create the buffer and send it
-var arrBuf = new ArrayBuffer(8);
-console.info('arrBuf.byteLength pre transfer:', arrBuf.byteLength);
-
-myWorker.postMessage(
-    {
-        aTopic: 'do_sendWorkerArrBuff',
-        aBuf: arrBuf // The array buffer that we passed to the transferrable section 3 lines below
-    },
-    [
-        arrBuf // The array buffer we created 9 lines above
-    ]
-);
-
-console.info('arrBuf.byteLength post transfer:', arrBuf.byteLength);
-
- -

Worker code

- -
self.onmessage = function (msg) {
-    switch (msg.data.aTopic) {
-        case 'do_sendWorkerArrBuff':
-                sendWorkerArrBuff(msg.data.aBuf)
-            break;
-        default:
-            throw 'no aTopic on incoming message to ChromeWorker';
-    }
-}
-
-function sendWorkerArrBuff(aBuf) {
-    console.info('from worker, PRE send back aBuf.byteLength:', aBuf.byteLength);
-
-    self.postMessage({aTopic:'do_sendMainArrBuff', aBuf:aBuf}, [aBuf]);
-
-    console.info('from worker, POST send back aBuf.byteLength:', aBuf.byteLength);
-}
-
- -

Output logged

- -
arrBuf.byteLength pre transfer: 8                              bootstrap.js:40
-arrBuf.byteLength post transfer: 0                             bootstrap.js:42
-
-from worker, PRE send back aBuf.byteLength: 8                  myWorker.js:5:2
-
-incoming message from worker, msg: message { ... }             bootstrap.js:20
-got back buf in main thread, aBuf.byteLength: 8                bootstrap.js:12
-
-from worker, POST send back aBuf.byteLength: 0                 myWorker.js:7:2
- -

We see that byteLength goes to 0 as it is trasnferred. To see a fully working example of this Firefox demo addon see here: GitHub :: ChromeWorker - demo-transfer-arraybuffer

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-worker-postmessage", "Worker.postMessage()")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#dom-worker-postmessage", "Worker.postMessage()")}}{{Spec2('Web Workers')}}Initial definition.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0 [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] Internet Explorer does not support {{domxref("Transferable")}} objects.

- -

See also

- - diff --git a/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html b/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html deleted file mode 100644 index 28675abd79..0000000000 --- a/files/es/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html +++ /dev/null @@ -1,232 +0,0 @@ ---- -title: Solicitudes síncronas y asíncronas -slug: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests -translation_of: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests ---- -

XMLHttpRequest soporta solicitudes síncronas y asíncronas, pero la mas preferida es la asíncrona por razones de rendimiento

- -

Las solicitudes síncronas bloquean la ejecución del código, mientras se procesa la solicitud, dejando a la pantalla congelada y dando una experiencia de usuario poco agradable

- -

Peticiones asíncronas

- -

Si se utiliza XMLHttpRequest de forma asíncrona, recibirá una devolución de llamada cuando los datos se hayan recibido . Esto permite que el navegador continúe funcionando de forma normal mientras se procesa la solicitud.

- -

Ejemplo: Enviar un archivo a la consola

- -

Este es el uso más simple de la asíncronia XMLHttpRequest.

- -
var xhr = new XMLHttpRequest();
-xhr.open("GET", "/bar/foo.txt", true);
-xhr.onload = function (e) {
-  if (xhr.readyState === 4) {
-    if (xhr.status === 200) {
-      console.log(xhr.responseText);
-    } else {
-      console.error(xhr.statusText);
-    }
-  }
-};
-xhr.onerror = function (e) {
-  console.error(xhr.statusText);
-};
-xhr.send(null); 
- -

En la linea 2, el ultimo parametro de open() , especifica true para indicar que la solicitud se tratara de forma asíncrona

- -

Line 3 creates an event handler function object and assigns it to the request's onload attribute.  This handler looks at the request's readyState to see if the transaction is complete in line 4, and if it is, and the HTTP status is 200, dumps the received content.  If an error occurred, an error message is displayed.

- -

Line 15 actually initiates the request.  The callback routine is called whenever the state of the request changes.

- -

Ejemplo: Creando una funcion estandar para leer archivos externos.

- -

In some cases you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener.

- -
function xhrSuccess () { this.callback.apply(this, this.arguments); }
-
-function xhrError () { console.error(this.statusText); }
-
-function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
-  var oReq = new XMLHttpRequest();
-  oReq.callback = fCallback;
-  oReq.arguments = Array.prototype.slice.call(arguments, 2);
-  oReq.onload = xhrSuccess;
-  oReq.onerror = xhrError;
-  oReq.open("get", sURL, true);
-  oReq.send(null);
-}
-
- -

Usage:

- -
function showMessage (sMsg) {
-  alert(sMsg + this.responseText);
-}
-
-loadFile("message.txt", showMessage, "New message!\n\n");
-
- -

The signature of the utility function loadFile declares (i) a target URL to read (via HTTP GET), (ii) a function to execute on successful completion of the XHR operation, and (iii) an arbitrary list of additional arguments that are "passed through" the XHR object to the success callback function.

- -

Line 1 declares a function invoked when the XHR operation completes successfully.  It, in turn, invokes the callback function specified in the invocation of the loadFile function (in this case, the function showMessage) which has been assigned to a property of the XHR object (Line 7). The additional arguments (if any) supplied to the invocation of function loadFile are "applied" to the running of the callback function.

- -

Line 3 declares a function invoked when the XHR operation fails to complete successfully.

- -

Line 7 stores on the XHR object the success callback function given as the second argument to loadFile.

- -

Line 8 slices the arguments array given to the invocation of loadFile. Starting with the third argument, all remaining arguments are collected, assigned to the arguments property of the variable oReq, passed to the success callback function xhrSuccess., and ultimately supplied to the callback function (in this case, showMessage) which is invoked by function xhrSuccess.

- -

Line 9 designates the function xhrSuccess as the callback to be invoked when the onload event fires, that is, when the XHR sucessfully completes.  

- -

Line 10 designates the function xhrError as the callback to be invoked when the XHR requests fails to complete.

- -

Line 11 specifies true for its third parameter to indicate that the request should be handled asynchronously.

- -

Line 12 actually initiates the request.

- -

Example: using a timeout

- -

You can use a timeout to prevent hanging your code forever while waiting for a read to occur. This is done by setting the value of the timeout property on the XMLHttpRequest object, as shown in the code below:

- -
function loadFile(sUrl, timeout, callback){
-
-    var args = arguments.slice(3);
-    var xhr = new XMLHttpRequest();
-    xhr.ontimeout = function () {
-        console.error("The request for " + url + " timed out.");
-    };
-    xhr.onload = function() {
-        if (xhr.readyState === 4) {
-            if (xhr.status === 200) {
-                callback.apply(xhr, args);
-            } else {
-                console.error(xhr.statusText);
-            }
-        }
-    };
-    xhr.open("GET", url, true);
-    xhr.timeout = timeout;
-    xhr.send(null);
-}
- -

Notice the addition of code to handle the "timeout" event by setting the ontimeout handler.

- -

Usage:

- -
function showMessage (sMsg) {
-  alert(sMsg + this.responseText);
-}
-
-loadFile("message.txt", 2000, showMessage, "New message!\n");
-
- -

Here, we're specifying a timeout of 2000 ms.

- -
-

Note: Support for timeout was added in {{Gecko("12.0")}}.

-
- -

Synchronous request

- -
Note: Starting with Gecko 30.0 {{ geckoRelease("30.0") }}, synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.
- -

In rare cases, the use of a synchronous method is preferable to an asynchronous one.

- -

Example: HTTP synchronous request

- -

This example demonstrates how to make a simple synchronous request.

- -
var request = new XMLHttpRequest();
-request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
-request.send(null);
-
-if (request.status === 200) {
-  console.log(request.responseText);
-}
-
- -

Line 3 sends the request.  The null parameter indicates that no body content is needed for the GET request.

- -

Line 5 checks the status code after the transaction is completed.  If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.

- -

Example: Synchronous HTTP request from a Worker

- -

One of the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker.

- -

example.html (the main page):

- -
<!doctype html>
-<html>
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<title>MDN Example</title>
-<script type="text/javascript">
-  var worker = new Worker("myTask.js");
-  worker.onmessage = function(event) {
-    alert("Worker said: " + event.data);
-  };
-
-  worker.postMessage("Hello");
-</script>
-</head>
-<body></body>
-</html>
-
- -

myFile.txt (the target of the synchronous XMLHttpRequest invocation):

- -
Hello World!!
-
- -

myTask.js (the Worker):

- -
self.onmessage = function (event) {
-  if (event.data === "Hello") {
-    var xhr = new XMLHttpRequest();
-    xhr.open("GET", "myFile.txt", false);  // synchronous request
-    xhr.send(null);
-    self.postMessage(xhr.responseText);
-  }
-};
-
- -
Note: The effect, because of the use of the Worker, is however asynchronous.
- -

It could be useful in order to interact in background with the server or to preload some content. See Using web workers for examples and details.

- -

Adapting Sync XHR usecases to the Beacon API

- -

There are some cases in which the synchronous usage of XMLHttpRequest was not replaceable, like during the window.onunload and window.onbeforeunload events.  The navigator.sendBeacon API can support these usecases typically while delivering a good UX.

- -

The following example (from the sendBeacon docs) shows a theoretical analytics code that attempts to submit data to a server by using a synchronous XMLHttpRequest in an unload handler. This results in the unload of the page to be delayed.

- -
window.addEventListener('unload', logData, false);
-
-function logData() {
-    var client = new XMLHttpRequest();
-    client.open("POST", "/log", false); // third parameter indicates sync xhr. :(
-    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
-    client.send(analyticsData);
-}
-
- -

Using the sendBeacon() method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation.

- -

The following example shows a theoretical analytics code pattern that submits data to a server using the by using the sendBeacon() method.

- -
window.addEventListener('unload', logData, false);
-
-function logData() {
-    navigator.sendBeacon("/log", analyticsData);
-}
-
- -

See also

- - - -

{{ languages( {"zh-cn": "zh-cn/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}

diff --git a/files/es/web/css/@document/index.html b/files/es/web/css/@document/index.html deleted file mode 100644 index 8c1ead6ac3..0000000000 --- a/files/es/web/css/@document/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: '@document' -slug: Web/CSS/@document -translation_of: Web/CSS/@document ---- -
{{CSSRef}}{{SeeCompatTable}}
- -

The @document CSS at-rule restricts the style rules contained within it based on the URL of the document. It is designed primarily for user-defined style sheets, though it can be used on author-defined style sheets, too.

- -
@document url("https://www.example.com/") {
-  h1 {
-    color: green;
-  }
-}
-
- - - -

Syntax

- - - -

Una regla @document puede especificar una o más funciones coincidentes. Si alguna de las funciones se aplica a una URL determinada, la regla tendrá efecto en esa URL. Las funciones disponibles son:

- - - -

The values provided to the url(), url-prefix(), and domain() functions can be optionally enclosed by single or double quotes. The values provided to the regexp() function must be enclosed in quotes.

- -

Escaped values provided to the regexp() function must additionally be escaped from the CSS. For example, a . (period) matches any character in regular expressions. To match a literal period, you would first need to escape it using regular expression rules (to \.), then escape that string using CSS rules (to \\.).

- -
-

Note: There is a -moz-prefixed version of this property — @-moz-document. This has been limited to use only in user and UA sheets in Firefox 59 in Nightly and Beta — an experiment designed to mitigate potential CSS injection attacks ({{bug(1035091)}}).

-
- -

Formal syntax

- -{{csssyntax}} - -

Example

- -

CSS

- -
@document url(http://www.w3.org/),
-          url-prefix(http://www.w3.org/Style/),
-          domain(mozilla.org),
-          regexp("https:.*") {
-  /* CSS rules here apply to:
-     - The page "http://www.w3.org/"
-     - Any page whose URL begins with "http://www.w3.org/Style/"
-     - Any page whose URL's host is "mozilla.org"
-       or ends with ".mozilla.org"
-     - Any page whose URL starts with "https:" */
-
-  /* Make the above-mentioned pages really ugly */
-  body {
-    color: purple;
-    background: yellow;
-  }
-}
-
- -

Specifications

- -

Initially in {{SpecName('CSS3 Conditional')}}, @document has been postponed to Level 4.

- -

Browser compatibility

- - - -

{{Compat("css.at-rules.document")}}

- -

See also

- - diff --git a/files/es/web/css/background-position-x/index.html b/files/es/web/css/background-position-x/index.html deleted file mode 100644 index 16f74f3cb7..0000000000 --- a/files/es/web/css/background-position-x/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: background-position-x -slug: Web/CSS/background-position-x -translation_of: Web/CSS/background-position-x ---- -
{{CSSRef}}
- -

El background-position-x propiedad de CSS  coloca la posicion horizontal inicial por cada imagen de fondo. La posicion es relativa a la posicion de la capa puesta por {{cssxref("background-origin")}}.

- -
{{EmbedInteractiveExample("pages/css/background-position-x.html")}}
- - - -

The value of this property is overridden by any declaration of the {{cssxref("background")}} or {{cssxref("background-position")}} shorthand properties applied to the element after it.

- -

Syntax

- -
/* Keyword values */
-background-position-x: left;
-background-position-x: center;
-background-position-x: right;
-
-/* <percentage> values */
-background-position-x: 25%;
-
-/* <length> values */
-background-position-x: 0px;
-background-position-x: 1cm;
-background-position-x: 8em;
-
-/* Side-relative values */
-background-position-x: right 3px;
-background-position-x: left 25%;
-
-/* Multiple values */
-background-position-x: 0px, center;
-
-/* Global values */
-background-position-x: inherit;
-background-position-x: initial;
-background-position-x: unset;
-
- -

The background-position-x property is specified as one or more values, separated by commas.

- -

Values

- -
-
left
-
Aligns the left edge of the background image with the left edge of the background position layer.
-
center
-
Aligns the center of the background image with the center of the background position layer.
-
right
-
Aligns the right edge of the background image with the right edge of the background position layer.
-
{{cssxref("<length>")}}
-
The offset of the given background image's left vertical edge from the background position layer's left vertical edge. (Some browsers allow assigning the right edge for offset).
-
{{cssxref("<percentage>")}}
-
The offset of the given background image's horizontal position relative to the container. A value of 0% means that the left edge of the background image is aligned with the left edge of the container, and a value of 100% means that the right edge of the background image is aligned with the right edge of the container, thus a value of 50% horizontally centers the background image.
-
- -

Formal definition

- -

{{cssinfo}}

- -

Formal syntax

- -{{csssyntax}} - -

Examples

- -

Basic example

- -

The following example shows a simple background image implementation, with background-position-x and background-position-y used to define the image's horizontal and vertical positions separately.

- -

HTML

- -
<div></div>
- -

CSS

- -
div {
-  width: 300px;
-  height: 300px;
-  background-color: skyblue;
-  background-image: url(https://media.prod.mdn.mozit.cloud/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png);
-  background-repeat: no-repeat;
-  background-position-x: center;
-  background-position-y: bottom 10px;
-}
- -

Result

- -

{{EmbedLiveSample('Basic_example', '100%', 300)}}

- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS4 Backgrounds', '#background-position-longhands', 'background-position-x')}}{{Spec2('CSS4 Backgrounds')}}Initial specification of longhand sub-properties of {{cssxref("background-position")}} to match longstanding implementations.
- -

Browser compatibility

- -

{{Compat("css.properties.background-position-x")}}

- -

See also

- - diff --git a/files/es/web/css/border-radius/index.html b/files/es/web/css/border-radius/index.html deleted file mode 100644 index 39e3ab03d7..0000000000 --- a/files/es/web/css/border-radius/index.html +++ /dev/null @@ -1,320 +0,0 @@ ---- -title: border-radius -slug: Web/CSS/border-radius -tags: - - CSS - - CSS Borders - - CSS Property - - Reference -translation_of: Web/CSS/border-radius ---- -

{{ CSSRef() }}

- -

Resumen

- -

La propiedad CSS border-radius permite a los desarrolladores Web definir qué tan redondeadas serán las esquinas. La redondez de cada esquina está definida usando uno o dos valores para el radio que define su forma dependiendo si es un círculo o una elipse.

- -

Images of CSS3 rounded corners: no rounding, rounding w/ an arc of circle, rounding w/ an arc of ellipse

- -

El radio se aplica a todo el {{ Cssxref("background") }}, aun si el elemento no tiene bordes; la posición exacta del recorte es definida por la propiedad {{ Cssxref("background-clip") }}.

- -

Esta propiedad es un atajo para establecer las cuatro propiedades {{ Cssxref("border-top-left-radius") }}, {{ Cssxref("border-top-right-radius") }}, {{ Cssxref("border-bottom-right-radius") }} y {{ Cssxref("border-bottom-left-radius") }}.

- -
As with any shorthand property, individual inherited values are not possible, that is border-radius:0 0 inherit inherit, which would override existing definitions partially. In that case, the individual longhand properties have to be used.
- -

{{cssinfo}}

- -

Sintaxis

- -
Formal grammar: [ <length> | <percentage> ]{1,4}  [ / [ <length> | <percentage> ]{1,4}] ?
-                \------------------------------/      \-------------------------------/
-                           First radii                     Second radii (optional)
-
- -
The syntax of the first radius allows one to four values:
-border-radius: radius
-border-radius: top-left-and-bottom-right top-right-and-bottom-left
-border-radius: top-left top-right-and-bottom-left bottom-right
-border-radius: top-left top-right bottom-right bottom-left
-
-The syntax of the second radius also allows one to four values
-border-radius: (first radius values) / radius
-border-radius: (first radius values) / top-left-and-bottom-right top-right-and-bottom-left
-border-radius: (first radius values) / top-left top-right-and-bottom-left bottom-right
-border-radius: (first radius values) / top-left top-right bottom-right bottom-left
-
-border-radius: inherit
-
- -

Valores

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
radiusall-corner.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in each corner of the border. It is used only in the one-value syntax.
top-left-and-bottom-righttop-left-bottom-right.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-left and bottom-right corners of the element's box. It is used only in the two-value syntax.
top-right-and-bottom-lefttop-right-bottom-left.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-right and bottom-left corners of the element's box. It is used only in the two- and three-value syntaxes.
top-lefttop-left.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-left corner of the element's box. It is used only in the three- and four-value syntaxes.
top-righttop-right.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-right corner of the element's box. It is used only in the four-value syntax.
bottom-rightbottom-rigth.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the bottom-right corner of the element's box. It is used only in the three- and four-value syntaxes.
bottom-leftbottom-left.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the bottom-left corner of the element's box. It is used only in the four-value syntax.
inherit Is a keyword indicating that all four values are inherited from their parent's element calculated value.
- -

Valores

- -
-
<length>
-
Denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipsis. It can be expressed in any unit allowed by the CSS {{cssxref("<length>")}} data types. Negative values are invalid.
-
<percentage>
-
Denotes the size of the circle radius, or the semi-major and semi-minor axes of the ellipsis, using percentage values. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid.
-
- -

Por ejemplo:

- -
border-radius: 1em/5em;
-
-/* es equivalente a: */
-
-border-top-left-radius:     1em 5em;
-border-top-right-radius:    1em 5em;
-border-bottom-right-radius: 1em 5em;
-border-bottom-left-radius:  1em 5em;
-
- -
border-radius: 4px 3px 6px / 2px 4px;
-
-/* es equivalente a: */
-
-border-top-left-radius:     4px 2px;
-border-top-right-radius:    3px 4px;
-border-bottom-right-radius: 6px 2px;
-border-bottom-left-radius:  3px 4px;
-
- -

Ejemplos

- -
  border: solid 10px;
-  /* the border will curve into a 'D' */
-  border-radius: 10px 40px 40px 10px;
-
- -
  border: groove 1em red;
-  border-radius: 2em;
-
- -
  background: gold;
-  border: ridge gold;
-  border-radius: 13em/3em;
-
- -
  border: none;
-  border-radius: 40px 10px;
-
- -
  border: none;
-  border-radius: 50%;
-
- -

Notas

- - - -

Especificaciones

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{ SpecName('CSS3 Backgrounds', '#border-radius', 'border-radius') }}{{ Spec2('CSS3 Backgrounds') }} 
- -

Compatibilidad con los navegadores

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{ CompatGeckoDesktop("2.0") }}
- {{ CompatGeckoDesktop("1.0") }}{{ property_prefix("-moz") }}
4.0
- 0.2{{ property_prefix("-webkit") }}
9.010.55.0
- 3.0{{ property_prefix("-webkit") }}
Elliptical borders{{ CompatGeckoDesktop("1.9.1") }}yesyesyesyes, but see below
4 values for 4 cornersyes4.0yesyes5.0
Percentagesyes
- was {{ non-standard_inline() }} (see below)
yesyes11.55.1
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureiOS SafariOpera MiniOpera MobileAndroid Browser
Basic support3.2{{ property_prefix("-webkit") }}{{ CompatNo() }}{{ CompatNo() }}2.1{{ property_prefix("-webkit") }}
Elliptical borders{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}
4 values for 4 corners{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}
Percentages{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}
-
- -

<percentage> values

- - - -

Gecko notes

- -

In Gecko 2.0 -moz-border-radius was renamed to border-radius; -moz-border-radius was supported as an alias until Gecko 12.0. In order to conform to the CSS3 standard, Gecko 2.0

- - - -
Note: Support for the prefixed version (-moz-border-radius) was removed in Gecko 13.0 {{ geckoRelease("13.0") }}.
- -

WebKit notes

- -

Older Safari and Chrome versions (prior to WebKit 532.5)

- - - -

Opera notes

- -

In Opera (prior to Opera 11.60), applying border-radius to replaced elements will not have rounded corners.

- -

Vea también

- - - -

{{ languages( { "de": "de/CSS/border-radius", "fr": "fr/CSS/-moz-border-radius", "ja": "ja/CSS/border-radius", "pl": "pl/CSS/-moz-border-radius" } ) }}

diff --git a/files/es/web/css/cascade/index.html b/files/es/web/css/cascade/index.html deleted file mode 100644 index 87b99bd61c..0000000000 --- a/files/es/web/css/cascade/index.html +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Introducción a CSS en cascada -slug: Web/CSS/Cascade -translation_of: Web/CSS/Cascade ---- -
{{CSSRef}}
- -
La cascada es un algoritmo que define como combinar valores de propiedad originarios de diferentes fuentes. Este se encuentra en el núcleo de CSS, como enfatizafo por el nombre: Hojas de Estilo en Cascada. Este articulo explica que es cascada, el orden de las {{Glossary("CSS")}} declaraciones en cascada, y como esto te afecta, el desarrollador web.
- -

¿Cuáles entidades CSS participan en la cascada?

- -

Solo las declaraciones CSS, es decir pares de propiedad/valor, participan en la cascada. Esto significa que las at-rules que contienen entidades distintas de las declaraciones, como una regla @font-face que contiene descriptores, no participan en la cascada. En estos casos, solo la regla-at en su conjunto participa en la cascada: aquí, la @font-face identificada por su descriptor de familia de tipografías. Si se definen varias reglas @font-face con el mismo descriptor, solo se considera la @font-face, como conjunto, más adecuada. 

- -

Mientras que las declaraciones contenidas en la mayoría de las reglas-at -como aquellas en @media, @document o @support - participan en la cascada, las declaraciones contenidas en @keyframes no. Como con @font-face, solo la regla-at en su conjunto se selecciona a través del algoritmo en cascada.

- -

Finalmente, debemos tener en cuenta que {{cssxref ("@ import")}} y {{cssxref ("@ charset")}} obedecen a algoritmos específicos y no se ven afectados por el algoritmo en cascada.

- -

Origin of CSS declarations

- -

The CSS cascade algorithm's job is to select CSS declarations in order to determine the correct values for CSS properties. CSS declarations originate from different origins: the {{anch("User-agent stylesheets")}}, the {{anch("Author stylesheets")}}, and the {{anch("User stylesheets")}}.

- -

Though style sheets come from these different origins, they overlap in scope; to make this work, the cascade algorithm defines how they interact.

- -

User-agent stylesheets

- -

The browser has a basic style sheet that gives a default style to any document. These style sheets are named user-agent stylesheets. Some browsers use actual style sheets for this purpose, while others simulate them in code, but the end result is the same.

- -

Some browsers let users modify the user-agent stylesheet. Although some constraints on user-agent stylesheets are set by the HTML specification, browsers still have a lot of latitude: that means that significant differences exist from one browser to another. To simplify the development process, Web developers often use a CSS reset style sheet, forcing common properties values to a known state before beginning to make alterations to suit their specific needs.

- -

Author stylesheets

- -

Author stylesheets are the most common type of style sheet. These are style sheets that define styles as part of the design of a given web page or site. The author of the page defines the styles for the document using one or more stylesheets, which define the look and feel of the website — its theme.

- -

User stylesheets

- -

The user (or reader) of the web site can choose to override styles in many browsers using a custom user stylesheet designed to tailor the experience to the user's wishes.

- -

Cascading order

- -

The cascading algorithm determines how to find the value to apply for each property for each document element.

- -
    -
  1. It first filters all the rules from the different sources to keep only the rules that apply to a given element. That means rules whose selector matches the given element and which are part of an appropriate media at-rule.
  2. -
  3. Then it sorts these rules according to their importance, that is, whether or not they are followed by !important, and by their origin. The cascade is in ascending order, which means that !important values from a user-defined style sheet have precedence over normal values originated from a user-agent style sheet: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    OriginImportance
    1user agentnormal
    2usernormal
    3authornormal
    4animations
    5author!important
    6user!important
    7user agent!important
    8transitions
    -
  4. -
  5. In case of equality, the specificity of a value is considered to choose one or the other.
  6. -
- -

Resetting styles

- -

After your content has finished altering styles, it may find itself in a situation where it needs to restore them to a known state. This may happen in cases of animations, theme changes, and so forth. The CSS property {{cssxref("all")}} lets you quickly set (almost) everything in CSS back to a known state.

- -

all lets you opt to immediately restore all properties to any of their initial (default) state, the state inherited from the previous level of the cascade, a specific origin (the user-agent stylesheet, the author stylesheet, or the user stylesheet), or even to clear the values of the properties entirely.

- -

CSS animations and the cascade

- -

CSS animations, using {{ cssxref("@keyframes")}} at-rules, define animations between states. Keyframes don't cascade, meaning that at any given time CSS takes values from only one single {{cssxref("@keyframes")}}, and never mixes multiple ones together.

- -

When several keyframes are appropriate, it chooses the latest defined in the most important document, but never combined all together.

- -

Example

- -

Let's look at an example involving multiple sources of CSS across the various origins; here we have a user agent style sheet, two author style sheets, a user stylesheet, and inline styles within the HTML:

- -

User-agent CSS:

- -
li { margin-left: 10px }
- -

Author CSS 1:

- -
li { margin-left: 0 } /* This is a reset */
- -

Author CSS 2:

- -
@media screen {
-  li { margin-left: 3px }
-}
-
-@media print {
-  li { margin-left: 1px }
-}
-
- -

User CSS:

- -
.specific { margin-left: 1em }
- -

HTML:

- -
<ul>
-  <li class="specific">1<sup>st</sup></li>
-  <li>2<sup>nd</sup></li>
-</ul>
-
- -

In this case, declarations inside li and .specific rules should apply. No declaration is marked as !important, so the precedence order is author style sheets before user style sheets or user-agent stylesheet.

- -

So three declarations are in competition:

- -
margin-left: 0
- -
margin-left: 3px
- -
margin-left: 1px
- -

The last one is ignored (on a screen), and the first two have the same selector, hence the same specificity. Therefore, it is the last one that is then selected:

- -
margin-left: 3px
- -

Note that the declaration defined in the user CSS, though having a greater specificity, is not chosen as the cascade algorithm is applied before the specificity algorithm.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("CSS4 Cascade")}}{{Spec2("CSS4 Cascade")}}Added the {{CSSxRef("revert")}} keyword, which allows rolling a property back a cascade level.
{{SpecName("CSS3 Cascade")}}{{Spec2("CSS3 Cascade")}}Removed the override cascade origin, as it was never used in a W3C standard.
{{SpecName("CSS2.1", "cascade.html", "the cascade")}}{{Spec2("CSS2.1")}}
{{SpecName("CSS1", "#the-cascade", "the cascade")}}{{Spec2("CSS1")}}Initial definition.
- -

See also

- - diff --git a/files/es/web/css/clip-path/index.html b/files/es/web/css/clip-path/index.html deleted file mode 100644 index a8b5253601..0000000000 --- a/files/es/web/css/clip-path/index.html +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: clip-path -slug: Web/CSS/clip-path -translation_of: Web/CSS/clip-path ---- -
{{CSSRef}}{{SeeCompatTable}}
- -

La propiedad CSS clip-path proviene que una porción de un elemento se muestre definiendo una región de recorte para mostrarse, es decir, solo una parte especifica del elemento se mostrara. La región recortada es un path especificado como una URL referenciando a un SVG inline o externo, o un metodo de figura como lo es circle(). La propiedad clip-path reemplaza la ahora deprecada propiedad clip.

- -
/* Valores clave */
-clip-path: none;
-
-/* Valores de imagen */
-clip-path: url(resources.svg#c1);
-
-/* Valores de caja */
-clip-path: fill-box;
-clip-path: stroke-box;
-clip-path: view-box;
-clip-path: margin-box;
-clip-path: border-box;
-clip-path: padding-box;
-clip-path: content-box;
-
-/* Valores geometricos */
-clip-path: inset(100px 50px);
-clip-path: circle(50px at 0 100px);
-clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
-
-/* Valores Geometricos y de caja combinados */
-clip-path: padding-box circle(50px at 0 100px);
-
-/* Valores globales */
-clip-path: inherit;
-clip-path: initial;
-clip-path: unset;
-
- -

{{cssinfo}}

- -

Syntax

- -

Valores

- -
-
url()
-
Represents a URL referencing a clip path element.
-
 
-
inset(), circle(), ellipse(), polygon()
-
A {{cssxref("<basic-shape>")}} function. Such a shape will make use of the specified <geometry-box> to size and position the basic shape. If no geometry box is specified, the border-box will be used as reference box.
-
<geometry-box>
-
If specified in combination with a <basic-shape>, it provides the reference box for the basic shape. If specified by itself, it uses the edges of the specified box including any corner shaping (e.g. defined by {{cssxref("border-radius")}}) as clipping path. The geometry box can be one of the following values: -
-
fill-box
-
Uses the object bounding box as reference box.
-
stroke-box
-
Uses the stroke bounding box as reference box.
-
view-box
-
Uses the nearest SVG viewport as reference box. If a {{SVGAttr("viewBox")}} attribute is specified for the element creating the SVG viewport, the reference box is positioned at the origin of the coordinate system established by the viewBox attribute and the dimension of the reference box is set to the width and height values of the viewBox attribute.
-
margin-box
-
Uses the margin box as the reference box.
-
border-box
-
Uses the border box as the reference box.
-
padding-box
-
Uses the padding box as the reference box.
-
content-box
-
Uses the content box as the reference box.
-
-
-
none
-
There is no clipping path created.
-
- -

Formal syntax

- -{{csssyntax}} - -

Examples

- -
/* inline SVG  */
-.target {
-  clip-path: url(#c1);
-}
-
-/* external SVG */
-.anothertarget {
-  clip-path: url(resources.svg#c1);
-}
-
-/* circle */
-.circleClass {
-  clip-path: circle(15px at 20px 20px);
-}
- -

Live sample

- -

HTML

- -
<img id="clipped" src="https://mdn.mozillademos.org/files/12668/MDN.svg"
-    alt="MDN logo">
-<svg height="0" width="0">
-  <defs>
-    <clipPath id="cross">
-      <rect y="110" x="137" width="90" height="90"/>
-      <rect x="0" y="110" width="90" height="90"/>
-      <rect x="137" y="0" width="90" height="90"/>
-      <rect x="0" y="0" width="90" height="90"/>
-    </clipPath>
-  </defs>
-</svg>
-
-<select id="clipPath">
-  <option value="none">none</option>
-  <option value="circle(100px at 110px 100px)">circle</option>
-  <option value="url(#cross)" selected>cross</option>
-  <option value="inset(20px round 20px)">inset</option>
-</select>
-
- -

CSS

- -
#clipped {
-  margin-bottom: 20px;
-  clip-path: url(#cross);
-}
-
- - - -

Result

- -

{{EmbedLiveSample("Live_sample", 230, 250)}}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("CSS Masks", "#the-clip-path", 'clip-path')}}{{Spec2('CSS Masks')}}Extends its application to HTML elements
{{SpecName('SVG1.1', 'masking.html#ClipPathProperty', 'clip-path')}}{{Spec2('SVG1.1')}}Initial definition (applies to SVG elements only)
- -

Browser compatibility

- - - -

{{Compat("css.properties.clip-path")}}

- -

See also

- - diff --git a/files/es/web/css/media_queries/testing_media_queries/index.html b/files/es/web/css/media_queries/testing_media_queries/index.html deleted file mode 100644 index 81f1e41608..0000000000 --- a/files/es/web/css/media_queries/testing_media_queries/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Probando media queries -slug: Web/CSS/Media_Queries/Testing_media_queries -translation_of: Web/CSS/Media_Queries/Testing_media_queries -original_slug: Web/Guide/CSS/probando_media_queries ---- -

{{SeeCompatTable}}

-

El DOM proporciona características que hacen posible probar los resultados de un media query estructuradamente. Esto es hecho usando la interfaz {{domxref("MediaQueryList") }} y sus métodos y propiedades. Una vez que hayas creado el objeto {{domxref("MediaQueryList") }}, puedes revisar el resultado del query o, como alternativa, recibir notificaciones automáticamente cuando el resultado cambie.

-

Creando una media query list

-

Before you can evaluate the results of a query, you need to create the {{domxref("MediaQueryList") }} object representing the media query. To do this, use the {{domxref("window.matchMedia") }} method.

-

For example, if you want to set up a query list that determines whether the device is in landscape or portrait orientation, you can do so like this:

-
var mql = window.matchMedia("(orientation: portrait)");
-
-

Revisando el resultado de un query

-

Once your media query list has been created, you can check the result of the query by looking at the value of its matches property, which reflects the result of the query:

-
if (mql.matches) {
-  /* The device is currently in portrait orientation */
-} else {
-  /* The device is currently in landscape orientation */
-}
-
-

Recibiendo notificaciones query

-

If you need to be aware of changes to the evaluated result of the query on an ongoing basis, it's more efficient to register a listener than to poll the query's result. To do this, you can call the addListener() method on the {{domxref("MediaQueryList") }} object, specifying an observer that implements the {{domxref("MediaQueryListListener") }} interface:

-
var mql = window.matchMedia("(orientation: portrait)");
-mql.addListener(handleOrientationChange);
-handleOrientationChange(mql);
-
-

This code creates the orientation testing media query list, mql, then adds a listener to it. Note that after adding the listener, we actually invoke the listener directly once. This lets our listener perform initial adjustments based on the current device orientation (otherwise, if our code assumes the device is in portrait mode but it's actually in landscape mode at startup, we could have inconsistencies).

-

The handleOrientationChange() method we implement then would look at the result of the query and handle whatever we need to do on an orientation change:

-
function handleOrientationChange(mql) {
-  if (mql.matches) {
-    /* The device is currently in portrait orientation */
-  } else {
-    /* The device is currently in landscape orientation */
-  }
-}
-
-

Terminando con las notificaciones query 

-

Cuando ya no vayas a necesitar recibir las notificaciones sobre los cambios de valro de tu media query, simplemente llama al removeListener() en el {{domxref("MediaQueryList") }}:

-
mql.removeListener(handleOrientationChange);
-
-

Compatibilidad con los navegadores

-

{{CompatibilityTable}}

-
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico9{{CompatGeckoDesktop("6.0") }}1012.15.1
-
-
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico3.0{{CompatUnknown}}1012.15
-
-

Ver también

- diff --git a/files/es/web/html/attributes/autocomplete/index.html b/files/es/web/html/attributes/autocomplete/index.html deleted file mode 100644 index 553e9a293c..0000000000 --- a/files/es/web/html/attributes/autocomplete/index.html +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: The HTML autocomplete attribute -slug: Web/HTML/Attributes/autocomplete -translation_of: Web/HTML/Attributes/autocomplete -original_slug: Web/HTML/Atributos/autocomplete ---- -

El atributo autocomplete  está disponible en varios tipos de  {{HTMLElement("input")}} aquellos que toman un texto o valor numérico como entrada. autocomplete  permite a los desarrolladores web especificar qué permisos si los hay {{Glossary("user agent")}}  debe proporcionar asistencia automatizada para completar los valores de los campos de formulario, así como una guía para el navegador en cuanto al tipo de información que se espera en el campo.

- -

 

- -

Los valores sugeridos generalmente depende del navegador. Normalmente, provienen de valores ​​ingresados ​​por el usuario, pero también pueden provenir de valores preconfigurados. Por ejemplo, un navegador puede permitir que el usuario guarde su nombre, dirección, número de teléfono y direcciones de correo electrónico para autocompletar así como también datos de tarjetas de crédito.

- -

Si un elemento {{HTMLElement("input")}} no tiene el atributo autocomplete , entonces los navegadores usan el atributo autocomplete del {{HTMLElement("form")}} que lo contiene. En otras palabras, el {{HTMLElement("form")}} del que el {{HTMLElement("input")}} desciende. También puede ser especificado en el atributo {{htmlattrxref("form", "input")}} del {{HTMLElement("input")}} en cuestión.

- -

Para más información vea el atributo {{htmlattrxref("autocomplete", "form")}} del elemento {{HTMLElement("form")}}

- -
-

Para proveer el autocompletado, el navegador necesita del los elementos <input>:

- -
    -
  1. Que tengan name y/o id
  2. -
  3. Pertenezcan a un elemento <form>
  4. -
  5. Que el formulario tenga un botón {{HTMLElement("input/submit", "submit")}}
  6. -
-
- -

Valores

- -
-
"off"
-
The browser is not permitted to automatically enter or select a value for this field. It is possible that the document or application provides its own autocomplete feature, or that security concerns require that the field's value not be automatically entered. -
Note: In most modern browsers, setting autocomplete to "off" will not prevent a password manager from asking the user if they would like to save username and password information, or from automatically filling in those values in a site's login form. See the autocomplete attribute and login fields.
-
-
"on"
-
The browser is allowed to automatically complete the input. No guidance is provided as to the type of data expected in the field, so the browser may use its own judgement.
-
"name"
-
The field expects the value to be a person's full name. Using "name" rather than breaking the name down into its components is generally preferred because it avoids dealing with the wide diversity of human names and how they are structured; however, you can use the following autocomplete values if you do need to break the name down into its components: -
-
"honorific-prefix"
-
The prefix or title, such as "Mrs.", "Mr.", "Miss", "Ms.", "Dr.", or "Mlle.".
-
"given-name"
-
The given (or "first") name.
-
"additional-name"
-
The middle name.
-
"family-name"
-
The family (or "last") name.
-
"honorific-suffix"
-
The suffix, such as "Jr.", "B.Sc.", "PhD.", "MBASW", or "IV".
-
"nickname"
-
A nickname or handle.
-
-
-
"email"
-
An email address.
-
"username"
-
A username or account name.
-
"new-password"
-
A new password. When creating a new account or changing passwords, this is the "Enter your new password" field, as opposed to any "Enter your current password" field that might be present. This may be used by the browser both to avoid accidentally filling in an existing password and to offer assistance in creating a secure password.
-
"current-password"
-
The user's current password.
-
"organization-title"
-
A job title, or the title a person has within an organization, such as "Senior Technical Writer", "President", or "Assistant Troop Leader".
-
"organization"
-
A company or organization name, such as "Acme Widget Company" or "Girl Scouts of America".
-
"street-address"
-
A street address. This can be multiple lines of text, and should fully identify the location of the address within its second administrative level (typically a city or town), but should not include the city name, ZIP or postal code, or country name.
-
"address-line1", "address-line2", "address-line3"
-
Each individual line of the street address. These should only be present if the "street-address" is also present.
-
"address-level4"
-
The finest-grained {{anch("Administrative levels in addresses", "administrative level")}}, in addresses which have four levels.
-
"address-level3"
-
The third {{anch("Administrative levels in addresses", "administrative level")}}, in addresses with at least three administrative levels.
-
"address-level2"
-
The second {{anch("Administrative levels in addresses", "administrative level")}}, in addresses with at least two of them. In countries with two administrative levels, this would typically be the city, town, village, or other locality in which the address is located.
-
"address-level1"
-
The first {{anch("Administrative levels in addresses", "administrative level")}} in the address. This is typically the province in which the address is located. In the United States, this would be the state. In Switzerland, the canton. In the United Kingdom, the post town.
-
"country"
-
A country code.
-
"country-name"
-
A country name.
-
"postal-code"
-
A postal code (in the United States, this is the ZIP code).
-
"cc-name"
-
The full name as printed on or associated with a payment instrument such as a credit card. Using a full name field is preferred, typically, over breaking the name into pieces.
-
"cc-given-name"
-
A given (first) name as given on a payment instrument like a credit card.
-
"cc-additional-name"
-
A middle name as given on a payment instrument or credit card.
-
"cc-family-name"
-
A family name, as given on a credit card.
-
"cc-number"
-
A credit card number or other number identifying a payment method, such as an account number.
-
"cc-exp"
-
A payment method expiration date, typically in the form "MM/YY" or "MM/YYYY".
-
"cc-exp-month"
-
The month in which the payment method expires.
-
"cc-exp-year"
-
The year in which the payment method expires.
-
"cc-csc"
-
The security code for the payment instrument; on credit cards, this is the 3-digit verification number on the back of the card.
-
"cc-type"
-
The type of payment instrument (such as "Visa" or "Master Card").
-
"transaction-currency"
-
The currency in which the transaction is to take place.
-
"transaction-amount"
-
The amount, given in the currency specified by "transaction-currency", of the transaction, for a payment form.
-
"language"
-
A preferred language, given as a valid BCP 47 language tag.
-
"bday"
-
A birth date, as a full date.
-
"bday-day"
-
The day of the month of a birth date.
-
"bday-month"
-
The month of the year of a birth date.
-
"bday-year"
-
The year of a birth date.
-
"sex"
-
A gender identity (such as "Female", "Fa'afafine", "Male"), as freeform text without newlines.
-
"tel"
-
A full telephone number, including the country code. If you need to break the phone number up into its components, you can use these values for those fields: -
-
"tel-country-code"
-
The country code, such as "1" for the United States, Canada, and other areas in North America and parts of the Caribbean.
-
"tel-national"
-
The entire phone number without the country code component, including a country-internal prefix. For the phone number "1-855-555-6502", this field's value would be "855-555-6502".
-
"tel-area-code"
-
The area code, with any country-internal prefix applied if appropriate.
-
"tel-local"
-
The phone number without the country or area code. This can be split further into two parts, for phone numbers which have an exchange number and then a number within the exchange. For the phone number "555-6502", use "tel-local-prefix" for "555" and "tel-local-suffix" for "6502".
-
-
-
"tel-extension"
-
A telephone extension code within the phone number, such as a room or suite number in a hotel or an office extension in a company.
-
"impp"
-
A URL for an instant messaging protocol endpoint, such as "xmpp:username@example.net".
-
"url"
-
A URL, such as a home page or company web site address as appropriate given the context of the other fields in the form.
-
"photo"
-
The URL of an image representing the person, company, or contact information given in the other fields in the form.
-
- -

See the WHATWG Standard for more detailed information.

- -
-

Note: The autocomplete attribute also controls whether Firefox will — unlike other browsers — persist the dynamic disabled state and (if applicable) dynamic checkedness of an <input> across page loads. The persistence feature is enabled by default. Setting the value of the autocomplete attribute to off disables this feature. This works even when the autocomplete attribute would normally not apply to the <input> by virtue of its type. See {{bug(654072)}}.

-
- -

Administrative levels in addresses

- -

The four administrative level fields ("address-level1" through "address-level4") describe the address in terms of increasing levels of precision within the country in which the address is located. Each country has its own system of administrative levels, and may arrange the levels in different orders when addresses are written.

- -

"address-level1" always represents the broadest administrative division; it is the least-specific portion of the address short of the country name.

- -

Form layout flexibility

- -

Given that different countries write their address in different ways, with each field in different places within the address, and even different sets and numbers of fields entirely, it can be helpful if, when possible, your site is able to switch to the layout expected by your users when presenting an address entry form, given the country the address is located within.

- -

Variations

- -

The way each administrative level is used will vary from country to country. Below are some examples; this is not meant to be an exhaustive list.

- -

United States

- -

A typical home address within the United States looks like this:

- -

432 Anywhere St
- Exampleville CA 95555

- -

In the United States, the least-specific portion of the address is the state, in this case "CA" (the official US Postal Service shorthand for "California"). Thus "address-level1" is the state, or "CA" in this case.

- -

The second-least specific portion of the address is the city or town name, so "address-level2" is "Exampleville" in this example address.

- -

United States addresses do not use levels 3 and up.

- -

United Kingdom

- -

The UK uses one or two address levels, depending on the address. These are the post town and, in some instances, the locality.

- -

China

- -

China can use as many as three administrative levels: the province, the city, and the district.

diff --git a/files/es/web/html/element/shadow/index.html b/files/es/web/html/element/shadow/index.html deleted file mode 100644 index 7c5720124f..0000000000 --- a/files/es/web/html/element/shadow/index.html +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: -slug: Web/HTML/Element/shadow -translation_of: Web/HTML/Element/shadow -original_slug: Web/HTML/Elemento/Shadow ---- -

{{obsolete_header}}

- -

El HTML <shadow> element—es una parte absoluta de la suite tecnológica de Web Components —estaba destinado a ser utilizado como un shadow DOM {{glossary("insertion point")}}. Es posible que lo hayas usado si has creado varias root shadow bajo un shadow host. No es útil en HTML ordinario.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Content categoriesTransparent content.
Permitted contentFlow content.
Tag omission{{no_tag_omission}}
Permitted parentsAny element that accepts flow content.
Permitted ARIA rolesNone
DOM interface{{domxref("HTMLShadowElement")}}
- -

Attributes

- -

This element includes the global attributes.

- -

Example

- -

Aquí está un ejemplo simple usando el  <shadow> element. Es un archivo HTML con todo lo necesario en él.

- -
-

Note: This is an experimental technology. For this code to work, the browser you display it in must support Web Components. See Enabling Web Components in Firefox.

-
- -
<html>
-  <head></head>
-  <body>
-
-  <!-- This <div> will hold the shadow roots. -->
-  <div>
-    <!-- This heading will not be displayed -->
-    <h4>My Original Heading</h4>
-  </div>
-
-  <script>
-    // Get the <div> above with its content
-    var origContent = document.querySelector('div');
-    // Create the first shadow root
-    var shadowroot1 = origContent.createShadowRoot();
-    // Create the second shadow root
-    var shadowroot2 = origContent.createShadowRoot();
-
-    // Insert something into the older shadow root
-    shadowroot1.innerHTML =
-      '<p>Older shadow root inserted by
-          &lt;shadow&gt;</p>';
-    // Insert into younger shadow root, including <shadow>.
-    // The previous markup will not be displayed unless
-    // <shadow> is used below.
-    shadowroot2.innerHTML =
-      '<shadow></shadow> <p>Younger shadow
-       root, displayed because it is the youngest.</p>';
-  </script>
-
-  </body>
-</html>
-
- -

If you display this in a web browser it should look like the following.

- -

shadow example

- -

Specifications

- -

This element is no longer defined by any specifications.

- -

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, <shadow> elements will behave like {{domxref("HTMLUnknownElement")}}. Shadow DOM was first implemented in Firefox 33 and is behind a preference, dom.webcomponents.enabled, which is disabled by default.

- -

See also

- - - -
{{HTMLRef}}
diff --git a/files/es/web/javascript/reference/global_objects/encodeuricomponent/index.html b/files/es/web/javascript/reference/global_objects/encodeuricomponent/index.html deleted file mode 100644 index e1e70a7747..0000000000 --- a/files/es/web/javascript/reference/global_objects/encodeuricomponent/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: encodeURIComponent -slug: Web/JavaScript/Reference/Global_Objects/encodeURIComponent -tags: - - JavaScript - - URI -translation_of: Web/JavaScript/Reference/Global_Objects/encodeURIComponent -original_slug: Web/JavaScript/Referencia/Objetos_globales/encodeURIComponent ---- -
{{jsSidebar("Objects")}}
- -

Resumen

- -

El método encodeURIComponent() codifica un componente URI (Identificador Uniforme de Recursos) al reemplazar cada instancia de ciertos caracteres por una, dos, tres o cuatro secuencias de escape que representan la codificación UTF-8 del carácter (solo serán cuatro secuencias de escape para caracteres compuestos por dos carácteres "sustitutos").

- -

Sintaxis

- -
encodeURIComponent(str);
- -

Parámetros

- -
-
str
-
Cadena. Un componente de un URI.
-
- -

Descripción

- -

encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )

- -

Note that an {{jsxref("Objetos_globales/URIError", "URIError")}} will be thrown if one attempts to encode a surrogate which is not part of a high-low pair, e.g.,

- -
// high-low pair ok
-alert(encodeURIComponent('\uD800\uDFFF'));
-
-// lone high surrogate throws "URIError: malformed URI sequence"
-alert(encodeURIComponent('\uD800'));
-
-// lone low surrogate throws "URIError: malformed URI sequence"
-alert(encodeURIComponent('\uDFFF'));
-
- -

To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.

- -

For application/x-www-form-urlencoded (POST), spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".

- -

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

- -
function fixedEncodeURIComponent (str) {
-  return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
-}
-
- -

Examples

- -

The following example provides the special encoding required within UTF-8 Content-Disposition and Link server response header parameters (e.g., UTF-8 filenames):

- -
var fileName = 'my file(2).txt';
-var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);
-
-console.log(header);
-// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
-
-
-function encodeRFC5987ValueChars (str) {
-    return encodeURIComponent(str).
-        // Note that although RFC3986 reserves "!", RFC5987 does not,
-        // so we do not need to escape it
-        replace(/['()]/g, escape). // i.e., %27 %28 %29
-        replace(/\*/g, '%2A').
-            // The following are not required for percent-encoding per RFC5987,
-            //  so we can allow for a little better readability over the wire: |`^
-            replace(/%(?:7C|60|5E)/g, unescape);
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 3rd Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.1.3.4', 'encodeURIComponent')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-encodeuricomponent-uricomponent', 'encodeURIComponent')}}{{Spec2('ES6')}}
- -

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/statements/with/index.html b/files/es/web/javascript/reference/statements/with/index.html deleted file mode 100644 index 9ad9f256c4..0000000000 --- a/files/es/web/javascript/reference/statements/with/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: with -slug: Web/JavaScript/Reference/Statements/with -translation_of: Web/JavaScript/Reference/Statements/with -original_slug: Web/JavaScript/Referencia/Sentencias/with ---- -
El uso de la declaración no es recomendado,  ya que puede ser el origen de los errores de confusión y problemas de compatibilidad. See the "Ambiguity Con" paragraph in the "Description" section below for details.
- -
{{jsSidebar("Statements")}}
- -

La sentencia with extiende el alcance de una cadena con la declaración.

- -

Sintaxis

- -
with (expresión) {
-  declaración
-}
-
- -
-
expresión
-
Añade la expresión dada a la declaración. Los parentesis alrededor de la expresión son necesarios.
-
declaración
-
Se puede ejecutar cualquier declaración. Para ejecutar varias declaraciónes, utilizar una declaración de bloque ({ ... }) para agrupar esas declaraciónes.
-
- -

Descripción

- -

JavaScript looks up an unqualified name by searching a scope chain associated with the execution context of the script or function containing that unqualified name. The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property. Otherwise a {{jsxref("ReferenceError")}} is thrown.

- -
Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.
- -

Performance pro & contra

- -

Pro: The with statement can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty. The scope chain change required by 'with' is not computationally expensive. Use of 'with' will relieve the interpreter of parsing repeated object references. Note, however, that in many cases this benefit can be achieved by using a temporary variable to store a reference to the desired object.

- -

Contra: The with statement forces the specified object to be searched first for all name lookups. Therefore all identifiers that aren't members of the specified object will be found more slowly in a 'with' block. Where performance is important, 'with' should only be used to encompass code blocks that access members of the specified object.

- -

Ambiguity contra

- -

Contra: The with statement makes it hard for a human reader or JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. So given this example:

- -
function f(x, o) {
-  with (o)
-    print(x);
-}
- -

Only when f is called is x either found or not, and if found, either in o or (if no such property exists) in f's activation object, where x names the first formal argument. If you forget to define x in the object you pass as the second argument, or if there's some similar bug or confusion, you won't get an error -- just unexpected results.

- -

Contra: Code using with may not be forward compatible, especially when used with something else than a plain object. Consider this example:

- -
-
function f(foo, values) {
-    with (foo) {
-        console.log(values)
-    }
-}
-
- -

If you call f([1,2,3], obj) in an ECMAScript 5 environment, then the values reference inside the with statement will resolve to obj. However, ECMAScript 6 introduces a values property on Array.prototype (so that it will be available on every array). So, in a JavaScript environment that supports ECMAScript 6, the values reference inside the with statement will resolve to [1,2,3].values.

-
- -

Examples

- -

Using with

- -

The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references.

- -
var a, x, y;
-var r = 10;
-
-with (Math) {
-  a = PI * r * r;
-  x = r * cos(PI);
-  y = r * sin(PI / 2);
-}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-with-statement', 'with statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.10', 'with statement')}}{{Spec2('ES5.1')}}Now forbidden in strict mode.
{{SpecName('ES3', '#sec-12.10', 'with statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.10', 'with statement')}}{{Spec2('ES1')}}Initial definition
- -

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/mathml/authoring/index.html b/files/es/web/mathml/authoring/index.html deleted file mode 100644 index f9c30ff92c..0000000000 --- a/files/es/web/mathml/authoring/index.html +++ /dev/null @@ -1,415 +0,0 @@ ---- -title: Redacción de MathML -slug: Web/MathML/Authoring -translation_of: Web/MathML/Authoring ---- -

Este artículo explica como redactar funciones matemáticas utilizando el lenguaje MathML. Al igual que HTML, MathML puede describirse con etiquetas y atributos. HTML puede volverse interminable cuando tu documento contiene estructuras avanzadas como listas o tablas pero afortunadamente existen varios generadores, desde simple notaciones, editores WYSIWYG y otros Sistemas de Administración de Contenido (CMS) utilizados para la creación de páginas web.

- -

Las notaciones Matemáticas son aún más complejas con estructuras que contienen fracciones, raíces cuadradas o matrices que seguramente requerirán sus propias etiquetas. Como consecuencia, las buenas herramientas de redacción de MathML son importantes y más adelante describimos algunas opciones. En particular, el équipo MathML de Mozilla ha creado TeXZilla, un convertor de LaTeX a MathML compatible con Unicode, para ser utilizado en muchos scenari descrito ahí. Desde luego, la lista no es de ninguna manera definitiva y estás invitado a revisar la Lista de Software MathML de W3C donde puedes encontrar diferentes herramientas.

- -

Hay que señalar que por diseño, MathML está bien integrado en HTML5 y particularmente puedes utilizar las características Web comunes como CSS, DOM, Javascript o SVG. Esto está fuera del ámbito de este artículo pero cualquiera con conocimientos básicos de lenguajes Web será capaz de combinar fácilmente estas características con MathML. Revisa nuestros demos y referencias de MathML para más detalles.

- -

Fundamentos

- -

Utilizar MathML en páginas HTML

- -

Puedes utilizar MathML dentro de un documento HTML5:

- -
<!DOCTYPE html>
-<html>
-<head>
- <title>MathML in HTML5</title>
-</head>
-<body>
-
-  <h1>MathML in HTML5</h1>
-
-  <p>
-    Square root of two:
-    <math>
-      <msqrt>
-        <mn>2</mn>
-      </msqrt>
-    </math>
-  </p>
-
-</body>
-</html> 
- -

Content MathML no esta soportado por el navegador. Es recomendable convertir tu content MathML markup en Presentation MathML  antes de publicarlo, por ejemplo con la ayuda de la hoja de calculo  ctop.xsl  . Las herramientas mencionadas en esta pagina generan Presentation MathML.

- -

 

- -

Para navegadores sin soporte a MathML

- -

Desafortunadamente, algunos navegadores no son capaces  de  renderizar ecuaciones MathML o tienen un soporte limitado. Por lo tanto necesitará  usar  MathML polyfill para proveer el renderizado. Si necesita solo construcciones matematicas básicas tales como las utilizadas  en esta wiki de MDN entonces una pequeña hoja de cálculo mathml.css  podria  ser suficiente. Para usarlo, solo inserta una linea en el header de tu documento:

- -
<script src="http://fred-wang.github.io/mathml.css/mspace.js"></script>
- -

If you need more complex constructions, you might instead consider using the heavier MathJax library as a MathML polyfill:

- -
<script src="http://fred-wang.github.io/mathjax.js/mpadded.js"></script>
- -

Note that these two scripts perform feature detection of the mspace or mpadded elements (see the browser compatibility table on these pages). If you don't want to use this link to GitHub but instead to integrate these polyfills or others in your own project, you might need the detection scripts to verify the level of MathML support. For example the following function verifies the MathML support by testing the mspace element (you may replace mspace with mpadded):

- -
 function hasMathMLSupport() {
-  var div = document.createElement("div"), box;
-  div.innerHTML = "<math><mspace height='23px' width='77px'/></math>";
-  document.body.appendChild(div);
-  box = div.firstChild.firstChild.getBoundingClientRect();
-  document.body.removeChild(div);
-  return Math.abs(box.height - 23) <= 1  && Math.abs(box.width - 77) <= 1;
-}
- -

Alternatively, the following UA string sniffing will allow to detect the rendering engines with native MathML support (Gecko and WebKit). Note that UA string sniffing is not the most reliable method and might break from version to version:

- -
var ua = navigator.userAgent;
-var isGecko = ua.indexOf("Gecko") > -1 && ua.indexOf("KHTML") === -1 && ua.indexOf('Trident') === -1;
-var isWebKit = ua.indexOf('AppleWebKit') > -1 && ua.indexOf('Chrome') === -1;
- -

 

- -

Mathematical fonts

- -

Note: browsers can only use a limited set of mathematical fonts to draw stretchy MathML operators. However, implementation of the OpenType MATH table is in progress in Gecko & WebKit. This will provide a generic support for mathematical fonts and simplify the settings described in this section.

- -

To get a good mathematical rendering in browsers, some MathML fonts are required. It's a good idea to provide to your visitors a link to the MDN page that explains how to install MathML fonts. Alternatively, you can just make them available as Web fonts. You can get these fonts from the MathML-fonts add-on ; the xpi is just a zip archive that you can fetch and extract for example with the following command:

- -
wget https://addons.mozilla.org/firefox/downloads/latest/367848/addon-367848-latest.xpi -O mathml-fonts.zip; \
-unzip mathml-fonts.zip -d mathml-fonts
- -

Then copy the mathml-fonts/resource/ directory somewhere on your Web site and ensure that the woff files are served with the correct MIME type. Finally, include the mathml-fonts/resource/mathml.css style sheet in your Web pages, for example by adding the following rule to the default style sheet of your Web site:

- -
@import url('/path/to/resource/mathml.css');
- -

You then need to modify the font-family on the <math> elements and, for Gecko, the on ::-moz-math-stretchy pseudo element too. For example to use STIX fonts:

- -
math {
-  font-family: STIXGeneral;
-}
-
-::-moz-math-stretchy {
-  font-family: STIXNonUnicode, STIXSizeOneSym, STIXSize1, STIXGeneral;
-}
-
- -

Try the MathML torture test to compare the rendering of various fonts and the CSS rules to select them.

- -

Utilizar MathML en documentos XML (XHTML, EPUB, etc.)

- -

Si por alguna razón necesitas utilizar MathML en documentos XML, asegúrate de cumplir con los requisitos habituales: documentos bien realizados, el uso correcto de la especificación MIME, el prefijo MathML "http://www.w3.org/1998/Math/MathML" en la raíz <math>. Por ejemplo, la versión XHTML del ejemplo anterior luce de esta manera:
-  

- -
<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"
-  "http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
- <title>XHTML+MathML Example</title>
-</head>
-<body>
-
-<h1>XHTML+MathML Example</h1>
-
-  <p>
-    Square root of two:
-    <math xmlns="http://www.w3.org/1998/Math/MathML">
-      <msqrt>
-        <mn>2</mn>
-      </msqrt>
-    </math>
-  </p>
-
-</body>
-</html> 
- -

Note that if you use MathML as a standalone .mml or .svg documents or inside an EPUB book, it may not always be possible to use MathJax as a polyfill for rendering engines without MathML support. Hence whether MathML can be handled will vary according to the tools used to read these documents.

- -

Utilizar MathML en correos electrónicos

- -

Los clientes de correos modernos pueden enviar y recibir correos electrónicos en el formato HTML5 y por lo tanto pueden manejar expresiones de tipo MathML. Asegúrate de tener las opciones de "Enviar como HTML" y "Ver como HTML" habilitadas. En Thunderbird, puedes utilizar el comando "Insertar HTML" para pegar tu código HTML+MathML. MathBird es un complemento conveniente de Thunderbird para insertar este tipo de expresiones MathML utilizando la sintaxis AsciiMath.
-
- De nuevo, la forma en como MathML es manejada y la calidad de cómo se muestran estas expresiones depende del cliente de correo electrónico. Aún si tu navegador es compatible con MathML, tu servicio de correo electrónico puede evitar que envíes o recibas correos con expresiones MathML.

- -

Conversion from a Simple Syntax

- -

There are many simple notations (e.g. wiki or markdown syntaxes) to generate HTML pages. The same is true for MathML: for example ASCII syntaxes as used in calculators or the more powerful LaTeX language, very popular among the scientific community. In this section, we present some of these tools to convert from a simple syntax to MathML.

- - - -

Client-side Conversion

- -

In a Web environment, the most obvious method to convert a simple syntax into a DOM tree is to use Javascript and of course many libraries have been developed to perform that task.

- - - -

TeXZilla has an <x-tex> custom element, that can be used to write things like

- -
<x-tex>\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1</x-tex>
- -

and get it automatically converted into MathML. This is still a work-in-progress, but could be improved in the future thanks to Web Components and shadow DOM. Alternatively, you can use the more traditional Javascript parsing of expressions at load time as all the other tools in this section do.

- -

One simple client-side conversion tools is ASCIIMathML. Just download the ASCIIMathML.js script and copy it to your Web site. Then on your Web pages, add a <script> tag to load ASCIIMathML and the mathematical expressions delimited by ` (grave accent) will be automatically parsed and converted to MathML:

- -
<html>
-<head>
-...
-<script type="text/javascript" src="ASCIIMathML.js"></script>
-...
-</head>
-<body>
-...
-<p>blah blah `x^2 + y^2 = r^2` blah ...
-...
- -

LaTeXMathML is a similar script that allows to parse more LaTeX commands. The installation is similar: copy LaTeXMathML.js and LaTeXMathML.standardarticle.css, add links in the header of your document and the LaTeX content of your Web page marked by the "LaTeX" class will be automatically parsed and converted to HTML+MathML:

- -
<head>
-...
-<script type="text/javascript" src="LaTeXMathML.js"></script>
-<link rel="stylesheet" type="text/css" href="LaTeXMathML.standardarticle.css" />
-...
-</head>
-
-<body>
-...
-
-<div class="LaTeX">
-\documentclass[12pt]{article}
-
-\begin{document}
-
-\title{LaTeXML Example}
-\maketitle
-
-\begin{abstract}
-This is a sample LaTeXML document.
-\end{abstract}
-
-\section{First Section}
-
-  $ \sum_{n=1}^{+\infty} \frac{1}{n^2} = \frac{\pi^2}{6} $
-
-\end{document}
-</div>
-...
- -

jqMath is another script to parse a simple LaTeX-like syntax but which also accepts non-ASCII characters like  √{∑↙{n=1}↖{+∞} 6/n^2} = π  to write n = 1 + 6 n 2 = π . The installation is similar: download and copy the relevant Javascript and CSS files on your Web site and reference them in your page header (see the COPY-ME.html file from the zip archive for an example). One of the advantage of jqMath over the previous scripts is that it will automatically add some simple CSS rules to do the mathematical layout and make the formulas readable on browsers with limited MathML support.

- -

Another way to work around the lack of MathML support in some browsers is to use MathJax. However, note that you may find conflicts and synchronization issues between MathJax and the Javascript libraries previously mentioned. So if you really want to use MathJax as a MathML polyfill, you'd better use its own LaTeX/ASCIIMath parsers too. Note that on the one hand MathJax has better parsing and rendering support but on the other hand it is much bigger, more complex and slower than the previous Javascript libraries. Fortunately, you can use MathJax's CDN so that you don't need to install it on your Web server. Also, the slowest part of MathJax is currently its HTML-CSS / SVG output modes so we recommend to use the Native MathML output for Gecko-based browsers. Hence a typical configuration to use the AMS-LaTeX input is:

- -
...
-    <script type="text/x-mathjax-config">
-      MathJax.Hub.Config({
-        MMLorHTML: { prefer: { Firefox: "MML" } }
-      });
-    </script>
-    <script type="text/javascript"
-            src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
-   </script>
-  </head>
-  <body>
-   \[ \tau = \frac{x}{y} + \sqrt{3} \]
-...
- -

Note that the dollar delimiters are not used by default. To use the ASCIIMathML input instead, just replace TeX-AMS-MML_HTMLorMML by AM-MML_HTMLorMML.  MathJax has many other features, see the MathJax documentation for further details.

- -

Command-line Programs

- -

An alternative way is to parse the simple syntax before publishing your web pages. That is, you use command-line programs to generate them and publish these static pages on your server.

- - - -

TeXZilla can be used from the command line and will essentially have the same support as itex2MML described below. However, the stream filter behavior is not implemented yet.

- -

If you only want to parse simple LaTeX mathematical expressions, you might want to try tools like itex2MML or Blahtex. The latter is often available on Linux distributions. Let's consider the former, which was originally written by Paul Gartside at the beginning of the Mozilla MathML project and has been maintained by Jacques Distler since then. It's a small stream filter written in C/C++ and generated with flex and bison ; in particular it is very fast. Install flex/bison as well as the classical compiler and make tools. On Unix, you can then download itex2MML, build and install it:

- -
wget http://golem.ph.utexas.edu/~distler/blog/files/itexToMML.tar.gz; \
-tar -xzf itexToMML.tar.gz; \
-cd itex2MML/itex-src;
-make
-sudo make install
- -

Now suppose that you have a HTML page with TeX fragments delimited by dollars:

- -
input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}$</p>
-  <p>$$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} $$</p>
-</body>
-</html>lt;/p>
-  <p>$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} $</p>
-</body>
-</html>lt;/p>
-  <p>$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} $</p>
-</body>
-</html>lt;/p>
-  <p>$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}input.html
-
-...
-</head>
-<body>
-  <p>$\sqrt{a^2-3c}$</p>
-  <p>$$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} $$</p>
-</body>
-</html>lt;/p>
-  <p>$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} $</p>
-</body>
-</html>lt;/p>
-</body>
-</html>
- -

Then to generate the HTML page input.html with TeX expressions replaced by MathML expressions, just do

- -
cat input.html | itex2MML > output.html
- -

There are even more sophisticated tools to convert arbitrary LaTeX documents into HTML+MathML. For example TeX4ht is often included in TeX distributions and has an option to use MathML instead of PNG images. This command will generate an XHTML+MathML document foo.xml from a foo.tex LaTeX source:

- -
   mk4ht mzlatex foo.tex # Linux/Mac platforms
-   mzlatex foo.tex       # Windows platform
-
- -

LaTeXML is another tool that is still actively developed but the release version is rather old, so you'd better install the development version. In particular, this version can generate HTML5 and EPUB documents. Here is the command to execute in order to create a foo.html Web page from the foo.tex LaTeX source:

- -
  latexml --dest foo.xml foo.tex
-  latexmlpost --dest foo.html --format=html5 foo.xml
-
- -

If you want to have a MathJax fallback for non-Gecko browsers, copy the Javascript lines given above into a mathjax.js file and use the --javascript parameter to tell LaTeXML to include that file:

- -
  latexmlpost --dest foo.html --format=html5 --javascript=mathjax.js foo.xml
-
- -

If your LaTeX document is big, you might want to split it into several small pages rather putting everything in a single page. This is especially true if you use the MathJax fallback above, since in that case MathJax will take a lot of time to render the equations in non-Gecko browsers. Use the --splitat parameter for that purpose. For example, this will split the pages at the \section level:

- -
  latexmlpost --dest foo.html --format=html5 --splitat=section foo.xml
-
- -

Finally, to generate an EPUB document, you can do

- -
  latexmlc --dest foo.epub --splitat=section foo.xml
-
- -

Server-side Conversion

- - - -

TeXZilla can be used as a Web server in order to perform server-side LaTeX-to-MathML conversion. LaTeXML can also be used as a deamon to run server-side. Mathoid is another tool based on MathJax that is also able to perform additional MathML-to-SVG conversion.

- -

Instiki is a Wiki that integrates itex2MML to do server-side conversion. In future versions, MediaWiki will support server-side conversion too.

- -

Graphical Interface

- -

Input Box

- -

TeXZilla has several interfaces, including a CKEditor plugin used on MDN, an online demo, a Firefox add-on or a FirefoxOS Webapp. Abiword contains a small equation editor, based on itex2MML. Bluegriffon is a mozilla-based Wysiwyg HTML editor and has an add-on to insert MathML formulas in your document, using ASCII/LaTeX-like syntax.

- -

BlueGriffon

- -

WYSIYWG Editors

- -

Firemath is an extension for Firefox that provides a WYSIWYG MathML editor. A preview of the formula is displayed using the rendering engine of Mozilla. The generated MathML code is available at the bottom. Use the text field for token elements and buttons to build advanced constructions. Once you are done, you can save your document as a XHTML page.

- -

OpenOffice and LibreOffice have an equation editor (File → New → Formula). It is semi-WYSIWYG: you enter the source of the formula using the equation panel/keyboard and a preview of the formula is regularly refreshed. The editor uses its own syntax "StarMath" for the source but MathML is also generated when the document is saved. To get the MathML code, save the document as mml and open it with any text editor. Alternatively, you can extract the odf file (which is actually a zip archive) and open an xml file called content.xml.

- -

Open Office Math

- -

Amaya is the W3C's web editor, which is able to handle MathML inside XHTML documents. Use the Elements and the Special Chars panels to create various advanced mathematical constructs. Simple text such as a+2 is automatically parsed and the appropriate MathML markup is generated. Once you are done, you can directly save your XHTML page and open it in Mozilla.

- -

Optical Character & Handwriting Recognition

- -

Inftyreader is able to perform some Optical Character Recognition, including translation of mathematical equations into MathML. Other tools can do handwriting recognition such as the Windows Math Input Panel

- -

or the online converter Web Equation.

- -

Original Document Information

- -
-
    -
  • Author(s): Frédéric Wang
  • -
  • Other Contributors: Florian Scholz
  • -
  • Last Updated Date: April 2, 2011
  • -
  • Copyright Information: Portions of this content are © 2010 by individual mozilla.org contributors; content available under a Creative Commons license | Details.
  • -
-
- -

 

diff --git a/files/es/web/mathml/authoring/openoffice.png b/files/es/web/mathml/authoring/openoffice.png deleted file mode 100644 index 4876bc83df..0000000000 Binary files a/files/es/web/mathml/authoring/openoffice.png and /dev/null differ diff --git a/files/es/web/media/formats/index.html b/files/es/web/media/formats/index.html deleted file mode 100644 index b11ddc3580..0000000000 --- a/files/es/web/media/formats/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: 'Media type and format guide: image, audio, and video content' -slug: Web/Media/Formats -tags: - - API - - Audio - - Codecs - - Containers - - File Types - - Files - - Filetypes - - Landing - - Media - - NeedsTranslation - - TopicStub - - Types - - Video - - Web - - formats -translation_of: Web/Media/Formats ---- -

{{QuickLinksWithSubpages("/en-US/docs/Web/Media")}}

- -

Since nearly its beginning, the web has included support for some form of visual media presentation. Originally, these capabilities were limited, and were expanded organically, with different browsers finding their own solutions to the problems around including still and video imagery on the web. The modern web has powerful features to support the presentation and manipulation of media, with several media-related APIs supporting various types of content. Generally, the media formats supported by a browser are entirely up to the browser's creators, which can complicate the work of a web developer.

- -

This guide provides an overview of the media file types, {{Glossary("codec", "codecs")}}, and algorithms that may comprise media used on the web. It also provides browser support information for various combinations of these, and suggestions for prioritization of formats, as well as which formats excel at specific types of content.

- -
-
-

References

- -

Images

- -
-
Image file type and format guide
-
Covers support of image file types and content formats across the major web browsers, as well as providing basic information about each type: benefits, limitations, and use cases of interest to web designers and developers.
-
Image file types for web designers
-
Fundamental information about the various image file types that may be useful for web designers, including best practices and use cases for each type, and guidelines for choosing the right image file format for specific types of content.
-
- -

Media file types and codecs

- -
-
Media containers (file types)
-
A guide to the file types that contain media data. Some are audio-specific, while others may be used for either audio or combined audiovisual content such as movies. Includes overviews of each of the file types supported by the major web browsers, along with browser support information and supported features.
-
- -
-
Web audio codec guide
-
A guide to the audio codecs allowed for by the common media containers, as well as by the major browsers. Includes benefits, limitations, key specifications and capabilities, and use cases. It also covers each browser's support for using the codec in given containers.
-
Web video codec guide
-
This article provides basic information about the video codecs supported by the major browsers, as well as some that are not commonly supported but that you might still run into. It also covers codec capabilities, benefits, limitations, and browser support levels and restrictions.
-
The "codecs" parameter in common media types
-
When specifying the MIME type describing a media format, you can provide details using the codecs parameter as part of the type string. This guide describes the format and possible values of the codecs parameter for the common media types.
-
Codecs used by WebRTC
-
WebRTC doesn't use a container, but instead streams the encoded media itself from peer to peer using {{domxref("MediaStreamTrack")}} objects to represent each audio or video track. This guide discusses the codecs commonly used with WebRTC.
-
-
- -
-

Guides

- -

Concepts

- -
-
Digital audio concepts
-
An introduction to how audio is converted into digital form and stored for use by computers. It explains basic concepts about how audio is sampled, as well as concepts such as sample rate, audio frames, and audio compression.
-
Digital video concepts
-
A guide to fundamental concepts involved with digital video as used on the web, including basics about color formats, chroma subsampling, how human perception influences video coding, and so forth.
-
- -

Tutorials and how-tos

- -
-
Learning: Video and audio content
-
This tutorial introduces and details the use of media on the web.
-
Handling media support issues in web content
-
In this guide, we look at how to build web content that maximizes quality or performance while providing the broadest possible compatibility, by choosing media formats wisely, and offering fallbacks and alternate formats where it would be helpful.
-
- -

Other topics

- -
-
Media Capabilities API
-
The Media Capabilities API lets you discover the encoding and decoding capabilities of the device your app or site is running on. This lets you make real-time decisions about what formats to use and when.
-
-
-
diff --git a/files/es/web/svg/element/foreignobject/index.html b/files/es/web/svg/element/foreignobject/index.html deleted file mode 100644 index ea64360cbb..0000000000 --- a/files/es/web/svg/element/foreignobject/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: foreignObject -slug: Web/SVG/Element/foreignObject -translation_of: Web/SVG/Element/foreignObject ---- -
{{SVGRef}}
- -

El elemento foreignObject permite la inclusión de un namespace XML externo que tiene su contenido gráfico dibujado por un diferente user-agent. El contenido gráfico externo incluido está sujeto a las transformaciones SVG y composición.

- -

The contents of foreignObject are assumed to be from a different namespace. Any SVG elements within a foreignObject will not be drawn, except in the situation where a properly defined SVG subdocument with a proper xmlns attribute specification is embedded recursively. One situation where this can occur is when an SVG document fragment is embedded within another non-SVG document fragment, which in turn is embedded within an SVG document fragment (e.g., an SVG document fragment contains an XHTML document fragment which in turn contains yet another SVG document fragment).

- -

Usually, a foreignObject will be used in conjunction with the {{ SVGElement("switch") }} element and the {{ SVGAttr("requiredExtensions") }} attribute to provide proper checking for user agent support and provide an alternate rendering in case user agent support is not available.

- -

Usage context

- -

{{svginfo}}

- -

Example

- -
<svg width="400px" height="300px" viewBox="0 0 400 300"
-     xmlns="http://www.w3.org/2000/svg">
-  <desc>This example uses the 'switch' element to provide a
-        fallback graphical representation of a paragraph, if
-        XHTML is not supported.</desc>
-
-  <!-- The 'switch' element will process the first child element
-       whose testing attributes evaluate to true.-->
-  <switch>
-
-    <!-- Process the embedded XHTML if the requiredExtensions attribute
-         evaluates to true (i.e., the user agent supports XHTML
-         embedded within SVG). -->
-    <foreignObject width="100" height="50"
-                   requiredExtensions="http://www.w3.org/1999/xhtml">
-      <!-- XHTML content goes here -->
-      <body xmlns="http://www.w3.org/1999/xhtml">
-        <p>Here is a paragraph that requires word wrap</p>
-      </body>
-    </foreignObject>
-
-    <!-- Else, process the following alternate SVG.
-         Note that there are no testing attributes on the 'text' element.
-         If no testing attributes are provided, it is as if there
-         were testing attributes and they evaluated to true.-->
-    <text font-size="10" font-family="Verdana">
-      <tspan x="10" y="10">Here is a paragraph that</tspan>
-      <tspan x="10" y="20">requires word wrap.</tspan>
-    </text>
-  </switch>
-</svg>
-
- -

Attributes

- -

Global attributes

- - - -

Specific attributes

- - - -

DOM Interface

- -

This element implements the SVGForeignObjectElement interface.

- -

Browser compatibility

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.01.9{{ CompatNo() }}2.03.0
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}2.0{{ CompatNo() }}2.03.0
-
- -

The chart is based on these sources.

diff --git a/files/es/web/xslt/element/number/index.html b/files/es/web/xslt/element/number/index.html deleted file mode 100644 index 519c2361c2..0000000000 --- a/files/es/web/xslt/element/number/index.html +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: number -slug: Web/XSLT/Element/number -tags: - - Todas_las_Categorías - - XSLT -translation_of: Web/XSLT/Element/number -original_slug: Web/XSLT/number ---- -

{{XsltRef}}

- -

El elemento <xsl:number> hace conteos secuenciales. También puede ser usado para darle formato a los números.

- -

Sintaxis

- -
<xsl:number
-	count=EXPRESION
-	level="single" | "multiple" | "any"
-	from=EXPRESION
-	value=EXPRESION
-	format=FORMAT-STRING
-	lang=XML:LANG-CODE
-	letter-value="alphabetic" | "traditional"
-	grouping-separator=CARACTER
-	grouping-size=NUMERO  />
- -

Atributos requeridos

- -

Ninguno.

- -

Atributos opcionales

- -
-
count
-
Indica que es lo que debe ser numerado de manera secuencial. Usa una expresión XPath.
-
- -
-
level
-
Define cuantos niveles del documento deben ser tomados en cuenta para generar la secuencia numérica. Tiene 3 valores permitidos: single, multiple, y any. El valor por preestablecido es single:
-
- -
-
-
-
single
-
Numera los nodos hermanos de manera secuencia, como en los listados. ... CONTINUAR DESDE AQUÍ...
-
Numbers sibling nodes sequentially, as in the items in a list. The processor goes to the first node in the ancestor-or-self axis that matches the count attribute and then counts that node plus all its preceding siblings (stopping when it reaches a match to the from attribute, if there is one) that also match the count attribute.If no match is found, the sequence will be an empty list.
-
-
-
- -
-
-
-
multiple
-
Numbers nodes as a composite sequence that reflects the hierarchic position of the node, e.g. 1.2.2.5. (The nested format can be specified with the format attribute, e.g. A.1.1). The processor looks at all ancestors of the current node and the current node itself, stopping when it reaches a match for the from attribute, if there is one. For each node in this list that matches the count attribute, the processor counts how many preceding matching siblings it has, and adds one for the node itself. If no match is found, the sequence will be an empty list.
-
-
-
- -
-
-
-
any (Not supported at this time.)
-
Numbers all matching nodes, regardless of level, sequentially. The ancestor, self, and preceding axes are all considered. The processor starts at the current node and proceeds in reverse document order, stopping if it reaches a match to any from attribute. If no match to the count attribute is found, the sequence will be an empty list. This level is not supported at this time.
-
-
-
- -
-
from
-
Specifies where the numbering should start or start over. The sequence begins with the first descendant of the node that matches the from attribute.
-
- -
-
value
-
Applies a given format to a number. This is a quick way to format a user-supplied number (as opposed to a node sequence number) in any of the standard <xsl:number> formats.
-
- -
-
format
-
Defines the format of the generated number:
-
- -
-
-
-
format="1"
-
1 2 3 . . . (This is the only format supported at this time)
-
-
-
- -
-
-
-
format="01"
-
01 02 03 . . . 09 10 11 . . .
-
-
-
- -
-
-
-
format="a"
-
a b c . . .y z aa ab . . .
-
-
-
- -
-
-
-
format="A"
-
A B C . . . Y Z AA AB . . .
-
-
-
- -
-
-
-
format="i"
-
i ii iii iv v . . .
-
-
-
- -
-
-
-
format="I"
-
I II III IV V . . .
-
-
-
- -
-
lang (Not supported at this time.)
-
Specifies which language's alphabet should be used in letter-based numbering formats.
-
- -
-
letter-value
-
Disambiguates between numbering sequences that use letters. Some languages have more than one numbering system that use letters. If both systems begin with the same token, ambiguity can arise. This attribute can have the value "alphabetic" or "traditional". The default is "alphabetic".
-
- -
-
grouping-separator
-
Specifies what character should be used as the group (e.g. thousands) separator. The default is the comma (,).
-
- -
-
grouping-size
-
Indicates the number of digits that make up a numeric group. The default value is "3".
-
- -

Type

- -

Instruction, appears within a template.

- -

Defined

- -

XSLT, section 7.7

- -

Gecko support

- -

Partial support. See comments above.

-- cgit v1.2.3-54-g00ecf