From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- files/id/_redirects.txt | 26 + files/id/_wikihistory.json | 2171 ++++++++++++++++++ files/id/archive/add-ons/index.html | 11 + .../b2g_os/developing_firefox_os/index.html | 51 + .../developing_firefox_os/porting/index.html | 123 ++ files/id/archive/b2g_os/firefox_os_apps/index.html | 85 + .../b2g_os/firefox_os_apps/pelokalan/index.html | 92 + files/id/archive/b2g_os/index.html | 79 + .../installing_on_a_mobile_device/index.html | 100 + files/id/archive/b2g_os/introduction/index.html | 88 + .../id/archive/b2g_os/phone_guide/flame/index.html | 73 + .../flame/updating_your_flame/index.html | 411 ++++ files/id/archive/b2g_os/phone_guide/index.html | 85 + files/id/archive/b2g_os/platform/index.html | 82 + .../quickstart/aplikasi_pertama_kamu/index.html | 210 ++ files/id/archive/b2g_os/quickstart/index.html | 49 + files/id/archive/b2g_os/simulator/index.html | 120 + .../b2g_os/using_the_app_manager/index.html | 233 ++ files/id/archive/css3/index.html | 972 ++++++++ files/id/archive/index.html | 18 + files/id/archive/meta_docs/index.html | 11 + files/id/archive/mozilla/index.html | 8 + files/id/archive/mozilla/xul/index.html | 84 + .../index.html | 23 + .../archive/mozilla/xul/school_tutorial/index.html | 59 + .../xul/school_tutorial/perkenalan/index.html | 32 + .../the_essentials_of_an_extension/index.html | 344 +++ files/id/archive/mozilla/xulrunner/index.html | 84 + files/id/archive/web/index.html | 15 + .../standards-compliant_authoring_tools/index.html | 25 + files/id/developer_guide/index.html | 145 ++ .../virtual_arm_di_lingkungan_linux/index.html | 77 + files/id/games/index.html | 95 + .../publishing_games/game_promotion/index.html | 86 + files/id/games/publishing_games/index.html | 28 + files/id/games/techniques/index.html | 32 + files/id/glossary/404/index.html | 17 + files/id/glossary/ajax/index.html | 22 + files/id/glossary/algoritma/index.html | 8 + files/id/glossary/api/index.html | 24 + files/id/glossary/asynchronous/index.html | 14 + files/id/glossary/css/index.html | 48 + files/id/glossary/html/index.html | 44 + files/id/glossary/http/index.html | 22 + files/id/glossary/identifier/index.html | 16 + files/id/glossary/index.html | 27 + files/id/glossary/javascript/index.html | 45 + files/id/glossary/json/index.html | 24 + files/id/glossary/method/index.html | 29 + files/id/glossary/null/index.html | 27 + files/id/glossary/primitive/index.html | 32 + files/id/glossary/property/index.html | 11 + files/id/glossary/python/index.html | 19 + files/id/glossary/seo/index.html | 42 + files/id/glossary/statement/index.html | 21 + files/id/glossary/svg/index.html | 37 + files/id/glossary/url/index.html | 27 + files/id/glossary/variable/index.html | 21 + files/id/glossary/xml/index.html | 11 + files/id/learn/accessibility/index.html | 63 + .../bagaimana_cara_kerja_internet/index.html | 98 + .../berfikir_sebelum_membuat_kode/index.html | 180 ++ files/id/learn/common_questions/index.html | 135 ++ .../index.html | 118 + .../set_up_a_local_testing_server/index.html | 108 + files/id/learn/css/index.html | 67 + .../index.html | 117 + .../css_basics/index.html | 291 +++ .../how_the_web_works/index.html | 96 + .../html_basics/index.html | 233 ++ .../learn/getting_started_with_the_web/index.html | 76 + .../installing_basic_software/index.html | 76 + .../javascript_basics/index.html | 398 ++++ .../mengelola_file/index.html | 123 ++ .../publishing_your_website/index.html | 111 + files/id/learn/how_to_contribute/index.html | 108 + files/id/learn/html/howto/index.html | 142 ++ files/id/learn/html/index.html | 58 + .../adding_vector_graphics_to_the_web/index.html | 362 +++ .../learn/html/multimedia_dan_embedding/index.html | 73 + .../responsive_images/index.html | 251 +++ .../document_and_website_structure/index.html | 293 +++ .../html_text_fundamentals/index.html | 1047 +++++++++ files/id/learn/html/pengenalan_html/index.html | 64 + .../structuring_a_page_of_content/index.html | 116 + files/id/learn/html/tabel/index.html | 36 + files/id/learn/index.html | 97 + .../id/learn/javascript/building_blocks/index.html | 42 + .../javascript/client-side_web_apis/index.html | 50 + .../client-side_web_apis/introduction/index.html | 278 +++ files/id/learn/javascript/first_steps/index.html | 63 + .../first_steps/what_is_javascript/index.html | 433 ++++ files/id/learn/javascript/index.html | 57 + .../javascript/objects/dasar-dasar/index.html | 261 +++ files/id/learn/javascript/objects/index.html | 54 + .../django/development_environment/index.html | 423 ++++ files/id/learn/server-side/django/index.html | 67 + .../tutorial_local_library_website/index.html | 90 + files/id/learn/server-side/first_steps/index.html | 39 + files/id/learn/server-side/index.html | 59 + files/id/learn/web_mechanics/index.html | 29 + files/id/mdn/about/index.html | 135 ++ files/id/mdn/contribute/feedback/index.html | 56 + files/id/mdn/contribute/getting_started/index.html | 126 ++ .../howto/create_an_mdn_account/index.html | 44 + .../howto/do_a_technical_review/index.html | 49 + .../howto/do_an_editorial_review/index.html | 52 + files/id/mdn/contribute/howto/index.html | 16 + .../howto/set_the_summary_for_a_page/index.html | 46 + files/id/mdn/contribute/howto/tag/index.html | 373 ++++ files/id/mdn/contribute/index.html | 23 + files/id/mdn/contribute/processes/index.html | 23 + files/id/mdn/contribute/tugas/index.html | 25 + files/id/mdn/guidelines/index.html | 16 + files/id/mdn/guidelines/layout/index.html | 7 + .../mdn/guidelines/writing_style_guide/index.html | 802 +++++++ files/id/mdn/index.html | 46 + files/id/mdn/komunitas/conversations/index.html | 56 + files/id/mdn/komunitas/index.html | 75 + files/id/mdn/user_guide/index.html | 13 + .../id/mdn/user_guide/menghapus_halaman/index.html | 17 + files/id/mozilla/add-ons/index.html | 16 + .../index.html | 167 ++ .../webextensions/apa_itu_webextensions/index.html | 34 + .../webextensions/api/browsersettings/index.html | 63 + .../mozilla/add-ons/webextensions/api/index.html | 50 + .../webextensions/api/notifikasi/index.html | 62 + .../api/windows/createtype/index.html | 65 + .../add-ons/webextensions/api/windows/index.html | 127 ++ .../browser_support_for_javascript_apis/index.html | 21 + .../webextensions/content_scripts/index.html | 554 +++++ files/id/mozilla/add-ons/webextensions/index.html | 91 + .../your_first_webextension/index.html | 153 ++ files/id/mozilla/connect/index.html | 95 + .../id/mozilla/firefox/edisi_pengembang/index.html | 57 + files/id/mozilla/firefox/index.html | 75 + files/id/mozilla/firefox/privacy/index.html | 22 + .../errors/cookieblockedtracker/index.html | 33 + .../storage_access_policy/errors/index.html | 24 + .../privacy/storage_access_policy/index.html | 261 +++ files/id/mozilla/firefox/releases/index.html | 12 + files/id/mozilla/gecko/index.html | 69 + files/id/mozilla/index.html | 13 + files/id/mozilla/localization/index.html | 30 + .../localizing_with_verbatim/index.html | 158 ++ .../localization/quick_start_guide/index.html | 50 + .../quick_start_guide/qa_phase/index.html | 197 ++ .../localization/web_localizability/index.html | 33 + files/id/mozilla/mercurial/basics/index.html | 60 + files/id/mozilla/mercurial/index.html | 45 + files/id/mozilla/persona/index.html | 126 ++ files/id/mozilla/projects/index.html | 14 + files/id/mozilla/projects/nss/index.html | 180 ++ files/id/mozilla/projects/rhino/index.html | 25 + files/id/pengembangan_web/index.html | 78 + files/id/sandbox/index.html | 201 ++ files/id/tools/accessibility_inspector/index.html | 196 ++ files/id/tools/debugger/index.html | 49 + files/id/tools/index.html | 189 ++ files/id/tools/page_inspector/how_to/index.html | 13 + files/id/tools/page_inspector/index.html | 53 + files/id/tools/remote_debugging/index.html | 34 + files/id/tools/webide/index.html | 458 ++++ files/id/tools/webide/troubleshooting/index.html | 117 + files/id/web/api/abstractworker/index.html | 125 ++ files/id/web/api/api_push/index.html | 165 ++ files/id/web/api/cachestorage/index.html | 198 ++ files/id/web/api/canvas_api/index.html | 172 ++ files/id/web/api/console/index.html | 278 +++ files/id/web/api/document/createelement/index.html | 225 ++ files/id/web/api/document/index.html | 576 +++++ files/id/web/api/document/links/index.html | 101 + files/id/web/api/document/write/index.html | 77 + files/id/web/api/event/currenttarget/index.html | 127 ++ files/id/web/api/event/index.html | 149 ++ files/id/web/api/event/target/index.html | 90 + files/id/web/api/fetch_api/index.html | 88 + files/id/web/api/index.html | 12 + files/id/web/api/mobile_connection_api/index.html | 149 ++ files/id/web/api/navigator/index.html | 149 ++ files/id/web/api/navigator/mediadevices/index.html | 47 + .../id/web/api/navigator/serviceworker/index.html | 101 + files/id/web/api/service_worker_api/index.html | 283 +++ .../using_service_workers/index.html | 539 +++++ files/id/web/api/serviceworker/index.html | 157 ++ files/id/web/api/serviceworkercontainer/index.html | 132 ++ .../web/api/serviceworkerregistration/index.html | 245 +++ .../pushmanager/index.html | 130 ++ files/id/web/api/speechsynthesis/index.html | 151 ++ .../api/speechsynthesis/onvoiceschanged/index.html | 74 + files/id/web/api/storage/index.html | 100 + files/id/web/api/webgl_api/index.html | 235 ++ files/id/web/api/webrtc_api/index.html | 185 ++ files/id/web/api/window/getselection/index.html | 100 + files/id/web/api/window/index.html | 479 ++++ files/id/web/api/window/window/index.html | 63 + files/id/web/api/xmlhttprequest/index.html | 200 ++ .../xmlhttprequest/using_xmlhttprequest/index.html | 793 +++++++ .../id/web/css/@font-face/font-display/index.html | 101 + files/id/web/css/@font-face/index.html | 199 ++ files/id/web/css/_colon_active/index.html | 143 ++ files/id/web/css/background-color/index.html | 149 ++ files/id/web/css/css_box_model/index.html | 115 + .../introduction_to_the_css_box_model/index.html | 73 + files/id/web/css/css_selectors/index.html | 154 ++ .../index.html | 64 + files/id/web/css/flex-direction/index.html | 155 ++ files/id/web/css/index.html | 64 + files/id/web/css/mask-border-width/index.html | 104 + files/id/web/css/referensi/index.html | 185 ++ files/id/web/css/text-transform/index.html | 307 +++ files/id/web/css/type_selectors/index.html | 121 + files/id/web/events/cached/index.html | 74 + files/id/web/events/error/index.html | 71 + files/id/web/events/index.html | 2310 ++++++++++++++++++++ files/id/web/guide/api/index.html | 26 + files/id/web/guide/api/webrtc/index.html | 34 + files/id/web/guide/css/getting_started/index.html | 32 + files/id/web/guide/css/media_queries/index.html | 630 ++++++ files/id/web/guide/grafis/index.html | 48 + files/id/web/guide/html/forms/index.html | 340 +++ files/id/web/guide/html/html5/index.html | 179 ++ files/id/web/guide/index.html | 55 + files/id/web/html/element/base/index.html | 154 ++ files/id/web/html/element/dialog/index.html | 165 ++ files/id/web/html/element/image/index.html | 16 + files/id/web/html/element/index.html | 106 + files/id/web/html/index.html | 97 + files/id/web/http/basics_of_http/index.html | 51 + files/id/web/http/gambaran/index.html | 173 ++ files/id/web/http/index.html | 81 + files/id/web/http/methods/get/index.html | 73 + files/id/web/http/methods/index.html | 76 + .../http/proxy_servers_and_tunneling/index.html | 100 + .../proxy_auto-configuration_(pac)_file/index.html | 727 ++++++ files/id/web/http/status/100/index.html | 46 + files/id/web/http/status/200/index.html | 50 + files/id/web/http/status/400/index.html | 39 + files/id/web/http/status/403/index.html | 56 + files/id/web/http/status/404/index.html | 63 + files/id/web/http/status/405/index.html | 44 + files/id/web/http/status/410/index.html | 54 + files/id/web/http/status/500/index.html | 38 + files/id/web/http/status/index.html | 141 ++ files/id/web/index.html | 153 ++ .../a_re-introduction_to_javascript/index.html | 862 ++++++++ files/id/web/javascript/data_structures/index.html | 267 +++ files/id/web/javascript/index.html | 116 + .../inheritance_dan_prototype_chain/index.html | 304 +++ .../web/javascript/language_resources/index.html | 136 ++ .../id/web/javascript/memory_management/index.html | 187 ++ .../id/web/javascript/new_in_javascript/index.html | 74 + .../id/web/javascript/panduan/closures/index.html | 345 +++ files/id/web/javascript/panduan/index.html | 119 + .../panduan/loops_and_iteration/index.html | 330 +++ .../panduan/numbers_and_dates/index.html | 376 ++++ .../web/javascript/panduan/pengenalan/index.html | 156 ++ files/id/web/javascript/panduan/tentang/index.html | 144 ++ .../values,_variables,_and_literals/index.html | 648 ++++++ .../panduan/working_with_objects/index.html | 492 +++++ files/id/web/javascript/reference/about/index.html | 86 + .../reference/classes/constructor/index.html | 162 ++ .../reference/classes/extends/index.html | 112 + .../id/web/javascript/reference/classes/index.html | 383 ++++ .../errors/called_on_incompatible_type/index.html | 69 + .../id/web/javascript/reference/errors/index.html | 12 + .../errors/invalid_array_length/index.html | 78 + .../missing_semicolon_before_statement/index.html | 78 + .../errors/negative_repetition_count/index.html | 45 + .../reference/errors/not_a_codepoint/index.html | 56 + .../reference/errors/not_defined/index.html | 66 + .../errors/property_access_denied/index.html | 47 + .../reference/errors/too_much_recursion/index.html | 70 + .../web/javascript/reference/functions/index.html | 596 +++++ .../global_objects/array/concat/index.html | 169 ++ .../global_objects/array/filter/index.html | 244 +++ .../reference/global_objects/array/from/index.html | 248 +++ .../reference/global_objects/array/index.html | 484 ++++ .../global_objects/array/isarray/index.html | 144 ++ .../reference/global_objects/array/join/index.html | 132 ++ .../global_objects/array/length/index.html | 145 ++ .../reference/global_objects/array/of/index.html | 129 ++ .../reference/global_objects/array/pop/index.html | 134 ++ .../global_objects/array/reverse/index.html | 127 ++ .../global_objects/array/shift/index.html | 129 ++ .../global_objects/array/slice/index.html | 152 ++ .../global_objects/array/splice/index.html | 146 ++ .../global_objects/array/unshift/index.html | 135 ++ .../global_objects/array/values/index.html | 120 + .../global_objects/date/getfullyear/index.html | 88 + .../reference/global_objects/date/index.html | 261 +++ .../reference/global_objects/date/now/index.html | 124 ++ .../global_objects/date/tojson/index.html | 119 + .../global_objects/date/totimestring/index.html | 125 ++ .../reference/global_objects/error/index.html | 231 ++ .../reference/global_objects/error/name/index.html | 119 + .../global_objects/function/displayname/index.html | 123 ++ .../reference/global_objects/function/index.html | 241 ++ .../global_objects/function/length/index.html | 148 ++ .../global_objects/function/name/index.html | 191 ++ .../global_objects/function/prototype/index.html | 143 ++ .../javascript/reference/global_objects/index.html | 189 ++ .../reference/global_objects/isnan/index.html | 186 ++ .../reference/global_objects/json/index.html | 243 ++ .../reference/global_objects/json/parse/index.html | 171 ++ .../reference/global_objects/map/clear/index.html | 109 + .../reference/global_objects/map/delete/index.html | 114 + .../reference/global_objects/map/index.html | 443 ++++ .../reference/global_objects/math/abs/index.html | 145 ++ .../reference/global_objects/math/ceil/index.html | 174 ++ .../reference/global_objects/math/e/index.html | 81 + .../reference/global_objects/math/floor/index.html | 210 ++ .../reference/global_objects/math/index.html | 213 ++ .../reference/global_objects/math/ln10/index.html | 81 + .../reference/global_objects/math/max/index.html | 144 ++ .../reference/global_objects/math/min/index.html | 150 ++ .../reference/global_objects/math/pow/index.html | 53 + .../object/getprototypeof/index.html | 133 ++ .../reference/global_objects/object/index.html | 221 ++ .../global_objects/object/keys/index.html | 197 ++ .../object/preventextensions/index.html | 185 ++ .../global_objects/promise/catch/index.html | 127 ++ .../reference/global_objects/promise/index.html | 317 +++ .../global_objects/promise/reject/index.html | 81 + .../global_objects/promise/resolve/index.html | 140 ++ .../global_objects/promise/then/index.html | 132 ++ .../reference/global_objects/regexp/index.html | 231 ++ .../global_objects/string/concat/index.html | 134 ++ .../global_objects/string/fromcharcode/index.html | 143 ++ .../global_objects/string/fromcodepoint/index.html | 149 ++ .../reference/global_objects/string/index.html | 371 ++++ .../global_objects/string/indexof/index.html | 190 ++ .../global_objects/string/length/index.html | 126 ++ .../global_objects/string/link/index.html | 130 ++ .../global_objects/string/purwarupa/index.html | 221 ++ .../global_objects/string/split/index.html | 241 ++ .../global_objects/string/tolowercase/index.html | 121 + .../global_objects/string/tostring/index.html | 118 + .../global_objects/string/touppercase/index.html | 115 + .../reference/global_objects/typedarray/index.html | 344 +++ .../global_objects/typedarray/join/index.html | 114 + files/id/web/javascript/reference/index.html | 48 + .../reference/lexical_grammar/index.html | 670 ++++++ .../operators/conditional_operator/index.html | 167 ++ .../reference/operators/fungsi/index.html | 153 ++ .../web/javascript/reference/operators/index.html | 269 +++ .../reference/operators/yield/index.html | 109 + .../reference/statements/class/index.html | 171 ++ .../reference/statements/do...while/index.html | 101 + .../reference/statements/empty/index.html | 147 ++ .../reference/statements/export/index.html | 171 ++ .../reference/statements/for...in/index.html | 201 ++ .../reference/statements/fungsi/index.html | 232 ++ .../web/javascript/reference/statements/index.html | 139 ++ .../sekilas_teknologi_javascript/index.html | 87 + files/id/web/mathml/element/index.html | 234 ++ files/id/web/mathml/index.html | 76 + files/id/web/reference/api/index.html | 65 + files/id/web/reference/index.html | 49 + files/id/web/security/index.html | 12 + files/id/web/web_components/index.html | 230 ++ files/id/zones/index.html | 70 + 362 files changed, 56353 insertions(+) create mode 100644 files/id/_redirects.txt create mode 100644 files/id/_wikihistory.json create mode 100644 files/id/archive/add-ons/index.html create mode 100644 files/id/archive/b2g_os/developing_firefox_os/index.html create mode 100644 files/id/archive/b2g_os/developing_firefox_os/porting/index.html create mode 100644 files/id/archive/b2g_os/firefox_os_apps/index.html create mode 100644 files/id/archive/b2g_os/firefox_os_apps/pelokalan/index.html create mode 100644 files/id/archive/b2g_os/index.html create mode 100644 files/id/archive/b2g_os/installing_on_a_mobile_device/index.html create mode 100644 files/id/archive/b2g_os/introduction/index.html create mode 100644 files/id/archive/b2g_os/phone_guide/flame/index.html create mode 100644 files/id/archive/b2g_os/phone_guide/flame/updating_your_flame/index.html create mode 100644 files/id/archive/b2g_os/phone_guide/index.html create mode 100644 files/id/archive/b2g_os/platform/index.html create mode 100644 files/id/archive/b2g_os/quickstart/aplikasi_pertama_kamu/index.html create mode 100644 files/id/archive/b2g_os/quickstart/index.html create mode 100644 files/id/archive/b2g_os/simulator/index.html create mode 100644 files/id/archive/b2g_os/using_the_app_manager/index.html create mode 100644 files/id/archive/css3/index.html create mode 100644 files/id/archive/index.html create mode 100644 files/id/archive/meta_docs/index.html create mode 100644 files/id/archive/mozilla/index.html create mode 100644 files/id/archive/mozilla/xul/index.html create mode 100644 files/id/archive/mozilla/xul/international_characters_in_xul_javascript/index.html create mode 100644 files/id/archive/mozilla/xul/school_tutorial/index.html create mode 100644 files/id/archive/mozilla/xul/school_tutorial/perkenalan/index.html create mode 100644 files/id/archive/mozilla/xul/school_tutorial/the_essentials_of_an_extension/index.html create mode 100644 files/id/archive/mozilla/xulrunner/index.html create mode 100644 files/id/archive/web/index.html create mode 100644 files/id/archive/web/standards-compliant_authoring_tools/index.html create mode 100644 files/id/developer_guide/index.html create mode 100644 files/id/developer_guide/virtual_arm_di_lingkungan_linux/index.html create mode 100644 files/id/games/index.html create mode 100644 files/id/games/publishing_games/game_promotion/index.html create mode 100644 files/id/games/publishing_games/index.html create mode 100644 files/id/games/techniques/index.html create mode 100644 files/id/glossary/404/index.html create mode 100644 files/id/glossary/ajax/index.html create mode 100644 files/id/glossary/algoritma/index.html create mode 100644 files/id/glossary/api/index.html create mode 100644 files/id/glossary/asynchronous/index.html create mode 100644 files/id/glossary/css/index.html create mode 100644 files/id/glossary/html/index.html create mode 100644 files/id/glossary/http/index.html create mode 100644 files/id/glossary/identifier/index.html create mode 100644 files/id/glossary/index.html create mode 100644 files/id/glossary/javascript/index.html create mode 100644 files/id/glossary/json/index.html create mode 100644 files/id/glossary/method/index.html create mode 100644 files/id/glossary/null/index.html create mode 100644 files/id/glossary/primitive/index.html create mode 100644 files/id/glossary/property/index.html create mode 100644 files/id/glossary/python/index.html create mode 100644 files/id/glossary/seo/index.html create mode 100644 files/id/glossary/statement/index.html create mode 100644 files/id/glossary/svg/index.html create mode 100644 files/id/glossary/url/index.html create mode 100644 files/id/glossary/variable/index.html create mode 100644 files/id/glossary/xml/index.html create mode 100644 files/id/learn/accessibility/index.html create mode 100644 files/id/learn/common_questions/bagaimana_cara_kerja_internet/index.html create mode 100644 files/id/learn/common_questions/berfikir_sebelum_membuat_kode/index.html create mode 100644 files/id/learn/common_questions/index.html create mode 100644 files/id/learn/common_questions/pages_sites_servers_and_search_engines/index.html create mode 100644 files/id/learn/common_questions/set_up_a_local_testing_server/index.html create mode 100644 files/id/learn/css/index.html create mode 100644 files/id/learn/getting_started_with_the_web/akan_terlihat_seperti_apa_website_anda/index.html create mode 100644 files/id/learn/getting_started_with_the_web/css_basics/index.html create mode 100644 files/id/learn/getting_started_with_the_web/how_the_web_works/index.html create mode 100644 files/id/learn/getting_started_with_the_web/html_basics/index.html create mode 100644 files/id/learn/getting_started_with_the_web/index.html create mode 100644 files/id/learn/getting_started_with_the_web/installing_basic_software/index.html create mode 100644 files/id/learn/getting_started_with_the_web/javascript_basics/index.html create mode 100644 files/id/learn/getting_started_with_the_web/mengelola_file/index.html create mode 100644 files/id/learn/getting_started_with_the_web/publishing_your_website/index.html create mode 100644 files/id/learn/how_to_contribute/index.html create mode 100644 files/id/learn/html/howto/index.html create mode 100644 files/id/learn/html/index.html create mode 100644 files/id/learn/html/multimedia_dan_embedding/adding_vector_graphics_to_the_web/index.html create mode 100644 files/id/learn/html/multimedia_dan_embedding/index.html create mode 100644 files/id/learn/html/multimedia_dan_embedding/responsive_images/index.html create mode 100644 files/id/learn/html/pengenalan_html/document_and_website_structure/index.html create mode 100644 files/id/learn/html/pengenalan_html/html_text_fundamentals/index.html create mode 100644 files/id/learn/html/pengenalan_html/index.html create mode 100644 files/id/learn/html/pengenalan_html/structuring_a_page_of_content/index.html create mode 100644 files/id/learn/html/tabel/index.html create mode 100644 files/id/learn/index.html create mode 100644 files/id/learn/javascript/building_blocks/index.html create mode 100644 files/id/learn/javascript/client-side_web_apis/index.html create mode 100644 files/id/learn/javascript/client-side_web_apis/introduction/index.html create mode 100644 files/id/learn/javascript/first_steps/index.html create mode 100644 files/id/learn/javascript/first_steps/what_is_javascript/index.html create mode 100644 files/id/learn/javascript/index.html create mode 100644 files/id/learn/javascript/objects/dasar-dasar/index.html create mode 100644 files/id/learn/javascript/objects/index.html create mode 100644 files/id/learn/server-side/django/development_environment/index.html create mode 100644 files/id/learn/server-side/django/index.html create mode 100644 files/id/learn/server-side/django/tutorial_local_library_website/index.html create mode 100644 files/id/learn/server-side/first_steps/index.html create mode 100644 files/id/learn/server-side/index.html create mode 100644 files/id/learn/web_mechanics/index.html create mode 100644 files/id/mdn/about/index.html create mode 100644 files/id/mdn/contribute/feedback/index.html create mode 100644 files/id/mdn/contribute/getting_started/index.html create mode 100644 files/id/mdn/contribute/howto/create_an_mdn_account/index.html create mode 100644 files/id/mdn/contribute/howto/do_a_technical_review/index.html create mode 100644 files/id/mdn/contribute/howto/do_an_editorial_review/index.html create mode 100644 files/id/mdn/contribute/howto/index.html create mode 100644 files/id/mdn/contribute/howto/set_the_summary_for_a_page/index.html create mode 100644 files/id/mdn/contribute/howto/tag/index.html create mode 100644 files/id/mdn/contribute/index.html create mode 100644 files/id/mdn/contribute/processes/index.html create mode 100644 files/id/mdn/contribute/tugas/index.html create mode 100644 files/id/mdn/guidelines/index.html create mode 100644 files/id/mdn/guidelines/layout/index.html create mode 100644 files/id/mdn/guidelines/writing_style_guide/index.html create mode 100644 files/id/mdn/index.html create mode 100644 files/id/mdn/komunitas/conversations/index.html create mode 100644 files/id/mdn/komunitas/index.html create mode 100644 files/id/mdn/user_guide/index.html create mode 100644 files/id/mdn/user_guide/menghapus_halaman/index.html create mode 100644 files/id/mozilla/add-ons/index.html create mode 100644 files/id/mozilla/add-ons/setting_up_extension_development_environment/index.html create mode 100644 files/id/mozilla/add-ons/webextensions/apa_itu_webextensions/index.html create mode 100644 files/id/mozilla/add-ons/webextensions/api/browsersettings/index.html create mode 100644 files/id/mozilla/add-ons/webextensions/api/index.html create mode 100644 files/id/mozilla/add-ons/webextensions/api/notifikasi/index.html create mode 100644 files/id/mozilla/add-ons/webextensions/api/windows/createtype/index.html create mode 100644 files/id/mozilla/add-ons/webextensions/api/windows/index.html create mode 100644 files/id/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html create mode 100644 files/id/mozilla/add-ons/webextensions/content_scripts/index.html create mode 100644 files/id/mozilla/add-ons/webextensions/index.html create mode 100644 files/id/mozilla/add-ons/webextensions/your_first_webextension/index.html create mode 100644 files/id/mozilla/connect/index.html create mode 100644 files/id/mozilla/firefox/edisi_pengembang/index.html create mode 100644 files/id/mozilla/firefox/index.html create mode 100644 files/id/mozilla/firefox/privacy/index.html create mode 100644 files/id/mozilla/firefox/privacy/storage_access_policy/errors/cookieblockedtracker/index.html create mode 100644 files/id/mozilla/firefox/privacy/storage_access_policy/errors/index.html create mode 100644 files/id/mozilla/firefox/privacy/storage_access_policy/index.html create mode 100644 files/id/mozilla/firefox/releases/index.html create mode 100644 files/id/mozilla/gecko/index.html create mode 100644 files/id/mozilla/index.html create mode 100644 files/id/mozilla/localization/index.html create mode 100644 files/id/mozilla/localization/localizing_with_verbatim/index.html create mode 100644 files/id/mozilla/localization/quick_start_guide/index.html create mode 100644 files/id/mozilla/localization/quick_start_guide/qa_phase/index.html create mode 100644 files/id/mozilla/localization/web_localizability/index.html create mode 100644 files/id/mozilla/mercurial/basics/index.html create mode 100644 files/id/mozilla/mercurial/index.html create mode 100644 files/id/mozilla/persona/index.html create mode 100644 files/id/mozilla/projects/index.html create mode 100644 files/id/mozilla/projects/nss/index.html create mode 100644 files/id/mozilla/projects/rhino/index.html create mode 100644 files/id/pengembangan_web/index.html create mode 100644 files/id/sandbox/index.html create mode 100644 files/id/tools/accessibility_inspector/index.html create mode 100644 files/id/tools/debugger/index.html create mode 100644 files/id/tools/index.html create mode 100644 files/id/tools/page_inspector/how_to/index.html create mode 100644 files/id/tools/page_inspector/index.html create mode 100644 files/id/tools/remote_debugging/index.html create mode 100644 files/id/tools/webide/index.html create mode 100644 files/id/tools/webide/troubleshooting/index.html create mode 100644 files/id/web/api/abstractworker/index.html create mode 100644 files/id/web/api/api_push/index.html create mode 100644 files/id/web/api/cachestorage/index.html create mode 100644 files/id/web/api/canvas_api/index.html create mode 100644 files/id/web/api/console/index.html create mode 100644 files/id/web/api/document/createelement/index.html create mode 100644 files/id/web/api/document/index.html create mode 100644 files/id/web/api/document/links/index.html create mode 100644 files/id/web/api/document/write/index.html create mode 100644 files/id/web/api/event/currenttarget/index.html create mode 100644 files/id/web/api/event/index.html create mode 100644 files/id/web/api/event/target/index.html create mode 100644 files/id/web/api/fetch_api/index.html create mode 100644 files/id/web/api/index.html create mode 100644 files/id/web/api/mobile_connection_api/index.html create mode 100644 files/id/web/api/navigator/index.html create mode 100644 files/id/web/api/navigator/mediadevices/index.html create mode 100644 files/id/web/api/navigator/serviceworker/index.html create mode 100644 files/id/web/api/service_worker_api/index.html create mode 100644 files/id/web/api/service_worker_api/using_service_workers/index.html create mode 100644 files/id/web/api/serviceworker/index.html create mode 100644 files/id/web/api/serviceworkercontainer/index.html create mode 100644 files/id/web/api/serviceworkerregistration/index.html create mode 100644 files/id/web/api/serviceworkerregistration/pushmanager/index.html create mode 100644 files/id/web/api/speechsynthesis/index.html create mode 100644 files/id/web/api/speechsynthesis/onvoiceschanged/index.html create mode 100644 files/id/web/api/storage/index.html create mode 100644 files/id/web/api/webgl_api/index.html create mode 100644 files/id/web/api/webrtc_api/index.html create mode 100644 files/id/web/api/window/getselection/index.html create mode 100644 files/id/web/api/window/index.html create mode 100644 files/id/web/api/window/window/index.html create mode 100644 files/id/web/api/xmlhttprequest/index.html create mode 100644 files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html create mode 100644 files/id/web/css/@font-face/font-display/index.html create mode 100644 files/id/web/css/@font-face/index.html create mode 100644 files/id/web/css/_colon_active/index.html create mode 100644 files/id/web/css/background-color/index.html create mode 100644 files/id/web/css/css_box_model/index.html create mode 100644 files/id/web/css/css_box_model/introduction_to_the_css_box_model/index.html create mode 100644 files/id/web/css/css_selectors/index.html create mode 100644 files/id/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html create mode 100644 files/id/web/css/flex-direction/index.html create mode 100644 files/id/web/css/index.html create mode 100644 files/id/web/css/mask-border-width/index.html create mode 100644 files/id/web/css/referensi/index.html create mode 100644 files/id/web/css/text-transform/index.html create mode 100644 files/id/web/css/type_selectors/index.html create mode 100644 files/id/web/events/cached/index.html create mode 100644 files/id/web/events/error/index.html create mode 100644 files/id/web/events/index.html create mode 100644 files/id/web/guide/api/index.html create mode 100644 files/id/web/guide/api/webrtc/index.html create mode 100644 files/id/web/guide/css/getting_started/index.html create mode 100644 files/id/web/guide/css/media_queries/index.html create mode 100644 files/id/web/guide/grafis/index.html create mode 100644 files/id/web/guide/html/forms/index.html create mode 100644 files/id/web/guide/html/html5/index.html create mode 100644 files/id/web/guide/index.html create mode 100644 files/id/web/html/element/base/index.html create mode 100644 files/id/web/html/element/dialog/index.html create mode 100644 files/id/web/html/element/image/index.html create mode 100644 files/id/web/html/element/index.html create mode 100644 files/id/web/html/index.html create mode 100644 files/id/web/http/basics_of_http/index.html create mode 100644 files/id/web/http/gambaran/index.html create mode 100644 files/id/web/http/index.html create mode 100644 files/id/web/http/methods/get/index.html create mode 100644 files/id/web/http/methods/index.html create mode 100644 files/id/web/http/proxy_servers_and_tunneling/index.html create mode 100644 files/id/web/http/proxy_servers_and_tunneling/proxy_auto-configuration_(pac)_file/index.html create mode 100644 files/id/web/http/status/100/index.html create mode 100644 files/id/web/http/status/200/index.html create mode 100644 files/id/web/http/status/400/index.html create mode 100644 files/id/web/http/status/403/index.html create mode 100644 files/id/web/http/status/404/index.html create mode 100644 files/id/web/http/status/405/index.html create mode 100644 files/id/web/http/status/410/index.html create mode 100644 files/id/web/http/status/500/index.html create mode 100644 files/id/web/http/status/index.html create mode 100644 files/id/web/index.html create mode 100644 files/id/web/javascript/a_re-introduction_to_javascript/index.html create mode 100644 files/id/web/javascript/data_structures/index.html create mode 100644 files/id/web/javascript/index.html create mode 100644 files/id/web/javascript/inheritance_dan_prototype_chain/index.html create mode 100644 files/id/web/javascript/language_resources/index.html create mode 100644 files/id/web/javascript/memory_management/index.html create mode 100644 files/id/web/javascript/new_in_javascript/index.html create mode 100644 files/id/web/javascript/panduan/closures/index.html create mode 100644 files/id/web/javascript/panduan/index.html create mode 100644 files/id/web/javascript/panduan/loops_and_iteration/index.html create mode 100644 files/id/web/javascript/panduan/numbers_and_dates/index.html create mode 100644 files/id/web/javascript/panduan/pengenalan/index.html create mode 100644 files/id/web/javascript/panduan/tentang/index.html create mode 100644 files/id/web/javascript/panduan/values,_variables,_and_literals/index.html create mode 100644 files/id/web/javascript/panduan/working_with_objects/index.html create mode 100644 files/id/web/javascript/reference/about/index.html create mode 100644 files/id/web/javascript/reference/classes/constructor/index.html create mode 100644 files/id/web/javascript/reference/classes/extends/index.html create mode 100644 files/id/web/javascript/reference/classes/index.html create mode 100644 files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html create mode 100644 files/id/web/javascript/reference/errors/index.html create mode 100644 files/id/web/javascript/reference/errors/invalid_array_length/index.html create mode 100644 files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html create mode 100644 files/id/web/javascript/reference/errors/negative_repetition_count/index.html create mode 100644 files/id/web/javascript/reference/errors/not_a_codepoint/index.html create mode 100644 files/id/web/javascript/reference/errors/not_defined/index.html create mode 100644 files/id/web/javascript/reference/errors/property_access_denied/index.html create mode 100644 files/id/web/javascript/reference/errors/too_much_recursion/index.html create mode 100644 files/id/web/javascript/reference/functions/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/filter/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/length/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/shift/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/id/web/javascript/reference/global_objects/array/values/index.html create mode 100644 files/id/web/javascript/reference/global_objects/date/getfullyear/index.html create mode 100644 files/id/web/javascript/reference/global_objects/date/index.html create mode 100644 files/id/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/id/web/javascript/reference/global_objects/date/tojson/index.html create mode 100644 files/id/web/javascript/reference/global_objects/date/totimestring/index.html create mode 100644 files/id/web/javascript/reference/global_objects/error/index.html create mode 100644 files/id/web/javascript/reference/global_objects/error/name/index.html create mode 100644 files/id/web/javascript/reference/global_objects/function/displayname/index.html create mode 100644 files/id/web/javascript/reference/global_objects/function/index.html create mode 100644 files/id/web/javascript/reference/global_objects/function/length/index.html create mode 100644 files/id/web/javascript/reference/global_objects/function/name/index.html create mode 100644 files/id/web/javascript/reference/global_objects/function/prototype/index.html create mode 100644 files/id/web/javascript/reference/global_objects/index.html create mode 100644 files/id/web/javascript/reference/global_objects/isnan/index.html create mode 100644 files/id/web/javascript/reference/global_objects/json/index.html create mode 100644 files/id/web/javascript/reference/global_objects/json/parse/index.html create mode 100644 files/id/web/javascript/reference/global_objects/map/clear/index.html create mode 100644 files/id/web/javascript/reference/global_objects/map/delete/index.html create mode 100644 files/id/web/javascript/reference/global_objects/map/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/abs/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/e/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/floor/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/ln10/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/max/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/min/index.html create mode 100644 files/id/web/javascript/reference/global_objects/math/pow/index.html create mode 100644 files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/id/web/javascript/reference/global_objects/object/index.html create mode 100644 files/id/web/javascript/reference/global_objects/object/keys/index.html create mode 100644 files/id/web/javascript/reference/global_objects/object/preventextensions/index.html create mode 100644 files/id/web/javascript/reference/global_objects/promise/catch/index.html create mode 100644 files/id/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/id/web/javascript/reference/global_objects/promise/reject/index.html create mode 100644 files/id/web/javascript/reference/global_objects/promise/resolve/index.html create mode 100644 files/id/web/javascript/reference/global_objects/promise/then/index.html create mode 100644 files/id/web/javascript/reference/global_objects/regexp/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/concat/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/length/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/link/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/purwarupa/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/split/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/tolowercase/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/tostring/index.html create mode 100644 files/id/web/javascript/reference/global_objects/string/touppercase/index.html create mode 100644 files/id/web/javascript/reference/global_objects/typedarray/index.html create mode 100644 files/id/web/javascript/reference/global_objects/typedarray/join/index.html create mode 100644 files/id/web/javascript/reference/index.html create mode 100644 files/id/web/javascript/reference/lexical_grammar/index.html create mode 100644 files/id/web/javascript/reference/operators/conditional_operator/index.html create mode 100644 files/id/web/javascript/reference/operators/fungsi/index.html create mode 100644 files/id/web/javascript/reference/operators/index.html create mode 100644 files/id/web/javascript/reference/operators/yield/index.html create mode 100644 files/id/web/javascript/reference/statements/class/index.html create mode 100644 files/id/web/javascript/reference/statements/do...while/index.html create mode 100644 files/id/web/javascript/reference/statements/empty/index.html create mode 100644 files/id/web/javascript/reference/statements/export/index.html create mode 100644 files/id/web/javascript/reference/statements/for...in/index.html create mode 100644 files/id/web/javascript/reference/statements/fungsi/index.html create mode 100644 files/id/web/javascript/reference/statements/index.html create mode 100644 files/id/web/javascript/sekilas_teknologi_javascript/index.html create mode 100644 files/id/web/mathml/element/index.html create mode 100644 files/id/web/mathml/index.html create mode 100644 files/id/web/reference/api/index.html create mode 100644 files/id/web/reference/index.html create mode 100644 files/id/web/security/index.html create mode 100644 files/id/web/web_components/index.html create mode 100644 files/id/zones/index.html (limited to 'files/id') diff --git a/files/id/_redirects.txt b/files/id/_redirects.txt new file mode 100644 index 0000000000..809fc34c73 --- /dev/null +++ b/files/id/_redirects.txt @@ -0,0 +1,26 @@ +# FROM-URL TO-URL +/id/docs/HTML /id/docs/Web/HTML +/id/docs/JavaScript /id/docs/Web/JavaScript +/id/docs/JavaScript/Getting_Started /id/docs/Web/JavaScript/Getting_Started +/id/docs/JavaScript/Panduan /id/docs/Web/JavaScript/Panduan +/id/docs/JavaScript/Pengenalan_JS /id/docs/Web/JavaScript/Getting_Started +/id/docs/JavaScript/Reference /id/docs/Web/JavaScript/Reference +/id/docs/JavaScript/Reference/About /id/docs/Web/JavaScript/Reference/About +/id/docs/JavaScript/Reference/Global_Objects /id/docs/Web/JavaScript/Reference/Global_Objects +/id/docs/JavaScript/Reference/Global_Objects/Math /id/docs/Web/JavaScript/Reference/Global_Objects/Math +/id/docs/JavaScript/Reference/Global_Objects/Math/pow /id/docs/Web/JavaScript/Reference/Global_Objects/Math/pow +/id/docs/JavaScript/Reference/Statements /id/docs/Web/JavaScript/Reference/Statements +/id/docs/JavaScript/Reference/Statements/block /id/docs/Web/JavaScript/Reference/Statements/block +/id/docs/Learn/CSS/Introduction_to_CSS /en-US/docs/Learn/CSS/First_steps +/id/docs/Learn/CSS/Introduction_to_CSS/Box_model /en-US/docs/Learn/CSS/Building_blocks/The_box_model +/id/docs/MDN/Contribute/Content /id/docs/MDN/Guidelines +/id/docs/MDN/Contribute/Content/Layout /id/docs/MDN/Guidelines/Layout +/id/docs/MDN/Contribute/Content/Writing_style_guide /id/docs/MDN/Guidelines/Writing_style_guide +/id/docs/MDN/Langkah_Awal /id/docs/MDN/Contribute/Getting_started +/id/docs/Web/Guide/CSS /id/docs/Learn/CSS +/id/docs/Web/Guide/HTML /id/docs/Learn/HTML +/id/docs/Web/Guide/HTML/Pengenalan /id/docs/Learn/HTML/Introduction_to_HTML +/id/docs/Web/JavaScript/Reference/Methods_Index /id/docs/Web/JavaScript/Reference +/id/docs/Web/JavaScript/Reference/Properties_Index /id/docs/Web/JavaScript/Reference +/id/docs/Web/WebGL /id/docs/Web/API/WebGL_API +/id/docs/en /en-US/ diff --git a/files/id/_wikihistory.json b/files/id/_wikihistory.json new file mode 100644 index 0000000000..c7e8317627 --- /dev/null +++ b/files/id/_wikihistory.json @@ -0,0 +1,2171 @@ +{ + "Developer_Guide": { + "modified": "2019-03-23T23:27:41.297Z", + "contributors": [ + "bskari" + ] + }, + "Developer_Guide/Virtual_ARM_di_Lingkungan_Linux": { + "modified": "2019-03-23T23:27:45.214Z", + "contributors": [ + "ariestiyansyah" + ] + }, + "Games": { + "modified": "2020-07-23T02:23:56.130Z", + "contributors": [ + "SphinxKnight", + "wbamberg", + "firmanwyd", + "Alivanza", + "Dataware" + ] + }, + "Games/Publishing_games": { + "modified": "2020-07-23T02:24:59.333Z", + "contributors": [ + "wbamberg" + ] + }, + "Games/Publishing_games/Game_promotion": { + "modified": "2020-07-23T02:28:02.464Z", + "contributors": [ + "SphinxKnight" + ] + }, + "Games/Techniques": { + "modified": "2019-04-21T11:17:49.913Z", + "contributors": [ + "wbamberg" + ] + }, + "Glossary": { + "modified": "2020-10-07T11:10:52.018Z", + "contributors": [ + "peterbe", + "SphinxKnight", + "wbamberg", + "bekti", + "Jeremie" + ] + }, + "Glossary/404": { + "modified": "2019-03-23T22:32:14.780Z", + "contributors": [ + "bekti" + ] + }, + "Glossary/AJAX": { + "modified": "2019-03-23T22:19:41.769Z", + "contributors": [ + "galuhsahid", + "yahyaman", + "bekti" + ] + }, + "Glossary/API": { + "modified": "2019-03-23T22:32:10.841Z", + "contributors": [ + "bekti" + ] + }, + "Glossary/Algoritma": { + "modified": "2019-03-23T22:41:10.845Z", + "contributors": [ + "yayansupiana", + "astrominion", + "agungprasetyosakti" + ] + }, + "Glossary/Asynchronous": { + "modified": "2019-03-23T22:29:53.061Z", + "contributors": [ + "adoel90" + ] + }, + "Glossary/CSS": { + "modified": "2019-03-23T22:19:46.534Z", + "contributors": [ + "galuhsahid", + "bekti" + ] + }, + "Glossary/HTML": { + "modified": "2019-03-18T21:44:41.786Z", + "contributors": [ + "galuhsahid" + ] + }, + "Glossary/HTTP": { + "modified": "2019-03-23T22:19:40.425Z", + "contributors": [ + "galuhsahid", + "bekti" + ] + }, + "Glossary/Identifier": { + "modified": "2019-03-23T22:10:10.171Z", + "contributors": [ + "sori-goklas-hutagalung" + ] + }, + "Glossary/JSON": { + "modified": "2019-03-18T21:44:43.807Z", + "contributors": [ + "galuhsahid" + ] + }, + "Glossary/JavaScript": { + "modified": "2019-03-23T22:19:47.350Z", + "contributors": [ + "galuhsahid", + "bekti" + ] + }, + "Glossary/Method": { + "modified": "2019-03-23T22:32:21.055Z", + "contributors": [ + "bekti" + ] + }, + "Glossary/Null": { + "modified": "2019-03-23T22:18:02.352Z", + "contributors": [ + "dinugr" + ] + }, + "Glossary/Primitive": { + "modified": "2019-03-23T22:09:59.397Z", + "contributors": [ + "sori-goklas-hutagalung" + ] + }, + "Glossary/Python": { + "modified": "2019-03-18T21:42:33.944Z", + "contributors": [ + "adityaharist19" + ] + }, + "Glossary/SEO": { + "modified": "2019-09-22T13:59:47.933Z", + "contributors": [ + "duduindo", + "rizkysaskiaputra" + ] + }, + "Glossary/SVG": { + "modified": "2019-03-23T22:19:38.489Z", + "contributors": [ + "galuhsahid", + "bekti" + ] + }, + "Glossary/Statement": { + "modified": "2019-03-23T22:09:58.650Z", + "contributors": [ + "sori-goklas-hutagalung" + ] + }, + "Glossary/URL": { + "modified": "2019-03-23T22:19:45.495Z", + "contributors": [ + "galuhsahid", + "bekti" + ] + }, + "Glossary/Variable": { + "modified": "2019-03-23T22:09:46.873Z", + "contributors": [ + "bekti" + ] + }, + "Glossary/XML": { + "modified": "2019-03-23T22:19:46.777Z", + "contributors": [ + "galuhsahid", + "bekti" + ] + }, + "Glossary/property": { + "modified": "2019-03-23T22:32:18.314Z", + "contributors": [ + "bekti" + ] + }, + "Learn": { + "modified": "2020-08-08T15:57:34.011Z", + "contributors": [ + "excelrtuhin", + "lisa.angraini.la", + "setyadi", + "Transamunos", + "SphinxKnight", + "svarlamov", + "padila50", + "milhamj", + "bekti", + "miftahafina", + "bang_eko", + "Andrew_Pfeiffer" + ] + }, + "Learn/Accessibility": { + "modified": "2020-07-16T22:39:57.425Z", + "contributors": [ + "zahrulseptian295" + ] + }, + "Learn/CSS": { + "modified": "2020-07-16T22:25:34.322Z", + "contributors": [ + "sideshowbarker" + ] + }, + "Learn/Common_questions": { + "modified": "2020-07-16T22:35:24.163Z", + "contributors": [ + "ashymee", + "dennisblight", + "stephaniehobson" + ] + }, + "Learn/Common_questions/Bagaimana_cara_kerja_Internet": { + "modified": "2020-07-16T22:35:36.880Z", + "contributors": [ + "xenavrt", + "dennisblight" + ] + }, + "Learn/Common_questions/Berfikir_sebelum_membuat_kode": { + "modified": "2020-07-16T22:35:34.339Z", + "contributors": [ + "wahyuakbarwibowo" + ] + }, + "Learn/Common_questions/Pages_sites_servers_and_search_engines": { + "modified": "2020-07-16T22:35:39.876Z", + "contributors": [ + "ilhamm11194011" + ] + }, + "Learn/Common_questions/set_up_a_local_testing_server": { + "modified": "2020-07-16T22:35:52.964Z", + "contributors": [ + "dennisblight" + ] + }, + "Learn/Getting_started_with_the_web": { + "modified": "2020-07-16T22:33:53.018Z", + "contributors": [ + "Transamunos", + "thickkoezz", + "dennisblight", + "galuhsahid", + "bekti", + "miftahafina", + "adeyahya", + "chrisdavidmills" + ] + }, + "Learn/Getting_started_with_the_web/Akan_terlihat_seperti_apa_website_anda": { + "modified": "2020-07-16T22:34:16.825Z", + "contributors": [ + "thickkoezz", + "bekti", + "dovjay", + "yayansupiana" + ] + }, + "Learn/Getting_started_with_the_web/CSS_basics": { + "modified": "2020-07-16T22:34:58.859Z", + "contributors": [ + "thickkoezz", + "galuhsahid" + ] + }, + "Learn/Getting_started_with_the_web/HTML_basics": { + "modified": "2020-07-16T22:34:45.914Z", + "contributors": [ + "thickkoezz", + "adangwihanda", + "yasminzy", + "oktafh", + "bangyasri" + ] + }, + "Learn/Getting_started_with_the_web/How_the_Web_works": { + "modified": "2020-07-16T22:34:00.538Z", + "contributors": [ + "dennisblight", + "bekti" + ] + }, + "Learn/Getting_started_with_the_web/Installing_basic_software": { + "modified": "2020-07-16T22:34:08.020Z", + "contributors": [ + "Transamunos", + "thickkoezz", + "dennisblight", + "bekti", + "yayansupiana", + "agus_nurcholis" + ] + }, + "Learn/Getting_started_with_the_web/JavaScript_basics": { + "modified": "2020-07-16T22:35:10.743Z", + "contributors": [ + "willi-dev", + "MichaelSipayung", + "bekti", + "Fidelstu", + "miftahafina", + "adeyahya" + ] + }, + "Learn/Getting_started_with_the_web/Mengelola_file": { + "modified": "2020-07-16T22:34:33.806Z", + "contributors": [ + "thickkoezz", + "galuhsahid", + "BPiVcarD", + "vdanny" + ] + }, + "Learn/Getting_started_with_the_web/Publishing_your_website": { + "modified": "2020-07-16T22:34:25.723Z", + "contributors": [ + "bekti" + ] + }, + "Learn/HTML": { + "modified": "2020-07-16T22:22:18.743Z", + "contributors": [ + "bayuYudhaSaputra", + "fikrirazor" + ] + }, + "Learn/HTML/Howto": { + "modified": "2020-08-21T10:36:52.641Z", + "contributors": [ + "ikramwadudu99" + ] + }, + "Learn/HTML/Multimedia_dan_embedding": { + "modified": "2020-07-16T22:24:25.764Z", + "contributors": [ + "SphinxKnight", + "putrapuices", + "thickkoezz" + ] + }, + "Learn/HTML/Multimedia_dan_embedding/Adding_vector_graphics_to_the_Web": { + "modified": "2020-07-16T22:24:40.529Z", + "contributors": [ + "mujahid-it" + ] + }, + "Learn/HTML/Multimedia_dan_embedding/Responsive_images": { + "modified": "2020-07-16T22:24:34.275Z", + "contributors": [ + "mujahid-it" + ] + }, + "Learn/HTML/Pengenalan_HTML": { + "modified": "2020-07-30T01:00:05.720Z", + "contributors": [ + "setyadi", + "Zen-Akira", + "thickkoezz", + "ariaenggar" + ] + }, + "Learn/HTML/Pengenalan_HTML/Document_and_website_structure": { + "modified": "2020-07-16T22:24:04.997Z", + "contributors": [ + "mujahid-it" + ] + }, + "Learn/HTML/Pengenalan_HTML/HTML_text_fundamentals": { + "modified": "2020-07-16T22:23:32.925Z", + "contributors": [ + "Transamunos" + ] + }, + "Learn/HTML/Pengenalan_HTML/Structuring_a_page_of_content": { + "modified": "2020-07-16T22:24:19.411Z", + "contributors": [ + "mujahid-it" + ] + }, + "Learn/HTML/Tabel": { + "modified": "2020-07-16T22:25:12.167Z", + "contributors": [ + "jatmikaekachandra" + ] + }, + "Learn/How_to_contribute": { + "modified": "2020-07-16T22:33:44.062Z", + "contributors": [ + "SphinxKnight", + "bekti", + "ariestiyansyah" + ] + }, + "Learn/JavaScript": { + "modified": "2020-07-16T22:29:39.927Z", + "contributors": [ + "triashand", + "ariebrainware", + "bekti", + "miftahafina" + ] + }, + "Learn/JavaScript/Building_blocks": { + "modified": "2020-11-07T05:27:42.212Z", + "contributors": [ + "cxvq", + "Fidelstu" + ] + }, + "Learn/JavaScript/Client-side_web_APIs": { + "modified": "2020-07-16T22:32:39.540Z", + "contributors": [ + "awim" + ] + }, + "Learn/JavaScript/Client-side_web_APIs/Introduction": { + "modified": "2020-07-16T22:32:45.404Z", + "contributors": [ + "rizkypjt" + ] + }, + "Learn/JavaScript/First_steps": { + "modified": "2020-11-09T23:42:16.586Z", + "contributors": [ + "inbox.jen96", + "bekti" + ] + }, + "Learn/JavaScript/First_steps/What_is_JavaScript": { + "modified": "2020-07-16T22:30:08.653Z", + "contributors": [ + "ajiprio01", + "windykurniawan-windcode" + ] + }, + "Learn/JavaScript/Objects": { + "modified": "2020-07-16T22:31:50.305Z", + "contributors": [ + "thickkoezz", + "Fidelstu" + ] + }, + "Learn/JavaScript/Objects/Dasar-dasar": { + "modified": "2020-07-16T22:31:59.183Z", + "contributors": [ + "indrayoganata" + ] + }, + "Learn/Server-side": { + "modified": "2020-07-16T22:35:58.563Z", + "contributors": [ + "chrisdavidmills" + ] + }, + "Learn/Server-side/Django": { + "modified": "2020-09-27T09:04:00.240Z", + "contributors": [ + "MuhamadAzizi", + "AgungWiyono", + "aps2201", + "fikrirazor" + ] + }, + "Learn/Server-side/Django/Tutorial_local_library_website": { + "modified": "2020-09-27T09:52:56.557Z", + "contributors": [ + "MuhamadAzizi" + ] + }, + "Learn/Server-side/Django/development_environment": { + "modified": "2020-09-27T09:24:51.296Z", + "contributors": [ + "MuhamadAzizi", + "mujahid-it" + ] + }, + "Learn/Server-side/First_steps": { + "modified": "2020-07-16T22:36:09.052Z", + "contributors": [ + "ferdian89" + ] + }, + "Learn/Web_Mechanics": { + "modified": "2020-07-16T22:22:13.418Z", + "contributors": [ + "miftahafina" + ] + }, + "MDN": { + "modified": "2020-08-29T05:39:32.291Z", + "contributors": [ + "excelrtuhin", + "jswisher", + "SphinxKnight", + "wbamberg", + "bekti", + "Sheppy" + ] + }, + "MDN/About": { + "modified": "2020-08-09T11:25:04.711Z", + "contributors": [ + "harikun" + ] + }, + "MDN/Contribute": { + "modified": "2019-01-16T19:12:55.469Z", + "contributors": [ + "wbamberg", + "bekti", + "ariestiyansyah", + "Sheppy" + ] + }, + "MDN/Contribute/Feedback": { + "modified": "2020-09-30T17:51:12.443Z", + "contributors": [ + "chrisdavidmills", + "SphinxKnight", + "thickkoezz", + "wbamberg", + "chorie", + "viankakrisna", + "afishop", + "jswisher", + "pieteru_insekai" + ] + }, + "MDN/Contribute/Getting_started": { + "modified": "2020-09-30T17:12:29.554Z", + "contributors": [ + "chrisdavidmills", + "SphinxKnight", + "excelrtuhin", + "kangsantripaud", + "ISO", + "devmio", + "agenbaccaratnet", + "wbamberg", + "nsiregar", + "chorie", + "arifpedia", + "firmanwyd", + "bekti", + "bayuah", + "Mohdsalleh", + "Bobypurnomo", + "rio.putra", + "helloeny" + ] + }, + "MDN/Contribute/Howto": { + "modified": "2019-01-16T19:12:51.064Z", + "contributors": [ + "wbamberg", + "bekti", + "Sheppy" + ] + }, + "MDN/Contribute/Howto/Create_an_MDN_account": { + "modified": "2019-03-23T22:38:48.748Z", + "contributors": [ + "wbamberg", + "padila50", + "firmanwyd", + "taqiyyuki02", + "Lukman04" + ] + }, + "MDN/Contribute/Howto/Do_a_technical_review": { + "modified": "2019-03-23T22:32:05.940Z", + "contributors": [ + "wbamberg", + "heasanking" + ] + }, + "MDN/Contribute/Howto/Do_an_editorial_review": { + "modified": "2019-03-23T22:31:28.587Z", + "contributors": [ + "wbamberg", + "ElangSBP", + "bekti", + "Pieteru" + ] + }, + "MDN/Contribute/Howto/Set_the_summary_for_a_page": { + "modified": "2019-01-16T19:13:18.495Z", + "contributors": [ + "wbamberg", + "zekaras" + ] + }, + "MDN/Contribute/Howto/Tag": { + "modified": "2019-03-23T23:04:03.858Z", + "contributors": [ + "wbamberg", + "yayasl" + ] + }, + "MDN/Contribute/Processes": { + "modified": "2019-03-23T22:33:46.372Z", + "contributors": [ + "ignchristian", + "wbamberg", + "jswisher" + ] + }, + "MDN/Contribute/Tugas": { + "modified": "2019-01-16T19:13:42.819Z", + "contributors": [ + "wbamberg", + "firmanwyd", + "Cr7Pramana" + ] + }, + "MDN/Guidelines": { + "modified": "2020-09-30T15:29:57.815Z", + "contributors": [ + "chrisdavidmills", + "wbamberg", + "bekti", + "Sheppy" + ] + }, + "MDN/Guidelines/Writing_style_guide": { + "modified": "2020-09-30T15:29:58.831Z", + "contributors": [ + "chrisdavidmills", + "alvisolikah0507" + ] + }, + "MDN/Komunitas": { + "modified": "2019-05-29T21:20:10.743Z", + "contributors": [ + "alattalatta", + "KLIWONJagung", + "wbamberg", + "Makarim", + "firmanwyd", + "padila50", + "bekti", + "eriskatp" + ] + }, + "MDN/Komunitas/Conversations": { + "modified": "2019-03-23T22:41:40.315Z", + "contributors": [ + "wbamberg", + "jswisher", + "randiproska" + ] + }, + "MDN/User_guide": { + "modified": "2020-12-07T17:30:15.270Z", + "contributors": [ + "wbamberg", + "Sheppy" + ] + }, + "MDN/User_guide/Menghapus_halaman": { + "modified": "2019-01-16T18:55:32.659Z", + "contributors": [ + "wbamberg", + "helloeny" + ] + }, + "Mozilla": { + "modified": "2019-03-23T23:28:31.556Z", + "contributors": [ + "wim449", + "Sheppy" + ] + }, + "Mozilla/Add-ons": { + "modified": "2019-09-09T13:11:45.968Z", + "contributors": [ + "SphinxKnight", + "bekti", + "soulast", + "LukmanTambose", + "pieteru_insekai", + "novita" + ] + }, + "Mozilla/Add-ons/WebExtensions": { + "modified": "2019-07-03T08:48:34.929Z", + "contributors": [ + "SphinxKnight", + "herliansyah", + "fesuydev", + "wbamberg" + ] + }, + "Mozilla/Add-ons/WebExtensions/API": { + "modified": "2019-11-26T22:19:27.565Z", + "contributors": [ + "wbamberg" + ] + }, + "Mozilla/Add-ons/WebExtensions/API/browserSettings": { + "modified": "2020-10-15T22:32:28.909Z", + "contributors": [ + "SphinxKnight", + "joelinformaticien01", + "didikpramono" + ] + }, + "Mozilla/Add-ons/WebExtensions/API/notifikasi": { + "modified": "2020-10-15T22:05:36.197Z", + "contributors": [ + "asiongtobing", + "wbamberg", + "Azhe403" + ] + }, + "Mozilla/Add-ons/WebExtensions/API/windows": { + "modified": "2020-10-15T21:51:41.708Z", + "contributors": [ + "wbamberg", + "abbycar" + ] + }, + "Mozilla/Add-ons/WebExtensions/API/windows/CreateType": { + "modified": "2020-10-15T21:51:40.999Z", + "contributors": [ + "wbamberg", + "fesuydev" + ] + }, + "Mozilla/Add-ons/WebExtensions/Apa_Itu_WebExtensions": { + "modified": "2019-03-18T21:06:29.401Z", + "contributors": [ + "fesuydev" + ] + }, + "Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs": { + "modified": "2020-10-15T20:55:16.114Z", + "contributors": [ + "didikpramono" + ] + }, + "Mozilla/Add-ons/WebExtensions/Content_scripts": { + "modified": "2020-07-10T14:58:49.988Z", + "contributors": [ + "prajahutapea1980" + ] + }, + "Mozilla/Add-ons/WebExtensions/Your_first_WebExtension": { + "modified": "2019-03-18T21:06:21.389Z", + "contributors": [ + "fesuydev" + ] + }, + "Mozilla/Firefox": { + "modified": "2019-09-10T14:58:31.117Z", + "contributors": [ + "SphinxKnight", + "wbamberg", + "chorie", + "bekti", + "haris_haki89", + "StarGible" + ] + }, + "Mozilla/Firefox/Releases": { + "modified": "2019-03-23T23:09:29.710Z", + "contributors": [ + "wbamberg", + "bekti", + "ziyunfei" + ] + }, + "Pengembangan_Web": { + "modified": "2019-03-23T22:51:52.244Z", + "contributors": [ + "rahmatsubekti" + ] + }, + "Tools": { + "modified": "2020-07-16T22:44:15.262Z", + "contributors": [ + "SphinxKnight", + "wbamberg", + "srwicak", + "bekti", + "paleutoh", + "Rawoyo", + "agungprasetyosakti", + "abdulrahmandwn@gmail.com", + "bg17me", + "romifzld@gmail.com", + "Rusli88", + "redkhila", + "Almizajuhazamjabila", + "Dera_kom", + "InyoezzRusty", + "dodo_tgrcity" + ] + }, + "Tools/Accessibility_inspector": { + "modified": "2020-07-16T22:36:39.804Z", + "contributors": [ + "BrilliantFikri" + ] + }, + "Tools/Debugger": { + "modified": "2020-07-16T22:35:04.572Z", + "contributors": [ + "wbamberg", + "fscholz", + "trevorh", + "aslam" + ] + }, + "Tools/Page_Inspector": { + "modified": "2020-07-16T22:34:27.903Z", + "contributors": [ + "wbamberg", + "bekti" + ] + }, + "Tools/Page_Inspector/How_to": { + "modified": "2020-07-16T22:34:31.302Z" + }, + "Tools/Remote_Debugging": { + "modified": "2020-07-16T22:35:37.379Z", + "contributors": [ + "wbamberg", + "fahrizalsaler", + "Rizal712", + "zemaryal" + ] + }, + "Web": { + "modified": "2020-08-01T17:04:48.178Z", + "contributors": [ + "Transamunos", + "padila50", + "firmanwyd", + "TIYAN", + "Pieteru", + "bekti", + "nochis", + "srifqi", + "enda34", + "jefriebdn", + "groovecoder", + "Dhinicarnetta", + "pieteru_insekai", + "Jan.Ruzicka" + ] + }, + "Web/API": { + "modified": "2019-03-23T23:29:04.875Z", + "contributors": [ + "teoli", + "Rodin", + "ethertank", + "Sheppy", + "pieteru_insekai" + ] + }, + "Web/API/API_Push": { + "modified": "2019-03-23T22:39:12.627Z", + "contributors": [ + "bayuah" + ] + }, + "Web/API/AbstractWorker": { + "modified": "2019-03-23T22:32:36.681Z", + "contributors": [ + "bekti" + ] + }, + "Web/API/CacheStorage": { + "modified": "2020-10-15T22:30:28.579Z", + "contributors": [ + "AprilSylph" + ] + }, + "Web/API/Canvas_API": { + "modified": "2020-04-30T13:42:37.733Z", + "contributors": [ + "Thor-x86", + "her82man" + ] + }, + "Web/API/Console": { + "modified": "2019-03-23T22:06:01.155Z", + "contributors": [ + "chaosrock" + ] + }, + "Web/API/Document": { + "modified": "2019-03-23T22:31:44.953Z", + "contributors": [ + "teoli" + ] + }, + "Web/API/Document/createElement": { + "modified": "2019-03-18T21:40:57.940Z", + "contributors": [ + "srwicak" + ] + }, + "Web/API/Document/links": { + "modified": "2019-03-23T22:31:46.942Z", + "contributors": [ + "bekti" + ] + }, + "Web/API/Document/write": { + "modified": "2019-03-23T22:31:16.420Z", + "contributors": [ + "bekti" + ] + }, + "Web/API/Event": { + "modified": "2019-03-23T22:34:07.571Z", + "contributors": [ + "bekti" + ] + }, + "Web/API/Event/currentTarget": { + "modified": "2019-03-23T22:02:04.056Z", + "contributors": [ + "agengdp" + ] + }, + "Web/API/Event/target": { + "modified": "2020-10-15T22:29:42.203Z", + "contributors": [ + "mujahid-it" + ] + }, + "Web/API/Fetch_API": { + "modified": "2020-10-15T22:15:10.618Z", + "contributors": [ + "arifirmansyah" + ] + }, + "Web/API/Navigator": { + "modified": "2019-03-23T22:33:55.930Z", + "contributors": [ + "bekti", + "jpmedley" + ] + }, + "Web/API/Navigator/mediaDevices": { + "modified": "2020-10-15T22:35:18.495Z", + "contributors": [ + "ajid2" + ] + }, + "Web/API/Navigator/serviceWorker": { + "modified": "2019-03-23T22:33:57.198Z", + "contributors": [ + "bekti" + ] + }, + "Web/API/ServiceWorker": { + "modified": "2019-03-23T22:33:58.500Z", + "contributors": [ + "bekti" + ] + }, + "Web/API/ServiceWorkerContainer": { + "modified": "2020-10-15T22:30:32.905Z", + "contributors": [ + "Wind1808" + ] + }, + "Web/API/ServiceWorkerRegistration": { + "modified": "2019-03-23T22:24:55.454Z", + "contributors": [ + "lostsource" + ] + }, + "Web/API/ServiceWorkerRegistration/pushManager": { + "modified": "2019-03-23T22:25:01.542Z", + "contributors": [ + "bekti" + ] + }, + "Web/API/Service_Worker_API": { + "modified": "2019-03-23T22:34:03.819Z", + "contributors": [ + "chrisdavidmills" + ] + }, + "Web/API/Service_Worker_API/Using_Service_Workers": { + "modified": "2019-03-23T22:34:11.113Z", + "contributors": [ + "bekti" + ] + }, + "Web/API/SpeechSynthesis": { + "modified": "2020-10-15T22:26:55.754Z" + }, + "Web/API/SpeechSynthesis/onvoiceschanged": { + "modified": "2020-10-15T22:28:05.104Z", + "contributors": [ + "azaddogan0688" + ] + }, + "Web/API/Storage": { + "modified": "2020-10-15T22:14:31.365Z", + "contributors": [ + "daengbaco" + ] + }, + "Web/API/WebGL_API": { + "modified": "2020-04-29T19:32:33.970Z", + "contributors": [ + "bekti", + "fscholz", + "bassam", + "agungprasetyosakti" + ] + }, + "Web/API/WebRTC_API": { + "modified": "2019-03-23T22:16:11.428Z", + "contributors": [ + "fitra" + ] + }, + "Web/API/Window": { + "modified": "2019-03-23T22:04:16.389Z", + "contributors": [ + "jpmedley" + ] + }, + "Web/API/Window/getSelection": { + "modified": "2020-10-15T22:25:06.790Z", + "contributors": [ + "fsodic" + ] + }, + "Web/API/Window/window": { + "modified": "2019-03-23T22:04:14.512Z", + "contributors": [ + "Makarim" + ] + }, + "Web/API/XMLHttpRequest": { + "modified": "2020-10-15T22:29:42.073Z", + "contributors": [ + "mconley" + ] + }, + "Web/API/XMLHttpRequest/Using_XMLHttpRequest": { + "modified": "2020-10-15T22:29:44.031Z", + "contributors": [ + "cupsmaniak" + ] + }, + "Web/CSS": { + "modified": "2020-10-11T06:34:07.941Z", + "contributors": [ + "liimep", + "SphinxKnight", + "okabrionz", + "bekti", + "pieteru_insekai" + ] + }, + "Web/CSS/:active": { + "modified": "2019-03-23T22:39:29.350Z", + "contributors": [ + "fscholz", + "dedy_serang" + ] + }, + "Web/CSS/@font-face": { + "modified": "2020-10-15T22:29:43.073Z", + "contributors": [ + "Speich" + ] + }, + "Web/CSS/@font-face/font-display": { + "modified": "2020-10-15T22:29:40.410Z", + "contributors": [ + "yhogalampung" + ] + }, + "Web/CSS/CSS_Box_Model": { + "modified": "2019-11-12T01:36:35.726Z" + }, + "Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model": { + "modified": "2020-04-14T11:30:15.446Z", + "contributors": [ + "AndrEndru" + ] + }, + "Web/CSS/CSS_Selectors": { + "modified": "2019-03-23T22:39:36.340Z", + "contributors": [ + "dedy_serang", + "Sebastianz" + ] + }, + "Web/CSS/CSS_Selectors/Using_the_:target_pseudo-class_in_selectors": { + "modified": "2019-03-23T22:39:39.136Z", + "contributors": [ + "dedy_serang" + ] + }, + "Web/CSS/Type_selectors": { + "modified": "2019-03-23T22:39:33.121Z", + "contributors": [ + "dedy_serang" + ] + }, + "Web/CSS/background-color": { + "modified": "2020-10-15T22:13:54.838Z", + "contributors": [ + "Fairsu" + ] + }, + "Web/CSS/flex-direction": { + "modified": "2020-10-15T22:33:04.876Z", + "contributors": [ + "tegar97" + ] + }, + "Web/CSS/mask-border-width": { + "modified": "2020-11-28T00:13:02.295Z", + "contributors": [ + "alifudinashfa7" + ] + }, + "Web/CSS/referensi": { + "modified": "2020-10-11T06:52:29.728Z", + "contributors": [ + "liimep" + ] + }, + "Web/CSS/text-transform": { + "modified": "2020-10-15T22:00:17.057Z", + "contributors": [ + "fowlplay" + ] + }, + "Web/Events": { + "modified": "2019-04-30T14:00:32.443Z", + "contributors": [ + "wbamberg", + "bep" + ] + }, + "Web/Events/error": { + "modified": "2019-03-23T22:33:54.573Z", + "contributors": [ + "fscholz", + "bekti" + ] + }, + "Web/Guide": { + "modified": "2019-03-23T23:29:05.952Z", + "contributors": [ + "firmanwyd", + "bekti", + "rahmatsubekti", + "ethertank", + "Sheppy" + ] + }, + "Web/Guide/API": { + "modified": "2019-09-11T09:41:53.158Z", + "contributors": [ + "SphinxKnight", + "steffix.h2" + ] + }, + "Web/Guide/API/WebRTC": { + "modified": "2019-03-23T22:55:51.386Z", + "contributors": [ + "fitra", + "yuan8" + ] + }, + "Web/Guide/CSS/Getting_started": { + "modified": "2019-03-23T23:14:57.144Z", + "contributors": [ + "mahfudhi" + ] + }, + "Web/Guide/CSS/Media_queries": { + "modified": "2019-03-23T23:17:04.703Z", + "contributors": [ + "Sebastianz", + "mrstork", + "malayaleecoder", + "dpitaloka" + ] + }, + "Web/Guide/Grafis": { + "modified": "2019-03-23T23:29:12.829Z", + "contributors": [ + "firmanwyd", + "bekti", + "pieteru_insekai" + ] + }, + "Web/Guide/HTML/Forms": { + "modified": "2020-07-16T22:20:57.894Z", + "contributors": [ + "ariona_rian" + ] + }, + "Web/Guide/HTML/HTML5": { + "modified": "2019-04-27T02:10:19.507Z", + "contributors": [ + "eragone394", + "teoli", + "andi-sholihin", + "dac" + ] + }, + "Web/HTML": { + "modified": "2020-03-30T02:20:45.667Z", + "contributors": [ + "SphinxKnight", + "teriray23", + "Transamunos", + "GhalibPutra879", + "globalnet", + "Pieteru", + "bekti", + "pieteru_insekai", + "noorAddianna" + ] + }, + "Web/HTML/Element": { + "modified": "2020-05-04T02:43:50.266Z", + "contributors": [ + "SphinxKnight", + "ISO", + "Transamunos", + "bekti", + "kscarfone" + ] + }, + "Web/HTML/Element/base": { + "modified": "2019-09-22T14:03:48.366Z", + "contributors": [ + "duduindo", + "Ariansnirwana" + ] + }, + "Web/HTML/Element/dialog": { + "modified": "2020-10-15T22:00:58.630Z", + "contributors": [ + "jpmakangiras" + ] + }, + "Web/HTML/Element/image": { + "modified": "2019-03-23T22:11:52.537Z", + "contributors": [ + "Fidelstu" + ] + }, + "Web/HTTP": { + "modified": "2019-03-23T22:10:11.130Z", + "contributors": [ + "srwicak", + "Joe_Brown", + "Jasakontraktor", + "fscholz" + ] + }, + "Web/HTTP/Basics_of_HTTP": { + "modified": "2020-07-05T03:38:29.103Z", + "contributors": [ + "setyadi", + "mfuji09" + ] + }, + "Web/HTTP/Gambaran": { + "modified": "2020-11-29T00:41:21.794Z", + "contributors": [ + "mzgndrg", + "bcnight" + ] + }, + "Web/HTTP/Methods": { + "modified": "2020-10-15T21:55:31.625Z", + "contributors": [ + "bekti", + "fscholz" + ] + }, + "Web/HTTP/Methods/GET": { + "modified": "2020-10-15T21:55:31.974Z", + "contributors": [ + "bekti" + ] + }, + "Web/HTTP/Proxy_servers_and_tunneling": { + "modified": "2020-10-19T13:06:42.068Z", + "contributors": [ + "jwerre" + ] + }, + "Web/HTTP/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_(PAC)_file": { + "modified": "2020-10-20T02:03:59.798Z", + "contributors": [ + "SphinxKnight", + "worabaiyan" + ] + }, + "Web/HTTP/Status": { + "modified": "2020-07-11T00:04:04.381Z", + "contributors": [ + "tegar97", + "dyankastutara", + "M-Husein" + ] + }, + "Web/HTTP/Status/100": { + "modified": "2020-10-15T21:51:44.217Z", + "contributors": [ + "bekti" + ] + }, + "Web/HTTP/Status/200": { + "modified": "2020-10-15T21:55:30.356Z", + "contributors": [ + "bekti" + ] + }, + "Web/HTTP/Status/400": { + "modified": "2020-05-23T03:01:36.297Z", + "contributors": [ + "xenavrt" + ] + }, + "Web/HTTP/Status/403": { + "modified": "2020-10-15T22:30:03.647Z", + "contributors": [ + "xenavrt" + ] + }, + "Web/HTTP/Status/404": { + "modified": "2020-10-15T22:30:01.735Z", + "contributors": [ + "xenavrt" + ] + }, + "Web/HTTP/Status/405": { + "modified": "2020-05-23T02:57:36.571Z", + "contributors": [ + "xenavrt" + ] + }, + "Web/HTTP/Status/410": { + "modified": "2020-10-15T22:30:04.125Z", + "contributors": [ + "xenavrt" + ] + }, + "Web/HTTP/Status/500": { + "modified": "2020-10-15T21:57:54.889Z", + "contributors": [ + "dimyati_azhar", + "awanlamph" + ] + }, + "Web/JavaScript": { + "modified": "2020-03-12T19:37:54.103Z", + "contributors": [ + "SphinxKnight", + "Fidelstu", + "arifpedia", + "bekti", + "duriterlindung68", + "teoli", + "adeyahya", + "pieteru_insekai", + "keripix" + ] + }, + "Web/JavaScript/A_re-introduction_to_JavaScript": { + "modified": "2020-09-03T08:41:07.385Z", + "contributors": [ + "gifaeriyanto", + "irsyadharfiansyah", + "od2", + "kristoforusrp" + ] + }, + "Web/JavaScript/Data_structures": { + "modified": "2020-03-12T19:40:38.717Z", + "contributors": [ + "dinugr", + "Joe_Brown", + "fadlystwn", + "witart" + ] + }, + "Web/JavaScript/Inheritance_dan_prototype_chain": { + "modified": "2020-03-12T19:46:21.083Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Language_Resources": { + "modified": "2020-03-12T19:44:02.368Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Memory_Management": { + "modified": "2020-03-12T19:44:02.914Z", + "contributors": [ + "martinserafim93", + "agungprasetyosakti" + ] + }, + "Web/JavaScript/Panduan": { + "modified": "2020-03-12T19:38:02.146Z", + "contributors": [ + "bekti", + "teoli", + "kuntoaji" + ] + }, + "Web/JavaScript/Panduan/Closures": { + "modified": "2019-05-16T14:59:16.458Z", + "contributors": [ + "wbamberg", + "xlobin", + "sutikno" + ] + }, + "Web/JavaScript/Panduan/Loops_and_iteration": { + "modified": "2020-03-12T19:46:18.223Z", + "contributors": [ + "Fidelstu", + "jakarta" + ] + }, + "Web/JavaScript/Panduan/Numbers_and_dates": { + "modified": "2020-03-12T19:48:12.489Z", + "contributors": [ + "triashand" + ] + }, + "Web/JavaScript/Panduan/Tentang": { + "modified": "2019-05-16T15:03:14.492Z", + "contributors": [ + "wbamberg", + "adeyahya" + ] + }, + "Web/JavaScript/Panduan/Values,_variables,_and_literals": { + "modified": "2020-03-12T19:40:01.295Z", + "contributors": [ + "wbamberg", + "wawansumardi", + "sori-goklas-hutagalung", + "Fidelstu", + "bekti", + "kangfend", + "adeyahya" + ] + }, + "Web/JavaScript/Panduan/Working_with_Objects": { + "modified": "2020-03-12T19:48:10.821Z", + "contributors": [ + "thickkoezz", + "Fidelstu" + ] + }, + "Web/JavaScript/Panduan/pengenalan": { + "modified": "2020-03-12T19:41:22.637Z", + "contributors": [ + "snaztoz", + "thickkoezz", + "Fidelstu", + "ardhyui", + "bekti", + "adeyahya" + ] + }, + "Web/JavaScript/Reference": { + "modified": "2020-03-12T19:38:01.752Z", + "contributors": [ + "opblang", + "bekti", + "srifqi", + "teoli", + "keripix", + "boyo" + ] + }, + "Web/JavaScript/Reference/About": { + "modified": "2019-03-23T23:32:37.338Z", + "contributors": [ + "srifqi", + "teoli", + "keripix" + ] + }, + "Web/JavaScript/Reference/Classes": { + "modified": "2020-11-05T03:06:39.925Z", + "contributors": [ + "septianayoyo", + "syaifulrmdhn", + "rifqieh", + "shilohchis", + "fscholz" + ] + }, + "Web/JavaScript/Reference/Classes/constructor": { + "modified": "2020-03-12T19:45:06.809Z", + "contributors": [ + "bayuah", + "rafafauzi", + "MichaelSipayung", + "adfie" + ] + }, + "Web/JavaScript/Reference/Classes/extends": { + "modified": "2020-10-15T22:17:13.204Z", + "contributors": [ + "kbkesit" + ] + }, + "Web/JavaScript/Reference/Errors": { + "modified": "2020-03-12T19:44:10.832Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Errors/Called_on_incompatible_type": { + "modified": "2020-03-12T19:49:06.201Z", + "contributors": [ + "thickkoezz" + ] + }, + "Web/JavaScript/Reference/Errors/Invalid_array_length": { + "modified": "2020-03-12T19:49:10.144Z", + "contributors": [ + "thickkoezz" + ] + }, + "Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement": { + "modified": "2020-03-12T19:48:15.949Z", + "contributors": [ + "SphinxKnight" + ] + }, + "Web/JavaScript/Reference/Errors/Negative_repetition_count": { + "modified": "2020-03-12T19:49:08.676Z", + "contributors": [ + "thickkoezz" + ] + }, + "Web/JavaScript/Reference/Errors/Not_a_codepoint": { + "modified": "2020-03-12T19:49:02.574Z", + "contributors": [ + "thickkoezz" + ] + }, + "Web/JavaScript/Reference/Errors/Not_defined": { + "modified": "2020-03-12T19:48:26.149Z", + "contributors": [ + "alattalatta", + "KLIWONJagung", + "ariefjava" + ] + }, + "Web/JavaScript/Reference/Errors/Property_access_denied": { + "modified": "2020-03-12T19:49:07.387Z", + "contributors": [ + "thickkoezz" + ] + }, + "Web/JavaScript/Reference/Errors/Too_much_recursion": { + "modified": "2020-03-12T19:49:07.518Z", + "contributors": [ + "thickkoezz" + ] + }, + "Web/JavaScript/Reference/Functions": { + "modified": "2020-10-15T22:08:23.542Z", + "contributors": [ + "snek" + ] + }, + "Web/JavaScript/Reference/Global_Objects": { + "modified": "2020-03-12T19:38:31.023Z", + "contributors": [ + "bekti", + "teoli", + "Norbert" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array": { + "modified": "2020-04-13T23:45:16.177Z", + "contributors": [ + "jatmikaekachandra", + "hadyandev", + "triashand", + "arai" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/concat": { + "modified": "2019-03-23T22:34:10.740Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/filter": { + "modified": "2020-10-15T21:57:56.237Z", + "contributors": [ + "yahyaman" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/from": { + "modified": "2019-03-23T22:33:46.573Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/isArray": { + "modified": "2019-03-23T22:33:50.161Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/join": { + "modified": "2019-01-16T22:41:40.168Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/length": { + "modified": "2019-03-23T22:19:38.980Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/of": { + "modified": "2019-03-23T22:32:18.069Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/pop": { + "modified": "2019-03-23T22:32:08.604Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/reverse": { + "modified": "2019-03-23T22:33:45.481Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/shift": { + "modified": "2019-03-23T22:32:14.302Z", + "contributors": [ + "verdysaputra", + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/slice": { + "modified": "2020-10-15T22:30:58.309Z", + "contributors": [ + "Mikeul", + "adisetiawan" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/splice": { + "modified": "2020-10-15T22:01:33.229Z", + "contributors": [ + "handipriyono" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/unshift": { + "modified": "2019-03-23T22:32:11.465Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/values": { + "modified": "2019-03-23T22:32:16.581Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Date": { + "modified": "2019-03-23T22:34:07.176Z", + "contributors": [ + "fscholz" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Date/getFullYear": { + "modified": "2020-10-15T22:19:08.648Z", + "contributors": [ + "thickkoezz" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Date/now": { + "modified": "2019-03-23T22:32:46.175Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Date/toJSON": { + "modified": "2019-03-23T22:34:13.538Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Date/toTimeString": { + "modified": "2019-03-23T22:33:14.301Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Error": { + "modified": "2019-03-23T22:31:47.242Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Error/name": { + "modified": "2019-03-23T22:31:47.638Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Function": { + "modified": "2019-03-18T20:47:58.533Z", + "contributors": [ + "syaifulrmdhn", + "fscholz" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Function/displayName": { + "modified": "2019-03-23T22:32:21.293Z", + "contributors": [ + "teoli", + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Function/length": { + "modified": "2019-03-23T22:33:40.528Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Function/name": { + "modified": "2019-03-23T22:32:16.445Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Function/prototype": { + "modified": "2019-03-23T22:32:00.489Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/JSON": { + "modified": "2019-01-16T22:42:04.885Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/JSON/parse": { + "modified": "2019-03-23T22:33:56.784Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Map": { + "modified": "2019-03-23T22:33:57.668Z", + "contributors": [ + "fscholz" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Map/clear": { + "modified": "2019-03-23T22:33:58.119Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Map/delete": { + "modified": "2019-03-23T22:33:53.697Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Math": { + "modified": "2019-03-23T23:31:07.263Z", + "contributors": [ + "bekti", + "teoli", + "trucy" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Math/E": { + "modified": "2020-10-15T22:08:43.695Z", + "contributors": [ + "oktavianusmisro94" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Math/LN10": { + "modified": "2020-10-15T22:08:43.804Z", + "contributors": [ + "oktavianusmisro94" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Math/abs": { + "modified": "2019-03-23T22:27:14.164Z", + "contributors": [ + "baponk" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Math/ceil": { + "modified": "2020-10-15T21:49:08.672Z", + "contributors": [ + "bayuah", + "baponk" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Math/floor": { + "modified": "2019-03-23T22:27:14.949Z", + "contributors": [ + "twahyono", + "baponk" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Math/max": { + "modified": "2019-03-23T22:31:59.160Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Math/min": { + "modified": "2019-03-23T22:32:03.547Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Math/pow": { + "modified": "2019-03-23T23:31:18.374Z", + "contributors": [ + "teoli", + "egiw" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Object": { + "modified": "2019-03-23T22:37:32.954Z", + "contributors": [ + "dinugr", + "bekti", + "fscholz" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf": { + "modified": "2019-03-23T22:26:28.903Z", + "contributors": [ + "Ganesha" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Object/keys": { + "modified": "2019-03-23T22:26:35.536Z", + "contributors": [ + "haris" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Object/preventExtensions": { + "modified": "2019-07-08T04:20:18.084Z", + "contributors": [ + "Ganesha" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Promise": { + "modified": "2020-10-15T21:46:00.705Z", + "contributors": [ + "fscholz", + "PeteDevoy" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Promise/catch": { + "modified": "2020-10-15T21:46:01.765Z", + "contributors": [ + "fscholz", + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Promise/reject": { + "modified": "2020-10-15T21:46:00.008Z", + "contributors": [ + "fscholz", + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Promise/resolve": { + "modified": "2020-10-15T21:46:28.393Z", + "contributors": [ + "fscholz", + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Promise/then": { + "modified": "2020-10-15T21:46:01.723Z", + "contributors": [ + "fscholz", + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/RegExp": { + "modified": "2020-10-15T22:32:16.409Z", + "contributors": [ + "SphinxKnight", + "mijoonpcyoutuube" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String": { + "modified": "2019-03-23T22:54:51.028Z", + "contributors": [ + "wbamberg", + "srifqi" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String/concat": { + "modified": "2019-03-23T22:34:05.198Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String/fromCharCode": { + "modified": "2020-08-08T03:30:34.821Z", + "contributors": [ + "whitehoodie", + "srifqi" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String/fromCodePoint": { + "modified": "2020-10-15T22:15:58.214Z", + "contributors": [ + "antonbudianto" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String/indexOf": { + "modified": "2019-03-23T22:29:51.517Z", + "contributors": [ + "MuhammadFariMadyan", + "adoel90" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String/length": { + "modified": "2019-03-23T22:34:08.649Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String/link": { + "modified": "2019-03-23T22:31:46.275Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String/purwarupa": { + "modified": "2019-03-23T22:54:49.067Z", + "contributors": [ + "bekti", + "srifqi" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String/split": { + "modified": "2019-03-23T22:31:50.185Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String/toLowerCase": { + "modified": "2019-03-23T22:31:46.602Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String/toString": { + "modified": "2019-03-23T22:32:42.001Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String/toUpperCase": { + "modified": "2019-03-23T22:33:39.473Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/TypedArray": { + "modified": "2019-03-23T22:31:58.327Z", + "contributors": [ + "arai" + ] + }, + "Web/JavaScript/Reference/Global_Objects/TypedArray/join": { + "modified": "2019-03-23T22:32:07.353Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Global_Objects/isNaN": { + "modified": "2020-10-15T21:57:16.564Z", + "contributors": [ + "yusrilhs" + ] + }, + "Web/JavaScript/Reference/Lexical_grammar": { + "modified": "2020-03-12T19:46:20.884Z", + "contributors": [ + "nndwn", + "sori-goklas-hutagalung" + ] + }, + "Web/JavaScript/Reference/Operators": { + "modified": "2020-03-12T19:39:41.862Z", + "contributors": [ + "galih977", + "SphinxKnight", + "teoli" + ] + }, + "Web/JavaScript/Reference/Operators/Conditional_Operator": { + "modified": "2020-10-15T22:00:22.485Z", + "contributors": [ + "syuaib", + "zainalmustofa" + ] + }, + "Web/JavaScript/Reference/Operators/fungsi": { + "modified": "2020-03-12T19:45:02.306Z", + "contributors": [ + "opblang" + ] + }, + "Web/JavaScript/Reference/Operators/yield": { + "modified": "2020-10-15T21:58:01.116Z", + "contributors": [ + "PUYUP", + "j-blank", + "tangorboyz" + ] + }, + "Web/JavaScript/Reference/Statements": { + "modified": "2020-03-12T19:38:01.955Z", + "contributors": [ + "bekti", + "teoli", + "keripix" + ] + }, + "Web/JavaScript/Reference/Statements/Empty": { + "modified": "2020-03-12T19:45:20.591Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Statements/class": { + "modified": "2020-03-12T19:43:42.480Z", + "contributors": [ + "bekti" + ] + }, + "Web/JavaScript/Reference/Statements/do...while": { + "modified": "2020-10-15T21:46:22.842Z", + "contributors": [ + "bayuah", + "bekti" + ] + }, + "Web/JavaScript/Reference/Statements/export": { + "modified": "2020-03-12T19:44:15.912Z", + "contributors": [ + "fadlystwn", + "blubMe" + ] + }, + "Web/JavaScript/Reference/Statements/for...in": { + "modified": "2020-03-12T19:43:18.701Z", + "contributors": [ + "bekti", + "haris" + ] + }, + "Web/JavaScript/Reference/Statements/fungsi": { + "modified": "2020-03-12T19:46:13.838Z", + "contributors": [ + "irhamkim" + ] + }, + "Web/JavaScript/sekilas_teknologi_JavaScript": { + "modified": "2020-03-12T19:45:33.240Z", + "contributors": [ + "arifpedia" + ] + }, + "Web/MathML": { + "modified": "2020-10-15T22:09:52.119Z", + "contributors": [ + "AzizMuslim", + "ExE-Boss" + ] + }, + "Web/MathML/Element": { + "modified": "2019-03-18T21:24:31.292Z", + "contributors": [ + "okabrionz" + ] + }, + "Web/Reference": { + "modified": "2019-03-23T23:22:42.575Z", + "contributors": [ + "kscarfone" + ] + }, + "Web/Reference/API": { + "modified": "2019-03-23T23:22:41.127Z", + "contributors": [ + "bekti", + "Al_akbar", + "drihPee", + "bertzzie", + "teguhsetiyawan" + ] + }, + "Web/Security": { + "modified": "2019-09-10T16:35:29.682Z", + "contributors": [ + "SphinxKnight", + "cahbraling" + ] + }, + "Web/Web_Components": { + "modified": "2020-10-19T12:17:25.927Z", + "contributors": [ + "guciano" + ] + } +} \ No newline at end of file diff --git a/files/id/archive/add-ons/index.html b/files/id/archive/add-ons/index.html new file mode 100644 index 0000000000..acb2f057f2 --- /dev/null +++ b/files/id/archive/add-ons/index.html @@ -0,0 +1,11 @@ +--- +title: Add-ons +slug: Archive/Add-ons +tags: + - NeedsTranslation + - TopicStub +translation_of: Archive/Add-ons +--- +

Archived add-ons documentation.

+ +

Add-on SDK
Using the Add-on SDK, you can create Firefox add-ons. You can use various standard Web technologies: JavaScript, HTML, and CSS, to create the add-ons. The SDK includes JavaScript APIs, which you can use to create add-ons and tools for creating, running, testing, and packaging add-ons.
bookmarks.export()
Exports bookmarks to an HTML bookmark file.
bookmarks.import()
Imports bookmarks from an HTML bookmark file.
Bootstrapped extensions
browser.bookmarks.export( function() {...} // optional function )
Code snippets
Creating custom Firefox extensions with the Mozilla build system
There is a wealth of material on creating extensions for Firefox. All of these documents currently assume, however, that you are developing your extension using XUL and JavaScript only. For complex extensions, it may be necessary to create components in C++ that provide additional functionality. Reasons why you might want to include C++ components in your extension include:
Extension Etiquette
This article describes best practices when making extensions, including how to be kind to your users. It assumes that you are already familiar with Building an Extension.
Extension Packaging
By the end of 2017 WebExtensions will be the only supported add-on type in Firefox. To learn how to install a WebExtension for testing purposes, see Temporary Installation in Firefox. To learn how to package a WebExtension for distribution, see Publishing your WebExtension.
Extensions support in SeaMonkey 2
Starting with SeaMonkey 2 Alpha 1 SeaMonkey supports toolkit/-style extensions. These type of extensions have many advantages for both users and developers compared to the old xpinstall/-style extensions.
Firefox addons developer guide
The original document is in Japanese and distributed via the xuldev.org website. So there may be still some reference to the xuldev website (we want to host source code on MDC, not on xuldev), and to Japanese things (like some specific locales, which have been translated to French since non-latin characters are not well supported).
Hotfix Extension
This document has been moved to the Add-ons wiki.
How to convert an overlay extension to restartless
First off, what kind of add-on are we talking about here? Well, XUL overlays and windows, JSM files, chrome & resource mappings with localization, default preferences, but no XPCOM components of your own. Some of that will have to be replaced and the rest will need to be loaded differently.
Inline options
Firefox 7 supports a new syntax for defining extensions' preferences for both bootstrapped and traditional extensions. The user interface for the preferences defined with this new syntax appears in the extension's detail view in the Add-on Manager. This functionality originally appeared in Firefox mobile and is now available in Firefox on the desktop as well.
Install Manifests
An Install Manifest is the file an Add-on Manager-enabled XUL application (e.g. Firefox or Thunderbird) uses to determine information about an add-on as it is being installed. It contains metadata identifying the add-on, providing information about who created it, where more information can be found about it, which versions of what applications it is compatible with, how it should be updated, and so on.
Interaction between privileged and non-privileged pages
An easy way to send data from a web page to an extension is by using custom DOM events. In your extension's browser.xul overlay, write code which listens for a custom DOM event. Here we call the event MyExtensionEvent.
Legacy Add-ons
This section contains links to documentation for legacy technology for add-on development, including:
Legacy extensions for Firefox for Android
Add-ons that work with desktop Firefox do not automatically work in Firefox for Android:
Overlay extensions
This page contains links to documentation for the approach to developing extensions for Gecko-based applications which uses:
Performance best practices in extensions
One of Firefox's great advantages is its extreme extensibility. Extensions can do almost anything. There is a down side to this: poorly written extensions can have a severe impact on the browsing experience, including on the overall performance of Firefox itself. This article offers some best practices and suggestions that can not only improve the performance and speed of your extension, but also of Firefox itself.
Security best practices in extensions
This document is intended as a guide for developers to promote best practices in securing your extension. Your goal is to keep your users safe. Some items mentioned are strict guidelines, meaning that if you don't follow them then your add-on will not be approved on Mozilla add-ons. Other items are recommendations. The difference will be clearly flagged.
Setting up an extension development environment
This article provides suggestions for how to set up your Mozilla application for extension development. These details apply to Firefox, Thunderbird, and SeaMonkey (version 2.0 and above).
Tabbed browser
Here you should find a set of useful code snippets to help you work with Firefox's tabbed browser. The comments normally mark where you should be inserting your own code.
Techniques
.
Working with multiprocess Firefox
In older versions of Firefox, chrome code (including code inserted by extensions) and content run in the same operating system process. So extensions can access content directly:

diff --git a/files/id/archive/b2g_os/developing_firefox_os/index.html b/files/id/archive/b2g_os/developing_firefox_os/index.html new file mode 100644 index 0000000000..d36360d6fa --- /dev/null +++ b/files/id/archive/b2g_os/developing_firefox_os/index.html @@ -0,0 +1,51 @@ +--- +title: Developing Firefox OS +slug: Archive/B2G_OS/Developing_Firefox_OS +tags: + - B2G + - Developing + - Firefox OS + - NeedsTranslation + - TopicStub +translation_of: Archive/B2G_OS/Developing_Firefox_OS +--- +
+

Bagian ini memberikan dokumentasi yang berguna yang mencakup berbagai cara di mana OS Firefox (codename Boot2Gecko, atau B2G) dapat dimodifikasi / disesuaikan selama proses pembuatan, dan bagaimana Anda dapat membantu mengembangkan area platform tingkat rendah seperti Gecko dan Gonk.

+
+ +
+

Catatan: Jika Anda secara khusus tertarik untuk membantu mengembangkan Gaia, antarmuka pengguna Firefox OS, Anda harus berkonsultasi dengan halaman Mengembangkan Gaia kami.

+
+ +

Catatan Kontribusi Umum

+ +

Karena Gecko adalah bagian integral dari browser Firefox, berkontribusi pada komponen yang terkait dengan Firefox Gecko adalah proses yang mirip dengan Gecko pada umumnya; Menyumbang Gonk juga lumayan mirip. Pada dasarnya, Anda perlu mengenal komunitas, pelajari bagaimana basis kode bekerja, dan temukan bug untuk dikerjakan. Tempat yang baik untuk mulai mendapatkan penghasilan tentang proses kontribusi Kontribusi pada basis kode Mozilla.

+ +

Anda harus belajar tentang Gecko — cara kerjanya dan bagaimana strukturnya. Halaman awal MDN Gecko memiliki beberapa catatan yang berguna pada ini, seperti halnya Gecko: halaman Tinjauan pada Mozilla Wiki. Untuk informasi tentang API (Spesifik Mozilla OS), lihat halaman Wiki WebAPI untuk ringkasan pekerjaan, dan halaman MDN WebAPI untuk indeks semua API yang terdokumentasi.

+ +

Next, look at Gonk, the kernel that Firefox OS runs on top of. Gonk is basically another porting target for Gecko, just like Mac OS X, Windows and Linux are in the case of Desktop Firefox versions. Gonk itself is really just a stripped down version of the Android Open Source Project — we tend not to change much of Gonk itself since most of the source code isn't under our control, and the device partners we work with to create Firefox OS devices usually provide device-specific code to interface between the device and Gecko/Gonk.

+ +

There is still work to be done on APIs, however. Most Gonk-specific Gecko code either uses #ifdef MOZ_WIDGET_GONK to only enable it in Firefox OS, and/or are contained in gonk subdirectories, such as gecko-dev/hal/gonk. Try cloning the gecko-dev repo locally and having a look around. Our Mozilla Source Code Directory Structure article is also useful.

+ +

Next, you should learn more about Firefox OS architecture, how to Build Firefox OS (start with the Firefox OS build process summary), and how to Port Firefox OS to other devices.

+ +

Firefox OS is developed as a series of separate Modules: review the Firefox OS Modules page to get an idea of how the codebase is grouped, and learn who the main module owners are so you can get an idea of who to talk to if you need help.

+ +
+

Note: To find help, the best places to start are the dev-b2g mailing list, and the #b2g chatroom on Mozilla IRC.

+
+ +

Specific Firefox OS development topics

+ +
+
Filing bugs against Firefox OS
+
This article provides a guide to filing bugs against any aspect of Firefox OS.
+
Modifying the hosts file
+
A guide to what can be achieved by modifying the Firefox OS hosts file.
+
Customization with the .userconfig file
+
How to customize the build and execution of Firefox OS by changing the .userconfig file.
+
Customizing the b2g.sh script
+
An explanation of what can be achieved by customizing the b2g.sh script, which runs the b2g application and controls many aspects of the system.
+
Customizing DNS
+
This article outlines a procedure to change the DNS servers for all interfaces (wifi, cellular, etc.) on a Firefox OS device.
+
diff --git a/files/id/archive/b2g_os/developing_firefox_os/porting/index.html b/files/id/archive/b2g_os/developing_firefox_os/porting/index.html new file mode 100644 index 0000000000..33d147813a --- /dev/null +++ b/files/id/archive/b2g_os/developing_firefox_os/porting/index.html @@ -0,0 +1,123 @@ +--- +title: Porting Firefox OS +slug: Archive/B2G_OS/Developing_Firefox_OS/Porting +translation_of: Archive/B2G_OS/Porting_B2G_OS/basics +--- +
+

Firefox OS (formerly Boot to Gecko) uses a kernel derived from Android, with a Gecko-based user interface on top of it. This article provides a basic guide to how to go about porting the operating system to new devices.

+
+

This guide assumes you're porting to a new device that already runs Android; if you're porting to another device, the job is going to be more involved.

+

Set up your build system

+

The first step is to configure your build system; you can follow the guide in Firefox OS build prerequisites.

+

Create a local backup of the original Android system

+

Next, you should back up your Android device before you start nuking it with your test builds of B2G. In addition, some of these bits will be needed by the build and install process.

+
mkdir my_device_backup
+cd my_device_backup
+adb pull /system system
+

Clone the B2G repositories

+

The first step is to clone the B2G repository as well as the repository with the manifests.

+
git clone https://github.com/mozilla-b2g/B2G.git
+git clone https://github.com/mozilla-b2g/b2g-manifest.git
+

Add a new device to config.sh

+

The next step is to add a new device to config.sh in the B2G repository;  you can use the existing ones as a template. This basically involves providing the instructions for fetching the correct files to do the build.

+

Create a manifest for the new device

+

Now you need to add a manifest file for the new device. Refer to one of the existing manifests for a template. You can use the hamachi manifest a reference. Once done, you should add and commit your new manifest to your local b2g-manifest repository:

+
git add my-new-device.xml
+git commit
+
+

Next, you will want the config.sh file to use your local b2g-manifest repository instead of the official one. To achieve this, change the values of the GITREPO and BRANCH variables in the config.sh file to the location of your local repository and desired branch, for example:

+
GITREPO=${GITREPO:-"file:///home/yourname/b2g-manifest"}
+BRANCH=${BRANCH:-master}
+

Create a configuration tree for the new device

+

Create a new configuration tree for the new device. This should be at device/<manufacturer>/<device_id>. This tree should include, at least:

+ +

The content here may differ a great deal from one device to another. In particular, BoardConfig.mk and extract-files.sh may differ significantly. This part requires a lot of hacking, testing, and debugging to figure out which binary blobs should be extracted. To get a better idea what is supposed to be contained there, take a look at the configuration for the hamachi device. Remember to correctly reference your own configuration tree from the manifest you created for your new device.

+
+

Note: If you can find an existing reference on CyanogenMod for your device, this information will speed up the porting process. the XDA Forum is another good place to discuss and check for resources.

+
+

Rebuild boot.img

+

Once you have all that done, you need to rebuild the boot image. This isn't usually needed for the kernel itself, but to pick up the changes to init.rc.

+

Changes to init.rc

+

The init.rc you use is not the one provided by B2G; instead, you need to pull it from the device.

+

The main things you'll need to modify are:

+

Import init.b2g.rc

+

Add the following lines to import init.b2g.rc:

+
on early-init
+    start ueventd
+    import /init.b2g.rc
+

Fix permissions

+

Correct the permissions on the files /system/b2g/b2g, /system/b2g/updater, /system/b2g/plugin-container; this should be done after the lines that mount the filesystem read/write:

+
chmod 0755 /system/b2g/b2g
+chmod 0755 /system/b2g/updater
+chmod 0755 /system/b2g/plugin-container
+

You might want to start by modifying the init.rc from the new device instead of using the init.rc provided by the build system; if so, you need to remember to set TARGET_PROVIDES_INIT_RC in BoardConfig.mk.

+

Prebuilt kernel vs. building the kernel from source

+

You can use a prebuilt kernel, or you may build the kernel from source. To build the kernel from source, add AndroidKernel.mk and the kernel config to the device configuration tree.

+

The maguro on the old build system is an example that builds the kernel from source.

+

Extracting and modifying an existing boot image

+

It is possible to recover the boot image of a phone by dumping the contents of the /dev/mtd/mtd1 or /dev/mtd/mtd2 devices, the resulting image file can then be easily recovered:

+
adb shell 'cat /dev/mtd/mtd1 > /sdcard/boot.img'
+adb pull /sdcard/boot.img
+
+

Once the boot image file has been obtained it can be unpacked via a helper tool such as unmkbootimg. The tool will extract both the kernel image (zImage) and the ramdisk (initramfs.cpio.gz) as well as printing out a command to rebuild the image with the same parameters of the original one, for example:

+
$ unmkbootimg boot.img
+Kernel size 3872576
+Kernel address 0x208000
+Ramdisk size 265102
+Ramdisk address 0x1500000
+Secondary size 0
+Secondary address 0x1100000
+Kernel tags address 0x200100
+Flash page size 2048
+Board name is ""
+Command line "androidboot.hardware=aphone"
+Extracting kernel to file zImage ...
+Extracting root filesystem to file initramfs.cpio.gz ...
+All done.
+---------------
+To recompile this image, use:
+  mkbootimg --kernel zImage --ramdisk initramfs.cpio.gz --base 0x200000 --cmdline 'androidboot.hardware=aphone' -o new_boot.img
+---------------
+
+

To modify the ramdisk file create an output directory and extract it there:

+
mkdir initramfs_dir
+cd initramfs_dir
+gunzip -c ../initramfs.cpio.gz | cpio -i
+
+

Make all the required changes (such as modifying init.rc) and repack the ramdisk using mkbootfs, be sure to use the version that has been built with the B2G host tools:

+
/path/to/your/B2G/out/host/linux-x86/bin/mkbootfs . | gzip > ../newinitramfs.cpio.gz
+
+

Finally go back to the top-level directory and re-pack the boot image using the mkbootimg, also make sure you're using the version built with the other B2G host tools:

+
/path/to/your/B2G/out/host/linux-x86/bin/mkbootimg --kernel zImage --ramdisk newinitramfs.cpio.gz --base 0x200000 --cmdline 'androidboot.hardware=aphone' -o newboot.img
+
+

If you now copy the new boot image under out/target/product/$DEVICE/boot.img (where $DEVICE is your device name) it will be automatically flashed when invoking flash.sh. Alternatively you can flash it by hand with the following commands:

+
adb reboot bootloader
+fastboot flash boot newboot.img
+fastboot reboot
+
+

Add the new device to flash.sh

+

Add the new device to flash.sh; the specifics of how to do this will depend on what tools need to be used to flash the new device.

+

Configure, build, and flash the new device

+

Now you can try building for and flashing to your new device:

+
ANDROIDFS_DIR=my_device_backup ./config.sh <device_id> '../b2g-manifest/default.xml'
+./build.sh
+./flash.sh
+

Test and debug

+

We need some details added here; indeed, this entire article could use some help.

+

FAQ

+

Forthcoming

+

See also

+ diff --git a/files/id/archive/b2g_os/firefox_os_apps/index.html b/files/id/archive/b2g_os/firefox_os_apps/index.html new file mode 100644 index 0000000000..370236dd14 --- /dev/null +++ b/files/id/archive/b2g_os/firefox_os_apps/index.html @@ -0,0 +1,85 @@ +--- +title: Firefox OS apps +slug: Archive/B2G_OS/Firefox_OS_apps +tags: + - Apps + - Building + - Components + - Firefox OS + - Installing + - NeedsTranslation + - TopicStub + - device APIs +translation_of: Archive/B2G_OS/Firefox_OS_apps +--- +

This section of the Firefox OS docs covers the specific techniques required — and available tools — for building Firefox OS apps. You'll find a number of details below, from Firefox OS building blocks/web components, to device APIs and App installation.

+ +

Building Firefox OS apps

+ +
+
Building apps for Firefox OS
+
Firefox OS/Firefox platform app specifics, including App installation and management APIs, manifest files, packaged and hosted apps, handling API permissions.
+
Localization
+
This set of articles provides information for developers wishing to provide localized versions of their apps.
+
Performance
+
This page lists performance-related topics specific to Firefox OS.
+
Firefox Accounts on Firefox OS
+
This article provides an overview of using Firefox Accounts in Firefox OS.
+
Reference apps
+
This page lists a number of sample apps we've put together for you to download, install, play with and learn from. Have fun!
+
Screencast series: App Basics for Firefox OS
+
In this collection of short videos, developers from Mozilla and Telenor explain in a few steps how you can get started with building applications for Firefox OS.
+
+ +

Building blocks

+ +
+
Building Blocks
+
The Firefox OS Building Blocks are reusable UI components (also called 'common controls') that reflect OS-wide design patterns. Building Blocks are used to create the interfaces of all Gaia default apps. You are free to make use of these components in your own Firefox OS apps, or general Web apps.
+
+ +

Styleguides

+ +
+
Firefox OS Visual styleguide
+
Our style guide for Firefox OS visual design, covering colours, typeface, backgrounds, app icons, and the design of specific UI elements.
+
Firefox OS Copy styleguide
+
This guide outlines the rules we follow for writing Firefox OS app copy, but can be used as a general guide to writing good copy for any app interfaces.
+
Firefox OS in Arabic
+
A guide to the specific UX design implementation Firefox OS has in place for dealing with Arabic (and other RTL languages.)
+
+ +

Assets

+ +
+
Firefox OS design asset library
+
In this section you'll find design assets, artwork, graphic templates, fonts and other materials that will be helpful as you design Firefox OS/Gaia apps.
+
Firefox OS icon font
+
Firefox OS has its own icon font set available: this article explains how to use it in your own apps.
+
Firefox OS transitions
+
A reference to some of the transitions used in Firefox OS to move between different states in apps, including animated GIFs demonstrating the animations used, plus code samples to show the CSS animation code needed to implement these animations.
+
+ +

References

+ +
+
Firefox OS device APIs
+
This article provides a list of pages covering those APIs, as well as the app manifest permissions for each one.
+
Firefox OS app tools
+
This page provides a list of useful tools, libraries, examples, etc. that are useful for Firefox OS app developers, whether you want a code template to copy, or need help with adding a specific feature to your Firefox OS app.
+
+ +

Other app topics

+ +
+
Porting Chrome apps to Firefox OS Apps
+
This article discusses the differences between Chrome apps and Firefox OS Apps, and how you can convert between the two.
+
App development FAQ
+
This FAQ is a compilation of answers to common app development questions.
+
+ +

See also

+ + diff --git a/files/id/archive/b2g_os/firefox_os_apps/pelokalan/index.html b/files/id/archive/b2g_os/firefox_os_apps/pelokalan/index.html new file mode 100644 index 0000000000..acb5aeb487 --- /dev/null +++ b/files/id/archive/b2g_os/firefox_os_apps/pelokalan/index.html @@ -0,0 +1,92 @@ +--- +title: Pelokalan aplikasi +slug: Archive/B2G_OS/Firefox_OS_apps/Pelokalan +translation_of: Archive/B2G_OS/Firefox_OS_apps/Localization +--- +

+ +
+

This set of articles provides information for developers wishing to provide localized versions of their apps.

+
+ +

Tutorials

+ +
+
Getting started with app localization
+
This tutorial provides a detailed guide to app localization.
+
Connecting developers and translators with Transifex
+
This article explores the use of Transifex for managing translation work, both for app developers and localizers.
+
+ +

Reference

+ +
+
L10n.js reference
+
This article provides a reference for the l10n.js library, and its associated date helper, l10n_date.js.
+
Internationalization helpers: IntlHelper and mozIntl
+
This article looks at how Firefox OS handles localization of dates, times, numbers and collators from version 2.5 onwards, using the Internationalization API and Gaia's built in helpers, IntlHelper and mozIntl.
+
App localization code best practices
+
Localization best practices and advanced techniques for experienced Gaia/app developers.
+
Developing Bidi Apps
+
Best coding practices and guidelines for developing bi-directional (left-to-right and right-to-left, RTL) apps.
+
+ +

Tools

+ +
+
Translation tester
+
This app is for testing translations for Firefox OS apps and provides a blueprint for adding translation support to your own apps.
+
diff --git a/files/id/archive/b2g_os/index.html b/files/id/archive/b2g_os/index.html new file mode 100644 index 0000000000..5d4a5149dc --- /dev/null +++ b/files/id/archive/b2g_os/index.html @@ -0,0 +1,79 @@ +--- +title: Firefox OS +slug: Archive/B2G_OS +tags: + - Boot to Gecko + - Firefox OS + - Gaia +translation_of: Archive/B2G_OS +--- +

Firefox OS (kadang-kadang disingkat FxOS) adalah sistem operasi mobile baru yang dikembangkan oleh Mozilla. menggunakan kernel Linux dan mesin berbasis Gecko, yang memungkinkan pengguna menjalankan aplikasi yang dikembangkan seluruhnya menggunakan HTML, JavaScript, dan open web application APIs lainnya.

+ +

Firefox OS saat ini dalam pengembangan besar; kami terus bekerja untuk membuatnya lebih mudah digunakan dan hack pada Gaia (aplikasi standar) dan membuat sendiri. Namun, Anda perlu pengetahuan tentang sistem untuk melakukan hal-hal seperti membangun Firefox OS stack, atau memasang Firefox OS kedalam handphne Anda. Link dibawah ini adalah panduan untuk pengembang web yang tertarik menjalankan dan membuat peribahan untuk Gaia atau mengembangkan aplikasi untuk berjalan di perangkat Firefox OS.

+ + + + + + + + +
+

Dokumentasi tentang Firefox OS

+ +
+
Pengantar Firefox OS
+
Informasi pengantar tentang apa itu Firefox OS dan bagaimana cara kerjanya.
+
Tips dan trik Firefox OS
+
Beberapa artikel pendek tentang tips dan trik yang berguna untuk mengetahui Firefox OS disaat melakukan hacking.
+
Menulis aplikasi untuk Firefox OS
+
Dokumentasi tentang membuat aplikasi Firefox OS.
+
Pusat pengembang
+
Kumpulan peralatan, tutorial, dan layanan untuk pengembang aplikasi Firefox OS.
+
UX (Pengalaman pengguna)
+
Panduan untuk Gaya user experience desain, maupun pola kode dan template untuk membantu Anda membuat aplikasi Firefox OS yang menarik dan konsisten.
+
Platform Firefox OS
+
Dokumentasi tentang platform Firefox OS, termasuk Gonk, Gaia, dan lainnya. Ini termasuk dokumentasi untuk membangun dan memasang platform ke perangkat, serta membangun simulator dan emulator.
+
Keamanan
+
Dokumentasi tentang keamnan  di Firefox OS; ini termasuk topik tentang keamanan perangkat dari setiap perspektif: untuk pengembang aplikasi, perangkat integrator, dan sebagainya.
+
Performa
+
Artikel tentang mengoptimalisasi aplikasi Firefox OS.
+
Pemecahan Masalah
+
Panduan untuk mengatasi masalah umum pada Firefox OS.
+
Debugging pada Firefox OS
+
Panduan untuk debugging aplikasi mobile dan Firefox OS itu sendiri.
+
Panduan untuk  Firefox OS developer phone
+
Panduan untuk Firefox OS developer phones, Mozilla memberikan telepon ke beberapa pengembang. Panduan ini juga berlaku jika sesorang memasang Firefox OS ke teleponnya
+
+ +

Lihat Semua...

+
+

Dapatkan bantuan dari komunitas

+ +

Jika Anda bekerja dengan Firefox OS, atau mengembangkan aplikasi yang ingin dijalankan di perangkat Firefox OS, ada komunitas yang akan membantu Anda!

+ +
    +
  • Ajukan pertanyaan Anda ke Mozilla Boot to Gecko IRC channel: #b2g
  • +
+ +

Jangan lupa tentang netiquette...

+ + + + + + +

Sumber Lain

+ + +
diff --git a/files/id/archive/b2g_os/installing_on_a_mobile_device/index.html b/files/id/archive/b2g_os/installing_on_a_mobile_device/index.html new file mode 100644 index 0000000000..9ee7eb6251 --- /dev/null +++ b/files/id/archive/b2g_os/installing_on_a_mobile_device/index.html @@ -0,0 +1,100 @@ +--- +title: Installing Firefox OS on a mobile device +slug: Archive/B2G_OS/Installing_on_a_mobile_device +translation_of: Archive/B2G_OS/Installing_on_a_mobile_device +--- +
+

Once you've built Boot to Gecko for a supported mobile device, you can install it. This article will guide you through the process.

+
+
+ Note: The first time you flash your phone, it must have Android 4 (Ice Cream Sandwich) installed. The process will not work correctly otherwise. Once you've done your first install of B2G, however, you can simply update on top of it.
+

Installing ADB

+

On OSX

+

If you have homebrew on OSX:

+
brew install android-platform-tools
+

Otherwise, download the Android Developer Tools and add the binaries to your PATH.

+

On Ubuntu

+
sudo apt-get install android-tools-adb
+

Flashing your phone

+

To flash everything to your phone, simply connect your phone and type:

+
./flash.sh
+
+

That's it. The B2G you've currently got built will flash onto your device.

+

Note that If you are updating across revisions with significant Gaia changes, you might need also do:

+
cd gaia
+make reset-gaia
+

This will wipe all of your data stored in Gaia, but also clear out obsolete Gaia settings and prefs so that you'll boot into a "clean" Gaia. In theory ./flash.sh should do this already, but for some devices (e.g. hamachi) ./flash.sh only flashes a subset of modules (./flash.sh -f will force flash everything.)

+

Configuring the udev rule for your device

+

On Linux, if you get this,

+
< waiting for device >
+

that probably means that you haven't added a udev rule for the fastboot device, which is not the same as the one for adb. (Though it also might just mean you need to run ./flash.sh with sudo) You can get the USB vendor ID by running lsusb now, but typically it's Google's: 18d1, so adding this line in your /etc/udev/rules.d/51-android.rules would work:

+
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", MODE="0666", GROUP="plugdev"
+
+ Note: If you get a very helpful libusb error "-3" on Linux, it means you need to be root to have the needed access to the USB device. Run the script again using sudo.
+
+ Note 2: If you have an Unagi or a Geeksphone Keon phone, you need two lines like this - one for the original phone vendor's ID, and one for Google's.
+

Special notes for Hamachi, Helix, and Leo devices

+

If your phone is a hamachi, helix or leo device, the ./flash.sh script will now default to flashing only gecko and gaia.  It is recommended that you flash with the OEM as a base build to get the firmware and the gonk layers and then flash the gecko and gaia on top.  If you want to flash using the images, there is an override flash where you can ./flash.sh -f and it will use the image files to flash your device.

+

Special notes for the Samsung Galaxy S2

+

If your phone is a Galaxy S2 and you are using heimdall 1.3.2 (the latest version; use heimdall version to check), you may see an alarming error "FACTORYFS upload failed!" followed by "Heimdall flashing failed" and some additional information. This is actually a success condition, and you can ignore the advice.

+

To get rid of this strange behavior, grab a source copy of heimdall, downgrading to the 1.3.1 release ("git checkout fbbed42c1e5719cc7a4dceeba098981f19f37c06"), then compile it  according to the README, then install that to make the error go away. However, this isn't strictly necessary.

+
+

Note: the image size may not a problem. see the next tip

+
+

All versions of heimdall are unable to flash a system.img larger than 100MB. Do:

+
ls -l ./out/target/product/galaxys2/system.img
+
+

to see how big yours is. If it's too large, ask in IRC for advice; there are ways to do it in two stages.

+

The argument of heimdall command may not work and result in fail when trying to flash. You'll need to change it in the ./flash.sh script, the argument must be in uppercase (l.185) :

+
case $project in
+        "system")
+                $HEIMDALL flash --FACTORYFS out/target/product/$DEVICE/$project.img
+                ;;
+
+        "kernel")
+                $HEIMDALL flash --KERNEL device/samsung/$DEVICE/kernel
+                ;;
+
+        "")
+                $HEIMDALL flash --FACTORYFS out/target/product/$DEVICE/system.img --KERNEL device/samsung/$DEVICE/kernel &&
+                update_time
+                ;;
+        esac
+

 

+

Added step for the Samsung Galaxy S2

+

If you're flashing onto the Galaxy S2, there is an additional step to follow. Gaia does not get flashed automatically by the flash.sh script; you'll need to also do:

+
./flash.sh gaia
+
+

Flashing specific partitions to fastboot phones

+

You can flash specific partitions to fastboot phones (that is, any phone other than the Samsung Galaxy S2). For example:

+
./flash.sh system
+./flash.sh boot
+./flash.sh user
+
+

WARNING: flashing user (at least) may delete your user-specific data (contacts, etc.).

+

Updating specific modules

+

You can update specific components of B2G by specifying their names when flashing. For example:

+
./flash.sh gaia
+./flash.sh gecko
+
+

In order to update only one application you can use BUILD_APP_NAME environment variable:

+
BUILD_APP_NAME=calendar ./flash.sh gaia
+

If your phone is not for developer (you aren't interested on test apps and/or require optimization), you can update gaia using:

+
VARIANT=user ./flash.sh gaia
+

Next steps

+

At this point, your phone should be running Boot to Gecko! It's time to experiment, write some code, test, or do some debugging!

+
+ Note: A helpful usage tip: if your build of B2G starts up with the lock screen requesting a pass code to unlock the phone, the default code is 0000.
+

Troubleshooting

+

Here are a some tips for what to do if your device doesn't work right after installing B2G, or updating it to a new version

+

If the UI doesn't start up

+

If you update your phone and the user interface doesn't start up, you can reset it to clear out out-of-date configuration and the like. This may bring it back to life, but note that it may also delete your user-specific data (contacts, etc.). Here's how:

+
cd gaia
+make reset-gaia
+
+

If you want change from developer to production mode

+
cd gaia
+make reset-gaia PRODUCTION=1
+

WARNING: reset-gaia may delete your user-specific data (contacts, etc.).

+

"image is too large" error message on ./flash.sh execution

+

It might mean that you phone needs to be rooted first before flashing it. As b2g needs to be written on root partition, your phone needs to be rooted in order to install it.

diff --git a/files/id/archive/b2g_os/introduction/index.html b/files/id/archive/b2g_os/introduction/index.html new file mode 100644 index 0000000000..1c113d8712 --- /dev/null +++ b/files/id/archive/b2g_os/introduction/index.html @@ -0,0 +1,88 @@ +--- +title: Pengantar Firefox OS +slug: Archive/B2G_OS/Introduction +tags: + - B2G + - Firefox OS +translation_of: Archive/B2G_OS/Introduction +--- +

Firefox OS (juga disebut dengan codename "Boot to Gecko" atau "B2G") adalah sistem operasi open source Mozilla berbasis Linux dan teknologi Mozilla Gecko. Firefox OS adalah sistem operasi mobile yang bebas dari teknologi ekslusif saat ini menjadi platform yang kuat yang memberikan pengembang aplikasi kesempatan untuk menciptakan produk unggulan Selain itu, Firefox OS fleksibel dan cukup mampu membuat pengguna bahagia.

+

Untuk pengembang Web bagian yang paling penting untuk dipahami adalah bahwa seluruh antarmuka pengguna adalah aplikasi web, yang mampu menampilkan dan meluncurkan aplikasi Web lainnya. Modifikasi yang Anda buat ke antarmuka pengguna dan aplikasi yang Anda buat untuk berjalan di Firefox OS adalah halaman Web, meskipun dengan meningkatkan akses ke perangkat kerasa dan layanan mobile.

+

Anda dapat belajar bagaimana membangun dan memasang Firefox OS dengan mengikuti panduan praktis kami.

+

Persyaratan perangkat keras

+

Perangakat mobile berbasis ARM terbaru cukup kuat untuk mendukung proting Firefox OS. Bagian ini mencakup persyaratan perangkat  keras dasar serta fitur perangkat keras yang direkomendasikan.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KomponenMinimumRekomendasi
CPUARMv6Cortex A5 class atau lebih
+ ARMv7a dengan NEON
GPUAdreno 200 class atau lebih
ConnectivityWiFi
+ 3G
SensorsAccelerometer
+ Proximity
+ Ambient light
+ A-GPS
+

Untuk pengalaman pengguna yang baik, itu ide yang baik untuk memilih perangakat yang menawarkan profil warna seragam (Implementasi dengan graphics device driver) dan dukungan headphone untuk mematikan dan menyalakan dan untuk menghentikan dan memutar media. Fitur ini umumnya ada di kalangan smartphone modern.

+

Tips penggunaan

+

Bagian ini  memberikan beberapa tips yang akan membantu Anda menggunakan Firefox OS. Ini adalah penampung sampai kita memiliki dokumentasi penggunaan nyata.

+

Membuka Kunci telepone

+

Jika Anda membangun Firefox OS, pada saat dijalankan meminta kode pass untuk membuka kunci perangkat Anda, kode standar adalah 0000. Beberapa Firefox OS akan melakukan ini seraya kami mengembangkan dan menguki layar kunci.

+

Menangkap screenshot

+

Menangkap screenshot simpel dengan menekan tombol power dan home secara bersamaan. Gambar screenshot akan berada di /sdcard/screenshots pada perangkat Anda; Anda dapat mengaksesnya menggunakan aplikasi Galeri pada telepon Anda, juga.

+

Jika karena alasan tertentu tidak dapat bekerja, Anda juga dpaat melakukannya dari terminal Linux atau Mac OS X komputer yang memiliki sistem Firefox OS.

+
    +
  1. Pastikan Anda telah memasang aplikasi ffmpeg. +
      +
    1. Pada Mac, Jika Anda menggunakan, Anda dapat melakukan ini dengan sudo port install ffmpeg. untuk homebrew, jalankan brew install ffmpeg.
    2. +
    3. Pada Linux (Ubuntu/Debian), gunakan sudo apt-get install ffmpeg.
    4. +
    +
  2. +
  3. Sambungkan telepon ke komputer menggunakan kabel USB.
  4. +
  5. Arahkan telepon Anda kedalam situasi apapun yang ingin Anda screenshot.
  6. +
  7. cd ke direktori B2G/gaia
  8. +
  9. make screenshot
  10. +
  11. Anda sekarang memiliki screenshot bernama screenshot.png.
  12. +
+

Remote debugging dengan ADB

+

Untuk mengaktifkan USB Debugging via adb, buka aplikasi Pengaturan dan arahkan ke Informasi Pernagkat > Informasi Lebih Lanjut > Pengembang. Dari daftar, berikan tanda centang pada Remote Debugging. Terakhir, hubungkan perankat via USB dengan komputer Anda.

+

Tombol dan kontrol

+

sebuah perangkat Firefox OS memiliki sejumlah tombol fisik:

+
+
+ Tombol Home
+
+ Tombol ini umumnya berpusat dibawah layar. Menekannya akan mengembalikan Anda ke peluncur aplikasi. Menekannya secara lama membuka tampilan card switching; gesekan ke atas pada tampilan tersebut akan hilang.
+
+ Volume rocker kontrol
+
+ Pada sisi kiri adalah volume rocker; Menekan bagian atas dari rocker akan meningkatkan volume dan menekan bagian bawah akan menurunkan volume.
+
+ Tombol Power
+
+ Tombol power berada di pojok kanan atas perangkat.
+
diff --git a/files/id/archive/b2g_os/phone_guide/flame/index.html b/files/id/archive/b2g_os/phone_guide/flame/index.html new file mode 100644 index 0000000000..697980244f --- /dev/null +++ b/files/id/archive/b2g_os/phone_guide/flame/index.html @@ -0,0 +1,73 @@ +--- +title: Flame +slug: Archive/B2G_OS/Phone_guide/Flame +tags: + - B2G + - Firefox OS + - Flame + - NeedsTranslation + - TopicStub + - developer phone + - official reference device +translation_of: Archive/B2G_OS/Phone_guide/Flame +--- +

A picture of the Flame device, showing the Firefox OS homescreen containing several app icons.

+ +

The Flame device is the official reference device for developing, testing, and debugging Firefox OS and open web apps. This guide provides basic information about its hardware specifications as well as practical documentation specific to experimenting with, developing for, and testing of software compatible with this phone.

+ +

The Flame hardware offers a representative set of specs — including FWVGA display and dual-core processor — to help developers build great content and experiences. A stable hardware platform is also good for testers, making it easier to test and address specific software issues without having to worry about device model-specific bugs, etc.

+ +

If you have your phone in hand and want to start playing with it, developing and distributing apps, or contributing to the Firefox platform, the following links will also get you where you need to go:

+ + + +

If you’d like to find out more about updating the operating system, recovering it, pushing apps to it, or phone specs, you’ll find the information you need at the following two articles :

+ + + +

Get a device

+ +

Flame sales have come to an end. There are still opportunities left for Mozilla contributors to get free Flames, including the upcoming Foxtrot program. If you have questions about getting a device for development or testing, please reach out to Asa Dotzler on the #fxos channel on IRC.

+ +

Device specifications

+ +

You can find more of the device specifications listed on our Phone and device specs page.

+ +

Network

+ + + +

Hardware

+ + + +

See also

+ + diff --git a/files/id/archive/b2g_os/phone_guide/flame/updating_your_flame/index.html b/files/id/archive/b2g_os/phone_guide/flame/updating_your_flame/index.html new file mode 100644 index 0000000000..f3ca1ae59c --- /dev/null +++ b/files/id/archive/b2g_os/phone_guide/flame/updating_your_flame/index.html @@ -0,0 +1,411 @@ +--- +title: Updating your Flame +slug: Archive/B2G_OS/Phone_guide/Flame/Updating_your_Flame +translation_of: Archive/B2G_OS/Phone_guide/Flame/Updating_your_Flame +--- +
+

This article covers how to update the software on your Flame — including updating Firefox OS and pushing new apps to your phone — along with backing up your data, and other useful troubleshooting and testing information. Before starting to do any of this, you should make sure you have run through the Initial setup information.

+
+ +

Quick guide to updating your device

+ +

There is a lot of information in this article, so here we've included a quick start guide that takes you through the steps you need quickly to get your device updated. You can refer to the below sections for more detail if it is needed.

+ +

Full flash to the latest base image

+ +

This set of steps needs to be done before you do anything else to your phone (see {{anch("Base image")}} and {{anch("Base image installation")}} if you require more details.)

+ +
Prerequisites: Make sure you have adb and fastboot installed and available in your system's PATH (see Installing ADB and Fastboot.)
+ +
    +
  1. Download the latest base image —Base image v18D_nightly_v4to your computer.
  2. +
  3. On your Flame device, enable remote debugging by navigating to Settings > Developer and enabling the Debugging via USB option.
  4. +
  5. Connect your Flame to your computer via a USB cable.
  6. +
  7. Verify that the computer is connected to the device by typing this command: +
    adb devices  
    +
    + You should see something like the following: + +
    List of devices attached
    +94f7ce4c    device
    + If you don't see your device attached (no second line), then try unplugging and replugging the USB cable and trying again; also check that Debugging via USB is enabled on the phone as mentioned in step 2. If you get a message saying that adb could not be found, you probably haven't set your path correctly (see prerequisites.)
  8. +
  9. Extract the base image zip file and navigate to the new directory, using for example: +
    cd v18D_nightly_v4
    +
  10. +
  11. Run the flashing script by running the correct below command for your system +
    # Windows
    +flash.bat
    +
    +# Linux / OSX
    +./flash.sh
    +
  12. +
+ +
+

Note: if you don't see the right filename for your system, you can rename flash.bat or flash.sh back and forth as needed. The contents are the same.

+
+ +
+

Note: Verify the contents of the base image using the checksum below:

+ +
Checksum: SHA512(v18D_nightly_v4.zip)= 9105e29fd39da1ae487b01da4431a803d619d31482147b4383002b8a10268905fd444b108a438395a78d289cfe4e8fba10c3fb6b0d187f3535f027bf90c2391a Build id: 20150527010201
+
+ +

At this point you should be on the latest 2.5 base image, and be able to receive OTA updates.

+ +
+

Note: if you want to be on the very latest builds of flame (that have not been smoke tested), go to settings -> developer, scroll down to the bottom, and change the channel to nightly-latest.  Reboot the device, then go back to settings -> device info and check for updates.  You can update to the latest version without having to shallow flash.  For shallow flashing see the next section.

+
+ +

Update channel reset bug

+ +

As mentioned in {{bug(1217490)}}, some Firefox OS testers testing Firefox OS 2.5 latest OTA updates (on Flame, but also on other dogfooding devices) may find that when they install an OTA update, their update channel is reset to nightly, meaning that they won’t receive subsequent OTA updates coming through other channels. To avoid this, it is recommended that you set your  update channel to nightly-latest in the Firefox OS settings via WebIDE. To do this:

+ +
    +
  1. Plug your phone into your computer via USB (make sure Debugging via USB is set to ADB and DevTools in the Phone's Developer Settings)
  2. +
  3. Go to Firefox Desktop and open WebIDE.
  4. +
  5. Connect WebIDE to your phone by selecting it under USB Devices. Accept the connection prompt that appears on your phone.
  6. +
  7. Under Other on the right hand side of the WebIDE UI, select Device Settings.
  8. +
  9. Find app.update.channel in the list, and change the setting value in the corresponding textbox to nightly-latest.
  10. +
  11. Find app.update.channel.backup and change the setting value to nightly-latest if you want it to persist after further updates.
  12. +
+ +

Shallow Flash to the latest Firefox OS nightly (Gaia and Gecko)

+ +

This set of steps only needs to be done if you want to update to the VERY latest builds (see {{anch("Updating your Flame to a nightly build")}} if you require more details.)

+ +
Prerequisites: Windows users will need to install Cygwin, which provides a Linux-like environment on Windows. The instructions below include steps for how to automatically install the appropriate packages if you don't already have it installed.
+ +
 
+ +
    +
  1. Download the latest build from Mozilla Central.  Download both the b2g-XX.XX.en-US.android-arm.tar.gz and gaia.zip files.
  2. +
  3. All platforms: Download the shallow flash script in the same directory as the build files.
  4. +
  5. Windows users: Also download the shallow_flash.bat Windows script in the same directory. If you don't already have Cygwin installed, also download the installation file (you don't have to run it, the shallow_flash.bat script will use the installer to automatically configure the necessary packages).
  6. +
  7. In your terminal, cd into the directory you saved the files in and flash the builds to your phone using the following: +
    # Linux
    +./shallow_flash.sh --gaia=gaia.zip --gecko=b2g-XX.XX.en-US.android-arm.tar.gz
    +
    +# Mac
    +./shallow_flash.sh --gaia gaia.zip --gecko b2g-XX.XX.en-US.android-arm.tar.gz
    +
    +# Windows
    +# You could also double click the shallow_flash.bat icon (with the cogs) from Windows Explorer.
    +shallow_flash.bat
    +
  8. +
+ +

This process will flash gaia.zip and a single b2g-XX.XX.en-US.android-arm.tar.gz file onto your phone. The files will be sent to the device and it will reboot after the process completes.

+ +
+

Note : On Linux, if the script fails during flashing Gaia, you can try replacing full options by their shortened version to see if that helps. Replace --gaia=gaia.zip by -g gaia.zip and --gecko=b2g-XX.XX.en-US.android-arm.tar.gz by -G b2g-XX.XX.en-US.android-arm.tar.gz.

+
+ +

Updating & upgrading the Flame's software

+ +

We have two main "channels" of Firefox OS software version releases for the Flame phone:

+ + + +

Base Image

+ +

You can get recovery files and tools at the following storage locations:

+ +

Up-to-date (use these unless you have a good reason not to)

+ + + +
+

Note: You can find out what base image your device is running using the command adb shell getprop ro.bootloader. The version is the last four characters, with the last one then removed, prefixed by 'v' (e.g. L1TC000118D0 > v18D).

+
+ +
+

Important: When running a shallow or full flash, your phone data will be overwritten: you should therefore back up your data before updating! See the {{anch("Backing up and restoring your Flame data")}} section for more details.

+
+ +

Outdated

+ +

These base images are stable & production only.

+ + + +
+

Note: Using a locale with base image v188 produces a mixed UI with locale and English languages.

+
+ +
+

Note: Firefox OS images v180 and above are based on Android KK (Kitkat, 4.4); JB (Jellybean, 4.1–4.3) builds have now been discontinued and are no longer supported, so don't use anything older than v180.

+
+ +

Base Image installation

+ +

To install the base image on your device:

+ +
    +
  1. Make sure remote debugging is enabled on your Flame, using the Remote debugging/Debugging via USB option in the device's Developer settings (the option is different, depending on whether you have Firefox 1.3 and under, or Firefox 1.4+ installed).
  2. +
  3. Connect your Flame to your computer via a USB cable if it isn't already. Verify that the computer is connected to the device by running the adb devices command in a terminal.
  4. +
  5. Download the base image .zip file referenced above. Unzip it onto your Desktop.
  6. +
  7. Go into the directory you extracted the software into and run it: +
      +
    • On Windows, enter the directory in your command prompt, then run the flash.bat script using flash.bat (or double click the file in explorer).
      + Note: If flash.bat is missing, simply rename the flash.sh file to flash.bat, then run that. Make sure you have adb and fastboot installed and available on PATH.
    • +
    • On Linux / OSX, enter the directory in your terminal, then run the flash.sh script using ./flash.sh (previous instructions encouraged you to use sudo. Don't. It is really dangerous to use sudo with things you download from the Internet. If the flash script fails to see your device, please double-check that your udev rules are correct). If you do not see a flash.sh file, simply rename flash.bat to flash.sh first and then use the above command.
    • +
    +
  8. +
+ +
+

Note: If you get a "permission denied" error when running the above commands, your shell script probably doesn't have the right permissions. Running chmod +x flash.sh on it should solve this problem.

+
+ +
+

Note: If the flash script gets stuck at "< waiting for device >" while the display shows "ThunderSoft(R)", the script doesn't have permission to access the device while in fastboot mode. You need to setup the udev rules to give it access. Also USB 3 ports may not work well with fastboot and can be the cause of this problem.

+
+ +
+

Note: You are also welcome to build your own builds to install on the Flame: see Building and installing Firefox OS.

+
+ +

Font fix

+ +
+

Important: This step is only needed for base image v180.

+
+ +

After updating Gecko and Gaia to nightly with the v180 base image, there will be a mismatch between the fonts that Gecko and Gaia expects and what the base image provides (this has been fixed as of v188). To fix this, you have two choices:

+ + + +

Updating your Flame to a nightly build

+ +
+

Note: For the current build, Nightly development builds of Firefox OS do not support A-GPS, which may lead to slow performance of GPS functionality. We plan to resolve this in an updated future Nightly channel.

+
+ +
+

Important: When running a shallow or full flash, your phone data will be overwritten: you should therefore back up your data before updating! See the {{anch("Backing up and restoring your Flame data")}} section for more details.

+
+ +
    +
  1. Before updating your phone to a Nightly build you should flash the latest base image to make sure the underlying systems are up to date. Download a base image with the same or a higher version of Firefox OS than the version you intend to use in step 3 below and use it to update your device's software, as explained above.
  2. +
  3. Because the above step installs a fresh operating system on your device, you'll need to enable remote debugging on your Flame again, using the Remote debugging option in the device's Developer settings.
  4. +
  5. Next, choose a build to install (found on https://ftp.mozilla.org/pub/mozilla.org/b2g/nightly/). You'll want one of the following: + +
  6. +
  7. Pick a version and download both the b2g-XX.XX.en-US.android-arm.tar.gz and gaia.zip files. Save them inside a directory on your Desktop called something like fxos.
  8. +
  9. Download the shallow flash script and save it in the same directory as the above two files.
  10. +
  11. For Windows users: Also download the shallow_flash.bat windows script and install Cygwin, which provides a Linux-like command environment on Windows. You will need to install the default Cygwin base category plus the unzip package but shallow_flash.bat will do this for you if you download and copy the Cygwin setup*.exe to the same folder as the script.
  12. +
  13. +

    In your Terminal, cd into the directory you saved the files in and Flash the builds to your phone using the following:

    + +

    Linux:

    + +
    ./shallow_flash.sh --gaia=gaia.zip --gecko=b2g-XX.XX.en-US.android-arm.tar.gz
    +
    + +

    Mac:

    + +
    ./shallow_flash.sh --gaia gaia.zip --gecko b2g-XX.XX.en-US.android-arm.tar.gz
    + +

    Windows:

    + +

    Double click shallow_flash.bat (with the cogs icon) or run it from a command shell. It will flash gaia.zip and a single b2g-XX.XX.en-US.android-arm.tar.gz file.

    +
  14. +
+ +
+

Note: If your update fails with an error "Flashing out/target/product/flame/system.img failed because the image was too large.", you will need to update to the newest {{anch("Base Image","base image")}}, then try applying the nightly build again. This is because the system partition size has been updated (see {{Bug("1184980")}}.)

+
+ +
+

Note: If you get a "permission denied" error when running the above commands, your shell script probably doesn't have the right permissions. Running chmod +x shallow_flash.sh on it should solve this problem.

+
+ +
+

Note: A "shallow flash" updates Gecko and Gaia plus data directories, as opposed to a full flash, which updates Gecko/Gaia, but also the underlying Gonk layer and associated binaries particular to that device type. This is why it is a good idea to update to the official base image first, as suggested above, then shallow flash over the top of that, once you've got the Gonk/binary layer right.

+
+ +
+

Note: You can check the update status of each build on the Flame OTA status page.

+
+ +

Once the install procedure finishes the phone should reboot into the updated build and display the first time user workflow.

+ +

Switch to nightly update channel

+ +

In v2.2 you can change the Update channel from default to nightly under Developer settings.

+ +

Below is the older method, if you don't find that setting in your device.

+ +
    +
  1. Make sure remote debugging is enabled on your Flame, using the Remote debugging/Debugging via USB option in the device's Developer settings.
  2. +
  3. Download the change channel script: follow the link, press the Raw button, then use your browser's save functionality to save the page directly as change_channel.sh.
  4. +
  5. In your Terminal, cd into the directory you saved the script in and change the update channel on your phone using the following command:
    + +
    ./change_channel.sh -v nightly
    +
  6. +
  7. Once the phone reboots, check for updates by going into Settings > Device information > Check now.
  8. +
+ +
+

Note: This step isn't needed in newer versions of the Firefox OS software — you should just get OTA updates automatically.

+
+ +
+

Note: You can choose between several different update channels. Run "./change_channel.sh -h" to see the other channel options.

+
+ +

Fastboot mode

+ +

If flashing a new build to your phone fails to work, your phone may become unresponsive, leading to the phone rebooting in recovery mode. The recovery mode provides few options (Reboot, Update from adb, Wipe data, Wipe cache, and Update from sdcard). Unfortunately, selecting Update from adb triggers a sideload mode in which you cannot use the other adb commands. The adb sideload command would work but the various flash scripts rely on other adb commands.

+ +

You can force fastboot mode as follows:

+ +
    +
  1. Power off the phone (which may involve removing the battery in extreme cases...).
  2. +
  3. Plug in the USB cable.
  4. +
  5. Power the phone up again by pressing the Volume Down and Power buttons together.
  6. +
+ +

The phone should now display the text "FASTBOOT": it is in fastboot mode and is waiting for a USB connection. At this point, a USB-connected, computer with adb installed should see the phone listed when the fastboot devices command is run. Note that regular adb would not see the device — only fastboot sees it. In this mode, you can use the flash script to install the last base image as explained above. As the script does use both adb and fastboot commands, you may see some initial error and warnings from adb, but the device should be flashed properly at the end of the procedure.

+ +

Emergency download mode

+ +

If flashing a new build to your phone fails to work, your phone becomes unresponsive, and the phone cannot enter fastboot mode, you can use emergency mode for recovery. You'll need the provided emergency USB cable with the “Recovery Cable” red label on it and the Emergency Download Tool to enter this mode. For full instructions, see the Flame emergency rescue tool tutorial included in the download tool's files. Contact the device maker (flameservice [at] thundersoft.com) if you need any more technical support.

+ +

Emergency download tool dialog box as it is when it start.

+ +
+

Note: The tool provided is Windows-only.

+
+ +

Recovery mode

+ +

You can enter recovery mode to clear your phone data or manually update the firmware. There are two ways to enter this mode:

+ + + +

When in recovery mode, press the Volume up/down keys to move the selection highlight, and the Power key to select. Make sure you have your phone data (Contacts, SMS, etc.) backed up before clearing data, and your upgrade packages downloaded before updating.

+ +

Backing up and restoring your Flame data

+ +

When using a Flame, you won't want to lose your phone's contacts and other data while upgrading to a new build (as explained earlier in this article). To backup and restore data you can use our Backup and restore profile tool, which is contained in the B2G-flash-tool Git repo.

+ +
    +
  1. To use this, first open up your terminal/command line.
  2. +
  3. Clone the above repo (you'll need Git installed) using +
    git clone https://github.com/Mozilla-TWQA/B2G-flash-tool
    +
  4. +
  5. The tool is a Python file: backup_restore_profile.py. Make sure you have Python installed (2.7.x is probably best.) Linux and Mac systems should have this out of the box.
  6. +
  7. Enter the directory you just cloned using cd B2G-flash-tool.
  8. +
+ +
+

Note: When using this tool, you'll also need to make sure that your phone is connected via USB to your computer, and that ADB (see {{anch("Important steps to follow first")}} above) and Debugging via USB (in your device's Developer settings) are enabled.

+
+ +
+

Note: If you get a message complaining about lack of permissions to execute this file, cd into the directory where you saved the file, and run the following command:

+ +
chmod +x backup_restore_profile.py
+
+ +

Backing up data from your phone

+ +

Before backing up you should make sure your device is updated with the most recent OTA update. To do this, on your phone go to Settings app > Device Information > Check for updates > click Check Now. If there is an update available, you should shortly get a notification of an available update. Choose to install the update.

+ +

Now, in the directory where you saved the backup_restore_profile.py file, run the following:

+ +
python backup_restore_profile.py -b
+ +

This should save your device profile to a directory called mozilla-profile, in the same directory as the script is located.

+ +
+

Warning: by default, it does not save the internal sd card content. So files like photos or videos from the gallery app will not be saved. If you want to backup the sd card content, add the --sdcard option

+ +
python backup_restore_profile.py -b --sdcard
+
+ +

Restoring data to your phone

+ +

Before restoring you should again make sure your device is updated with the most recent OTA update. Go to Settings app > Device Information > Check for updates > click Check Now. If there is an update available, you should shortly get a notification of an available update. Choose to install the update.

+ +

In the directory where your mozilla-profile directory is located (see above section), run the following:

+ +
python backup_restore_profile.py -r
+ +
+

Note: You can get a list of all the options the tool supports by running python backup_restore_profile.py -h.

+
+ +

Pushing apps to your Flame

+ +

The App Manager and WebIDE tools make it easy to push apps to your phone, for testing, etc.

+ +

RAM adjustment

+ +

You can adjust the available RAM capacity to see how apps perform on Firefox OS phones with lower memory footprints.

+ +

This is accomplished by entering fastboot mode (install fastboot first, which is available on the same SDK page as ADB) and typing:

+ +
adb reboot bootloader
+fastboot oem mem [0|256-1024]
+ +

“0” is the memory automatically detected and “256-1024” is the number of megabytes. For example, if you want to adjust device RAM capacity to 512M, enter fastboot oem mem 512.

+ +

You'll need to then reboot your device for the settings to take effect. This can be done using:

+ +
fastboot reboot
+ +

The current memory size can be returned by entering fastboot mode and typing:

+ +
fastboot getvar mem
+
diff --git a/files/id/archive/b2g_os/phone_guide/index.html b/files/id/archive/b2g_os/phone_guide/index.html new file mode 100644 index 0000000000..bbfc5ecee3 --- /dev/null +++ b/files/id/archive/b2g_os/phone_guide/index.html @@ -0,0 +1,85 @@ +--- +title: Firefox OS phone guide +slug: Archive/B2G_OS/Phone_guide +tags: + - Firefox OS + - Landing + - NeedsTranslation + - Phones + - TopicStub +translation_of: Archive/B2G_OS/Phone_guide +--- +
+

This section contains developer information relevant to specific phones that run Firefox OS — both developer and consumer devices. We have general information available on Building and installing Firefox OS and Hacking Firefox OS, so please go there for information about building and installing the platform from scratch. Developers with specific phones in their possession may however find the following articles useful.

+
+ +

Developer phone information

+ +

The phones listed here are specifically geared towards developers wanting to experiment with Firefox OS, including developing apps and contributing to the operating system itself. As such, they typically have unlocked SIMs, system files, etc.

+ +
+
Flame
+
The Flame device is the official reference device for developing, testing, and debugging Firefox OS and open web apps, produced in partnership with T2Mobile.
+
Geeksphone
+
In this article we cover some basic tips on how to keep your Geeksphone up-to-date and how to tweak the system Gaia applications.
+
Nexus 5
+
This article provides information about using Firefox OS on a Nexus 5, including Flashing Firefox OS onto your device.
+
Nexus 4
+
This article provides information about using Firefox OS on a Nexus 4, including Flashing Firefox OS onto your device.
+
ZTE OPEN
+
This article contains information on the ZTE OPEN Firefox OS device.
+
ZTE OPEN C
+
The ZTE Open C is an updated ZTE-produced Firefox OS device, with higher end hardware and newer software.
+
+ +

Consumer phone information

+ +

The phones listed here are consumer models, so not ideal for developers wanting to hack on devices. However, might be still useful for developers looking for more technical information on these consumer models. For a more complete list of devices, see our Find Firefox OS near you page.

+ +
+
Alcatel One Touch Fire
+
Based on Firefox OS 1.3 and available in more than 5 countries.
+
Alcatel One Touch Pixi 3 (3.5)
+
High-end consumer smartphone, powered by Firefox OS 2.0, with a 2 megapixel camera.
+
Alcatel Onetouch Fire 2C 4020D
+
Based on Tarako Firefox OS (1.3T) and released in India.
+
Alcatel Onetouch Fire C
+
Based on Tarako Firefox OS (1.3T) and released in India.
+
Alcatel Onetouch Fire E
+
Available in 5 countries.
+
Cherry Mobile Ace
+
Based on Firefox OS 1.3T and available in the Philippines.
+
Fx0
+
First Firefox OS phone released in Japan, by KDDI.
+
Huawei Y300 II
+
Based on Firefox OS 1.1 and available in the Philippines and Mexico.
+
Intex Cloud FX
+
First Firefox OS Tarako phone released in India and based on Firefox OS 1.3T.
+
LG Fireweb
+
Based on Firefox OS 1.1 and available in Uruguay and Brasil.
+
Spice Firefox MI FX1
+
Based on Tarako Firefox OS (1.3T) and released in India.
+
Spice Firefox MI FX2
+
High-end consumer 3G smartphone powered by FirefoxOS 1.4 with a 2 megapixel camera, released in India.
+
Symphony GoFox F15
+
First Firefox OS Device to come with 3G video calling capability, launched in Bangladesh.
+
Zen U105 Fire
+
Based on Firefox OS Tarako, available in India.
+
ZTE Open II
+
Has a1.2 GHz dual core processor and a 2.0 MP Rear Camera, available in 7 countries.
+
Orange Klif
+
The Orange Klif is a 3G Smartphone, powered by Firefox OS 2.0, with a 2 megapixel camera. It is available in a number of African countries.
+
+ +

General Firefox OS information

+ +
+
Firefox OS phone data
+
In this article we list the various available Firefox OS phones along with information such as their code names, availability, and specific hardware features.
+
General device features
+
This page lists typical Firefox OS hardware features and minimum hardware requirements.
+
Troubleshooting
+
This article provides tips for resolving common problems you may have while using Firefox OS.
+
Best practices for open reference devices
+
A set of best practices that we believe should come highly recommended for any widely available open reference devices. All of the recent Firefox OS reference devices have followed these practices.
+
diff --git a/files/id/archive/b2g_os/platform/index.html b/files/id/archive/b2g_os/platform/index.html new file mode 100644 index 0000000000..ec17b4cd1d --- /dev/null +++ b/files/id/archive/b2g_os/platform/index.html @@ -0,0 +1,82 @@ +--- +title: The Firefox OS platform +slug: Archive/B2G_OS/Platform +translation_of: Archive/B2G_OS/Platform +--- +
+

The Firefox OS platform consists of many components. While you don't need to understand its architecture in order to build applications that run on Firefox OS, if you're working on developing or porting the platform — or are simply curious — the following documentation may be of interest to you.

+
+ + + + + + + +
+

Documentation about the Firefox OS platform

+
+
+ Firefox OS architecture overview
+
+ An overview of how Firefox OS is structured internally; this is primarily of interest to platform developers and people doing porting work.
+
+ Firefox OS apps architecture
+
+ An overview of the application model on Firefox OS.
+
+ Gaia
+
+ Documentation about Gaia, the user interface application for Firefox OS devices; this is a Web application running atop the Firefox OS software stack.
+
+ Gonk
+
+ Documentation about Gonk, the operating system layer underneath Gaia. This consists of a Linux kernel and a hardware abstraction layer to which Gecko communicates.
+
+ Gecko
+
+ Gecko is the layer of Firefox OS that provides the same open web standards implementation used by Firefox and Thunderbird, as well as many other applications.
+
+  Security
+
+ Documentation about security in Firefox OS; this includes topics about security devices from every perspective: for app developers, device integrators, and so forth.
+
+ Out of memory management on Firefox OS
+
+ This article explains how low memory situations are managed on Firefox OS, using the low memory killer and low memory notifications.
+
+ Feature support chart
+
+ A chart of which features are available in which types of Firefox OS builds.
+
+ Firefox OS settings list
+
+ A list of common setting names that can be used with the Settings API.
+
+

View All...

+
+

Getting help from the community

+

If you're working with Firefox OS, or developing applications you'd like to run on Firefox OS devices, there are community resources to help you!

+
    +
  • Consult the Boot to Gecko project forum: {{ DiscussionList("dev-b2g", "mozilla.dev.b2g") }}
  • +
+
    +
  • Ask your question on Mozilla's Boot to Gecko IRC channel: #b2g
  • +
+

Don't forget about the netiquette...

+
+ + +

Resources

+ +
+

 

diff --git a/files/id/archive/b2g_os/quickstart/aplikasi_pertama_kamu/index.html b/files/id/archive/b2g_os/quickstart/aplikasi_pertama_kamu/index.html new file mode 100644 index 0000000000..ecc95018a2 --- /dev/null +++ b/files/id/archive/b2g_os/quickstart/aplikasi_pertama_kamu/index.html @@ -0,0 +1,210 @@ +--- +title: Aplikasi Pertama Kamu +slug: Archive/B2G_OS/Quickstart/aplikasi_pertama_kamu +translation_of: Archive/B2G_OS/Quickstart/Your_first_app +--- +
+
+

Aplikasi Open web memberikan kemudahan kepada Pengembang web persis seperti apa yang mereka inginkan selama ini: lingkungan cross-platform yang didedikasikan untuk aplikasi yang diinstal dan dibuat hanya dengan menggunakan HTML, CSS, dan JavaScript saja - dengan Firefox OS sebagai yang pertama yang mendedikasikan platform Aplikasi Open web ini. Panduan ini bertujuan untuk membuat Anda belajar dan membangun aplikasi, dengan petunjuk arsitektur dasar dan petunjuk membangun Aplikasi sehingga Anda dapat membuat aplikasi besar berikutnya!

+
+

Jika Anda tidak ingin mengikuti panduan ini, Anda dapat men-download template aplikasi quick start kami. Cari tahu lebih banyak tentang apa ini, dengan membaca panduan Template aplikasi kami.

+

Struktur Aplikasi

+

Paket vs. Aplikasi yang dihost

+

Ada dua jenis aplikasi Open web yaitu: dikemas dan dihosting.

+ +

Kedua jenis aplikasi ini memerlukan file manifest yang valid. Ketika tiba saatnya Anda ingin untuk mendaftarkan aplikasi Anda di Firefox Marketplace, Anda akan meng-upload aplikasi Anda sebagai file .zip atau memberikan URL di mana aplikasi anda dihosting.

+
+

+
+

Dibuat dalam kemitraan dengan Treehouse: Periksa mereka!

+
+
+

Untuk tujuan panduan ini, Anda akan membuat aplikasi host yang akan tinggal di alamat localhost Anda. Setelah aplikasi Anda sudah siap untuk daftar di Firefox Marketplace, Anda dapat membuat keputusan untuk bundel sebagai aplikasi dikemas atau meluncurkannya sebagai aplikasi host.

+

Manifests Aplikasi

+

Every Firefox app requires a manifest.webapp file at the app root. The manifest.webapp file provides important information about the app, such as version, name, description, icon location, locale strings, domains the app can be installed from, and much more. Only the name and description are required. The simple manifest included within the app template is similar to the following:

+
{
+  "version": "0.1",
+  "name": "Open Web App",
+  "description": "Your new awesome Open Web App",
+  "launch_path": "/app-template/index.html",
+  "icons": {
+    "16": "/app-template/app-icons/icon-16.png",
+    "48": "/app-template/app-icons/icon-48.png",
+    "128": "/app-template/app-icons/icon-128.png"
+  },
+  "developer": {
+    "name": "Your Name",
+    "url": "http://yourawesomeapp.com"
+  },
+  "locales": {
+    "es": {
+      "description": "Su nueva aplicación impresionante Open Web",
+      "developer": {
+        "url": "http://yourawesomeapp.com"
+      }
+    },
+    "it": {
+      "description": "La tua nuova fantastica Open Web App",
+      "developer": {
+        "url": "http://yourawesomeapp.com"
+      }
+    }
+  },
+  "default_locale": "en"
+}
+
+

+
+

Made in partnership with Treehouse: Check them out!

+
+
+

 

+

A basic manifest is all you need to get started. For more details about manifests, read App Manifest.

+

App Layout & Design

+

Responsive design has become increasingly important as more screen resolutions become standard on different devices. Even if the main target of your app is mobile platforms such as Firefox OS, other devices will likely have access to it as well. CSS media queries allow you to adapt layout to device, as shown in this skeleton CSS example:

+
/* The following are examples of different CSS media queries */
+
+/* Basic desktop/screen width sniff */
+@media only screen and (min-width : 1224px) {
+  /* styles */
+}
+
+/* Traditional iPhone width */
+@media
+  only screen and (-webkit-min-device-pixel-ratio : 1.5),
+  only screen and (min-device-pixel-ratio : 1.5) {
+  /* styles */
+}
+
+/* Device settings at different orientations */
+@media screen and (orientation:portrait) {
+  /* styles */
+}
+@media screen and (orientation:landscape) {
+  /* styles */
+}
+

There are many JavaScript and CSS frameworks available to aid in responsive design and mobile app development (Bootstrap, etc.) Choose the framework(s) that best fit your app and development style.

+

Web APIs

+

JavaScript APIs are being created and enhanced as quickly as devices are. Mozilla's WebAPI effort brings dozens of standard mobile features to JavaScript APIs. A list of device support and status is available on the WebAPI page. JavaScript feature detection is still the best practice, as shown in the following example:

+
// If this device supports the vibrate API...
+if('vibrate' in navigator) {
+    // ... vibrate for a second
+    navigator.vibrate(1000);
+}
+

In the following example, the display style of a <div> is modified based on changes in the battery state of the device:

+
// Create the battery indicator listeners
+(function() {
+  var battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery,
+      indicator, indicatorPercentage;
+
+  if(battery) {
+    indicator = document.getElementById('indicator'),
+    indicatorPercentage = document.getElementById('indicator-percentage');
+
+    // Set listeners for changes
+    battery.addEventListener('chargingchange', updateBattery);
+    battery.addEventListener('levelchange', updateBattery);
+
+    // Update immediately
+    updateBattery();
+  }
+
+  function updateBattery() {
+    // Update percentage width and text
+    var level = (battery.level * 100) + '%';
+    indicatorPercentage.style.width = level;
+    indicatorPercentage.innerHTML = 'Battery: ' + level;
+    // Update charging status
+    indicator.className = battery.charging ? 'charging' : '';
+  }
+})();
+

In the code sample above, once you confirm that the Battery API is supported, you can add event listeners for chargingchange and levelchange to update the element's display. Try adding the following to the quickstart template, and see if you can get it working.

+

Check the WebAPI page frequently to keep up to date with device API statuses.

+

Install API functionality

+

In our sample quickstart app template, we've implemented an install button that you can click when viewing the app as a standard Web page, to install that site on Firefox OS as an app. The button markup is nothing special:

+
<button id="install-btn">Install app</button>
+

This button's functionality is implemented using the Install API (see install.js):

+
var manifest_url = location.href + 'manifest.webapp';
+
+function install(ev) {
+  ev.preventDefault();
+  // define the manifest URL
+  // install the app
+  var installLocFind = navigator.mozApps.install(manifest_url);
+  installLocFind.onsuccess = function(data) {
+    // App is installed, do something
+  };
+  installLocFind.onerror = function() {
+    // App wasn't installed, info is in
+    // installapp.error.name
+    alert(installLocFind.error.name);
+  };
+};
+
+// get a reference to the button and call install() on click if the app isn't already installed. If it is, hide the button.
+var button = document.getElementById('install-btn');
+
+var installCheck = navigator.mozApps.checkInstalled(manifest_url);
+
+installCheck.onsuccess = function() {
+  if(installCheck.result) {
+    button.style.display = "none";
+  } else {
+    button.addEventListener('click', install, false);
+  };
+};
+
+

Let's run through briefly what is going on:

+
    +
  1. We get a reference to the install button and store it in the variable button.
  2. +
  3. We use navigator.mozApps.checkInstalled to check whether the app defined by the manifest at http://people.mozilla.com/~cmills/location-finder/manifest.webapp is already installed on the device. This test is stored in the variable installCheck.
  4. +
  5. When the test is successfully carried out, its success event is fired, therefore installCheck.onsuccess = function() { ... } is run.
  6. +
  7. We then test for the existence of installCheck.result using an if statement. If it does exist, meaning that the app is installed, we hide the button. An install button isn't needed if it is already installed.
  8. +
  9. If the app isn't installed, we add a click event listener to the button, so the install() function is run when the button is clicked.
  10. +
  11. When the button is clicked and the install() function is run, we store the manifest file location in a variable called manifest_url, and then install the app using navigator.mozApps.install(manifest_url), storing a reference to that installation in the installLocFind variable. You'll notice that this installation also fires success and error events, so you can run actions dependent on whether the install happened successfully or not.
  12. +
+

You may want to verify the implementation state of the API when first coming to Installable web apps.

+
+

Note: Installable open web apps have a "single app per origin" security policy; basically, you can't host more than one installable app per origin. This makes testing a bit more tricky, but there are still ways around this, such as creating different sub-domains for apps, testing them using the Firefox OS Simulator, or testing the install functionality on Firefox Aurora/Nightly, which allows you to install installable web apps on the desktop. See FAQs about apps manifests for more information on origins.

+
+

WebRT APIs (Permissions-based APIs)

+

There are a number of WebAPIs that are available but require permissions for that specific feature to be enabled. Apps may register permission requests within the manifest.webapp file like so:

+
// New key in the manifest: "permissions"
+// Request access to any number of APIs
+// Here we request permissions to the systemXHR API
+"permissions": {
+    "systemXHR": {}
+}
+

The three levels of permission are as follows:

+ +

For more information on app permission levels, read Types of packaged apps. You can find out more information about what APIs require permissions, and what permissions are required, at App permissions.

+
+

It's important to note that not all Web APIs have been implemented within the Firefox OS Simulator.

+
+

Tools & Testing

+

Testing is incredibly important when supporting mobile devices. There are many options for testing installable open web apps.

+

Firefox OS Simulator

+

Installing and using the Firefox OS Simulator is the easiest way to get up and running with your app. After you install the simulator, it is accessible from the Tools -> Web Developer -> Firefox OS Simulator menu. The simulator launches with a JavaScript console so you can debug your application from within the simulator.

+

App Manager

+

The new kid on the block with regards to testing tools is called the App Manager. This tool allows you to connect desktop Firefox to a compatible device via USB (or a Firefox OS simulator), push apps straight to the device, validate apps, and debug them as they run on the device.

+

Unit Testing

+

Unit tests are extremely valuable when testing on different devices and builds. jQuery's QUnit is a popular client-side testing utility, but you can use any set of testing tools you'd like.

+

Installing Firefox OS on a Device

+

Since Firefox OS is an open source platform, code and tools are available to build and install Firefox OS on your own device. Build and installation instructions, as well as notes on what devices it can be installed on, can be found on MDN.

+

Dedicated Firefox OS developer preview devices are also available: read our Developer preview phone page for more information.

+

App Submission and Distribution

+

Once your app is complete, you can host it yourself like a standard web site or app (read Self-publishing apps for more information), or it can be submitted to the Firefox Marketplace. Your app's manifest will be validated and you may choose which devices your app will support (e.g. Firefox OS, Desktop Firefox, Firefox Mobile, Firefox Tablet). Once validated, you can add additional details about your app (screenshots, descriptions, price, etc.) and officially submit the app for listing within the Marketplace. Once approved, your app is available to the world for purchase and installation.

+

More Marketplace & Listing Information

+
    +
  1. Submitting an App to the Firefox OS Marketplace
  2. +
  3. Marketplace Review Criteria
  4. +
  5. App Submission Video Walkthrough
  6. +
+
diff --git a/files/id/archive/b2g_os/quickstart/index.html b/files/id/archive/b2g_os/quickstart/index.html new file mode 100644 index 0000000000..ebe1f7c220 --- /dev/null +++ b/files/id/archive/b2g_os/quickstart/index.html @@ -0,0 +1,49 @@ +--- +title: Build +slug: Archive/B2G_OS/Quickstart +tags: + - NeedsTranslation + - TopicStub +translation_of: Archive/B2G_OS/Quickstart +--- +
+

Quickstart information on coding open web apps.

+
+
+
+ Introduction to open web apps
+
+ What are open web apps? How they differ from regular web pages? Why is this significant? This article aims to answer these questions and more.
+
+ Your first app
+
+ This article takes you through the basic steps and additional knowledge on top of regular web development required to create installable open web apps.
+
+ Introduction to Firefox OS
+
+ An introduction to Firefox OS, Mozilla's new open web app-based mobile platform.
+
+ Introduction to manifests
+
+ An FAQ designed to answer any questions you may have about manifests, hosting apps, origins, and other such topics.
+
+ App development for web developers
+
+ If you're a web developer, how do open web apps differ from what you're used to? This article explains all.
+
+ App development for mobile developers
+
+ If you're a native mobile application developer, what advantages can open web apps bring to you, and how do they differ from what you are used to? Here are some ideas.
+
+ Developing app functionality
+
+ This page talks about the kinds of different functionality that you might want to build into your apps, with links to further information.
+
+ Payments
+
+ How do you build functionality to make people pay for installing your open web apps? Here is the lowdown.
+
+ App tools
+
+ Last for this section, we provide some links to more information on the tools available to help you develop great open web apps.
+
diff --git a/files/id/archive/b2g_os/simulator/index.html b/files/id/archive/b2g_os/simulator/index.html new file mode 100644 index 0000000000..6bc32a3c38 --- /dev/null +++ b/files/id/archive/b2g_os/simulator/index.html @@ -0,0 +1,120 @@ +--- +title: Firefox OS Simulator +slug: Archive/B2G_OS/Simulator +translation_of: Archive/B2G_OS/Simulator +--- +
+

Halaman ini menjelaskan Firefox OS Simulator untuk pengembang menargetkan Firefox OS 1.2 atau yang lebih baru. Jika Anda sedang mengembangkan aplikasi untuk Firefox OS 1.1, maka Anda harus memeriksa dokumentasi untuk Firefox OS 1.1 Simulator gantinya.

+
+ +

Firefox OS Simulator adalah versi dari lapisan yang lebih tinggi dari Firefox OS yang mensimulasikan perangkat Firefox OS, tapi berjalan pada desktop. Ini berarti bahwa dalam banyak kasus, Anda tidak perlu perangkat nyata untuk menguji dan men-debug aplikasi Anda. Ini berjalan di jendela ukuran yang sama sebagai perangkat Firefox OS, termasuk antarmuka pengguna Firefox OS dan built-in aplikasi, dan mensimulasikan banyak dari Firefox OS perangkat API.

+ +

 

+ +

Simulator ini dikemas dan didistribusikan sebagai Firefox add-on. Setelah Anda download dan diinstal di Firefox, Anda dapat menjalankannya, mendorong aplikasi untuk itu, dan melampirkan alat pengembang untuk itu menggunakan App Manajer alat atau WebIDE.

+ +

Instalasi

+ +

Untuk menginstal simulator, menggunakan WebIDE ini Mengelola penambahan Komponen panel (tersedia sebagai bagian dari Firefox 34 dan seterusnya). Beberapa versi yang tersedia, dan Anda disarankan untuk menginstal mereka semua, untuk fleksibilitas maksimum.

+ +
+

Dimulai dengan Firefox 43, tentang: halaman addons mungkin menampilkan peringatan tentang addon Anda menjadi unsigned. Simulator yang benar ditandatangani pada waktu menginstal, namun mereka kemudian dimodifikasi sehingga muncul "rusak". Mereka akan terus berjalan dengan sukses meskipun pesan peringatan ini. Rinciannya di bug 1.197.262.

+
+ +

Untuk memulai Simulator, Anda memilih dari daftar runtime WebIDE ini. Untuk lebih jelasnya, lihat petunjuk pada dokumentasi WebIDE. Setelah menjalankan Simulator, Anda dapat mendorong aplikasi untuk itu dan debug mereka menggunakan WebIDE, seperti yang Anda bisa dengan perangkat nyata.

+ +

Jika Anda menggunakan Manajer App (alat tua tersedia sebelum WebIDE), Anda dapat menginstal simulator melalui tombol berikut:

+ +

Install Simulator

+ +

Simulator UI

+ +

Simulator muncul sebagai jendela terpisah, berukuran sehingga area layar simulasi adalah 320x480 piksel. Untuk mensimulasikan peristiwa sentuhan Anda dapat mengklik tombol mouse dan tarik sambil memegang tombol ke bawah. Jadi dengan mengklik dan menyeret kanan-ke-kiri dari Home Screen, Anda akan melihat aplikasi built-in, serta setiap aplikasi yang telah ditambahkan:

+ +

+ +

Simulator ini memiliki dua tombol di toolbar di bagian bawah:

+ + + +

Emulasi kartu SD

+ +

Dalam Simulator kartu SD perangkat dipetakan ke "fake-sdcard" direktori di profil Simulator ini, yang itu sendiri terletak di dalam "ekstensi" direktori di bawah profil Firefox yang Simulator diinstal. Sebagai contoh:

+ +
/path/to/Firefox/Profiles/Firefox-profile-name/extensions/fxos_2_2_simulator@mozilla.org/profile/fake-sdcard
+ +

File membaca atau menulis menggunakan getDeviceStorage API akan muncul di sini.

+ +

Sebelum versi 2.2 dari Simulator, Anda harus menciptakan "palsu-sdcard" direktori secara manual untuk bekerja. Dari 2,2 dan seterusnya, "palsu-sdcard" direktori dibuat untuk Anda secara otomatis.

+ +

Juga dari versi 2.2 dan seterusnya, jika Anda menjalankan Simulator dari baris perintah Anda dapat menentukan direktori yang berbeda dengan melewati --storage-path option.

+ +

.

+ +
Catatan: ini sebagian besar dimaksudkan untuk pengujian API. Musik akan dibaca tidak dari "palsu-sdcard" direktori, tapi dari sistem anda ~/Music gambar dari ~/Pictures video dari ~/Videos Download pergi ke ~/Downloads user-dirs.dirs redefinitions didukung.
+ +

Keterbatasan Simulator

+ +

Perhatikan bahwa Firefox OS Simulator bukan simulasi sempurna.

+ +

Keterbatasan hardware

+ +

Terlepas dari ukuran layar, Simulator tidak mensimulasikan keterbatasan perangkat keras dari perangkat Firefox OS seperti memori yang tersedia atau kecepatan CPU.

+ +

Codec audio / video

+ +

Codec berikut tergantung pada decoding hardware-accelerated dan karena itu belum didukung:

+ + + +

Ini berarti tidak mungkin untuk menggunakan Simulator untuk pemutaran video tes di aplikasi dan di website seperti Youtube yang mengandalkan codec ini.

+ +

API yang tidak didukung

+ +

API tertentu yang bekerja pada perangkat tidak akan bekerja pada Simulator, umumnya karena hardware pendukung tidak tersedia pada desktop. Kami telah menerapkan simulasi untuk beberapa API seperti geolocation, dan berharap untuk menambahkan lebih banyak dalam rilis mendatang. Namun, saat ini API tidak didukung. Menggunakan mereka mungkin melemparkan kesalahan atau hanya mengembalikan hasil yang salah:

+ + + +

 

+ +

Mendapatkan bantuan

+ +

Jika Anda memiliki pertanyaan, mencoba meminta kami pada daftar dev-pengembang-alat mailing atau #devtools pada irc.mozilla.org.

+ +

Cara mengaktifkan verbose logging

+ +

Anda dapat melihat pesan login dari aplikasi Anda di Web Console, yang dapat Anda melampirkan ke aplikasi Anda menggunakan WebIDE. Jika Anda ingin menangkap pesan awal terjadi selama startup aplikasi, sebelum konsol akan terhubung dan bekerja, Anda dapat mengaktifkan verbose logging di Simulator.

+ +

Kunjungi about: config dan menciptakan preferensi baru. Nama preferensi yang berbeda untuk setiap versi Simulator:

+ + + +

Set ke nilai string "semua", dan menonaktifkan, kemudian mengaktifkan kembali, add-on di Add-on manajer. Sekarang pesan tambahan tentang operasi Simulator akan muncul di Browser Console.

+ +

Membangun Simulator

+ +

Jika Anda ingin menguji patch ke Gecko atau Gaia kode yang Simulator mengandung, Anda mungkin tertarik dalam memodifikasi simulator untuk menggunakan kustom Gecko membangun atau profil Gaia. Atau, Anda dapat membangun Simulator baru dari checkout Gecko Anda.

+ +

Alternatif

+ +

Berbagai cara untuk menjalankan Gaia - termasuk daftar mereka dalam rangka kemudahan untuk menjalankan dan ketertiban kedekatan membalikkan untuk produk dikirim (sesuai dengan itu, Firefox OS Simulator paling mudah tapi terjauh.

diff --git a/files/id/archive/b2g_os/using_the_app_manager/index.html b/files/id/archive/b2g_os/using_the_app_manager/index.html new file mode 100644 index 0000000000..39a43a9762 --- /dev/null +++ b/files/id/archive/b2g_os/using_the_app_manager/index.html @@ -0,0 +1,233 @@ +--- +title: Using the App Manager +slug: Archive/B2G_OS/Using_the_App_Manager +translation_of: Archive/B2G_OS/Using_the_App_Manager +--- +
+

The App Manager is a new tool available in Firefox for Desktop, which provides a number of useful tools to help you test, deploy and debug HTML5 web apps on Firefox OS phones and the Firefox OS Simulator, directly from your browser.

+
+ +

{{EmbedYouTube("z1Bxg1UJVf0")}}

+ +

The App Manager is composed of:

+ + + +

Quick setup:

+ +

This section is designed to get you up and running as soon as possible; if you need some more detail please skip forward to the {{ anch("Device and system configuration") }} section and start reading from there.  Also see the {{ anch("Troubleshooting") }} section for help if you are having trouble.

+ +
    +
  1. Make sure you have Firefox Desktop 26+ installed
  2. +
  3. Open the App Manager (in the URL bar, type about:app-manager)
  4. +
  5. If you don't have a real device: +
      +
    1. Install the Firefox OS Simulator
    2. +
    3. In App Manager's bottom toolbar, click on Start Simulator, then click on the name of the installed simulator, which should appear there.
    4. +
    +
  6. +
  7. If you have a real device: +
      +
    1. Make sure your device is running Firefox OS 1.2+
    2. +
    3. In the Settings of your device, disable Screen Lock (Settings > Screen Lock) and enable Remote Debugging (Settings > Device information > More information > Developer)
    4. +
    5. Install the ADB Helper add-on in Firefox Desktop
    6. +
    7. Connect your device to your machine via a USB cable
    8. +
    9. You should see the name of your device in the App Manager's bottom bar. Click on it.
    10. +
    +
  8. +
  9. The bottom bar should show "Connected to: xxx"
  10. +
  11. Click on the Apps panel and add an app (packaged or hosted)
  12. +
  13. The Refresh button validates your app and installs it on the Simulator/Device
  14. +
  15. The Debug button connects the developer tools to the running app
  16. +
+ +

Device and system configuration

+ +

The first thing you'll need to do when using the App Manager is make sure your system and phone are set up correctly. This section will run thrugh all the steps required.

+ +

Firefox 1.2+ required

+ +

Make sure your device is running Firefox OS 1.2/Boot2Gecko 1.2 or higher. To check which version of Firefox OS the device is runing, go to Settings > Device Information > Software.

+ +

If you don't have a high enough version installed, depending on what phone you have you will need to either install an available nightly build of Firefox 1.2+, or configure and build it yourself from source.

+ +

Builds available:

+ + + +

To build your own Firefox OS 1.2+ distribution, follow the instructions located at Building and installing Firefox OS, starting with Firefox OS build prerequisites.

+ +

Remote debugging

+ +

Next, you need to enable remote debugging in Firefox OS. To do so, go to Settings > Device information > More information > Developer and check the Remote Debugging checkbox.

+ +

ADB or ADB helper

+ +

The process uses the Android Debug Bridge (ADB) to handle the device-computer connection and communication. There are two options for running ADB:

+ + + +
+

Note: There's no need to run this command if you installed the ADB Helper Add-on.

+
+ +

Connecting your device to the App Manager

+ +

With all your configuration done, it's now time to plug your device into your computer and start the App Manager:

+ +
    +
  1. Plug the device into your computer via USB.
  2. +
  3. Disable Screen lock on your device by going to Settings > Screen Lock and unchecking the Lock Screen checkbox. This is a good idea because when the screen gets locked, the phone connection gets lost, meaning it is no longer available for debugging.
  4. +
  5. Start the App Manager — In Firefox Desktop select the Tools > Web Developer > App Manager menu option, or type about:app-manager in the URL bar.
  6. +
  7. At the bottom of the App Manager tab, you will see a connection status bar (see screenshot below). You should be able to connect your device by clicking the "Connect to localhost:6000" button.
  8. +
  9. If this works successfully, a prompt should appear on your device: "An incoming request to permit remote debugging connection was detected. Allow connection?". Tap the OK button (You may also have to press the power button on the phone so you can see the prompt.) The connection status bar should update to say "Connected to B2G", with a Disconnect button available to press if you want to cancel the connection.
  10. +
+ +

+ +
+

Note that the other controls in the connection status bar allow you to connect a simulator to the App Manager, which we cover in the next section, below, and change the port that the connection happens on. If you change the port, you'll also need to enable port forwarding for this port as well, as instructed in the {{anch("Enable port forwarding")}} section, above.

+
+ +

Using a Firefox OS Simulator Add-on

+ +

If you haven't got a real device available to use with App Manager, you can still try it out using a Firefox OS Simulator Add-on. To start off, install the appropriate simulator for your operating system:

+ +

Install Simulator

+ +
+

Note that currently there is only a Firefox OS 1.2 simulator available, although more may appear in the future.

+
+ +

Once you've installed the simulator, you need to go to the connection status bar at the bottom of the App Manager tab, and click the "Start simulator" button. Three buttons will appear:

+ + + +

Apps panel

+ +

Now everything is working, let's review the functionality available inside the App Manager, starting with the Apps Panel. From here, you can import an existing app to push onto your device and debug:

+ + + +

Information about your app should appear on the right hand side of the window, as seen below:

+ +

+ +

Clicking on "Update" will update (install) the app on the device. Clicking on "debug" will connect a toolbox to the app, allowing you to debug its code directly:

+ +

+ +
+

Note: You'll enjoy playing around with the toolbox — try altering the DOM, CSS etc. and you'll see the updates reflected on the device in realtime. Such updates will be saved on the installed app code; you'll see them next time you open the app on the device.

+
+ +

If an app was not added successfully — for example if the URL was incorrect, or you selected a packaged app folder — an entry will be added to the page for this app, but this will include error information.

+ +

+ +

You can also delete an app from this view, by hovering over the App name/description on the left of the window, and pressing the "X" button that appears in each case. This however doesn't remove the app from the device. To do that you need to manually remove the app using the device itself.

+ +

Device panel

+ +

The Device tab displays information about the connected device. From the "Installed Apps" window, apps on the device can be started and debugged.

+ +

+ +
+

Note: Certified Apps are not listed by default. See how to debug certified apps.

+
+ +

The "Permissions" window shows the required priviledges for different Web APIs on the current device:

+ +

+ +

Finally, you can take a screenshot of the current device display by clicking the "Screenshot" button. The screenshot appears in a new tab on Firefox, and from there you can save or discard it as you wish.

+ +

Debugging Certified Apps

+ +

Currently only devices running a development build of Firefox OS 1.2 are capable of debugging certified apps. If you have a development build, you can enable certified app debugging by changing the pref devtools.debugger.forbid-certified-apps to false in your profile. To do this, follow the steps below:

+ +
    +
  1. +

    On your computer, enter the following command in Terminal/console to enter your device's filesystem via the shell:

    + +
    adb shell
    + +

    Your prompt should change to root@android.

    +
  2. +
  3. +

    Next, stop B2G running using the following command:

    + +
    stop b2g
    +
  4. +
  5. +

    Navigate to the following directory:

    + +
    cd /data/b2g/mozilla/*.default/
    +
  6. +
  7. +

    Here, update the prefs.js file with the following line:

    + +
    echo 'user_pref("devtools.debugger.forbid-certified-apps", false);' >> prefs.js
    +
  8. +
  9. +

    After you've finished editing and saving the file, start B2G again using the following command:

    + +
    start b2g
    +
  10. +
  11. +

    Exit the android filesystem using the exit command; this will return you to your normal terminal prompt.

    +
  12. +
  13. +

    Next, reconnect to the App Manager and you should see certified apps appear for debugging.

    +
  14. +
+ +
+

Note: If you want to add this preference to your Gaia build you can run make DEVICE_DEBUG=1 reset-gaia.

+
+ +

Troubleshooting

+ +

If the device is not recognized:

+ + + +

Can't connect your device to the App Manager or start the simulator? Let us know or file a bug.

diff --git a/files/id/archive/css3/index.html b/files/id/archive/css3/index.html new file mode 100644 index 0000000000..0c5eae08d5 --- /dev/null +++ b/files/id/archive/css3/index.html @@ -0,0 +1,972 @@ +--- +title: CSS3 +slug: Archive/CSS3 +translation_of: Archive/CSS3 +--- +

CSS3 merupakan perubahan terakhir dari bahasa Cascading Style Sheets dan bertujuan untuk perpanjangan dari CSS2.1. Menghadirkan banyak  catatan yang lama dinantikan, seperti di seputar lingkaran sudut, bayangan, gradients, transitions or animations, sama halnya pada layout baru multi-columns (beberapa kolom), flexible box (kemudahan tampilan) atau grid layouts. Bagian bagian pengalaman vendor-prefixed (penyedia-memperbaharui) dan kemungkinan yang lainnya dihilangkan dalam lingkungan pembuatan, atau digunakan dengan berlebihan menyebabkan keduanya syntax (penulisan) and semantics (bentuk penulisan) dapat berubah kemudian.

+ +

Modul and Proses Standarisasi

+ +

CSS Tingkat 2 diperlukan 9 tahun, dari Agustus 2002 sampai Juni 2011 yang kaya status rekomendasi. Ini merupakan tindakan nyata bahwa featur bagian kedua kembali didasarkan pada spesifikasi yang menyeluruh. Dalam melengkapi percepatan featur standarisasi tanpa gangguan, the CSS Working Group of the W3C (Pekerjaan Group CSS W3C), dalam sebuah bagian mereferensi pada Beijing doctrine, CSS dibagi dalam komponen komponen lebih kecil disebut modules . Masing masing modul sekarang ini merupakan sebuah bagian yang berdiri sendiri dari bahasa dan bergerak pada standarisasi percepatannya sendiri. Selagi beberapa modul telah menjadi rekomendasi W3C, yang lainnya masih merupakan bagian yang baru dalam rancangan atau draft pekerjaan. Modul modul baru juga ditambahkan ketika dibutuhkan pengidentifikasin baru.

+ +

CSS Modules and Snapshots as defined since CSS3 Secara bentukan, tidak ada uraian standar CSS. Masing masing modul dijadikan standar secara independen. Standar CSS terdiri dari CSS2.1 perubahan and diperpanjang dengan modul yang lengkap. Seluruhnya tidak diperlukan pada angka yang sama. Di tiap tiap titik waktu, sebuah snapshot (tampilan) dari standar CSS dapat digambarkan, daftar CSS2.1 dan modul saat ini.

+ +

Konsorsium W3C secara priode dipublikasikan yang menampilkan, seperti dalam tahun 2007 atau 2010.

+ +

Meski hari ini tanpa modul dengan tingkat yang lebih tinggi dari standarisasi CSS3, ini dapat berubah ke depannya. Beberapa modul, seperti Selectors 4 or CSS Borders and Backgrounds Level 4 telah mempunyai sebuah rancangan atau draft editor, meski mereka belum diperkaya dengan publikasi awal status Draft atau Rancangan Pekerjaan.

+ +

Status Modul CSS

+ +

Stabilitas Modul

+ +

Sedikitnya modul CSS telah stabil secara bersamaan dan telah kaya dari satu atau tiga tingkatan rekomensasi dari CSSWG: Rekomendasi Kandidat, Proposal Rekomendasi atau Rekomendasi. Ini dapat digunakan tanpa sebelum perbaikan dan merupakan kestabilan yang baik, meski sedikitnya featur dapat dihilangkan pada Tingkat Kandidat Rekomendasi.

+ +

Perpanjangan modul modul ini dan perubahan CSS2.1 spesifikasi yang mana membangun inti dari spesifikasi. Bersamaan dengan itu, mereka adalah tampilan sekarang dari spesifikasi CSS.

+ + + + + + + + + + + +
{{ SpecName("CSS3 Colors", "", "") }}{{ Spec2("CSS3 Colors") }} since June 7th, 2011
+

Adds the {{ cssxref("opacity") }} property, and the hsl(), hsla(), rgba() and rgb() functions to create {{cssxref("<color>")}} values. It also defines the currentColor keyword as a valid color.

+ +

The transparent color is now a real color (thanks to the support for the alpha channel) and is a now an alias for rgba(0,0,0,0.0) .

+ +

It deprecates the system-color keywords that shouldn't be used in a production environment anymore.

+
+ + + + + + + + + + + +
{{ SpecName("CSS3 Selectors", "", "") }}{{ Spec2("CSS3 Selectors") }} since September 29th, 2011
+

Adds:

+ +
    +
  • Substring matching attribute selectors, E[attribute^="value"], E[attribute$="value"], E[attribute*="value"] .
  • +
  • New pseudo-classes: {{ cssxref(":target") }}, {{ cssxref(":enabled") }} and {{ cssxref(":disabled") }}, {{ cssxref(":checked") }}, {{ cssxref(":indeterminate") }}, {{ cssxref(":root") }}, {{ cssxref(":nth-child") }} and {{ cssxref(":nth-last-child") }}, {{ cssxref(":nth-of-type") }} and {{ cssxref(":nth-last-of-type") }}, {{ cssxref(":last-child") }}, {{ cssxref(":first-of-type") }} and {{ cssxref(":last-of-type") }}, {{ cssxref(":only-child") }} and {{ cssxref(":only-of-type") }},{{ cssxref(":empty") }}, and {{ cssxref(":not") }}.
  • +
  • Pseudo-elements are now characterized by two colons rather than one: :after becomes {{ cssxref("::after") }}, :before becomes {{ cssxref("::before") }}, :first-letter becomes {{ cssxref("::first-letter") }}, and :first-line becomes {{ cssxref("::first-line") }}.
  • +
  • The new general sibling combinator ( h1~pre ).
  • +
+
+ +

The next iteration of the Selectors specification is already in progress, though it still hasn't reached the First Public Working Draft stage.

+ + + + + + + + + + + +
{{ SpecName("CSS3 Namespaces", "", "") }}{{ Spec2("CSS3 Namespaces") }} since September 29th, 2011
+

Adds the support for the XML Namespaces by defining the notion of CSS qualified name, using the ' | ' syntax and adding the {{ cssxref("@namespace") }} CSS at-rule.

+
+ + + + + + + + + + + +
{{ SpecName("CSS3 Media Queries", "", "") }}{{ Spec2("CSS3 Media Queries") }} since June 19th, 2012
+

Extends the former media type ( print, screen, ) to a full language allowing queries on the device media capabilities like only screen and (color) .

+ +

Media queries are not only used in CSS document but also in some attributes of HTML Elements, like the {{ htmlattrxref("media","link") }} attribute of the {{ HTMLElement("link") }} element.

+
+ +

The next iteration of this specification is in the work, allowing to tailor a Web site regarding the input methods available on the user agent, with new media features like hover or pointer. Detection of EcmaScript support, using the script media features is also proposed.

+ + + + + + + + + + + +
{{ SpecName("CSS3 Style", "", "") }}{{ Spec2("CSS3 Style") }} since November 7th, 2013
Formally defines the syntax of the content of the HTML style global attribute.
+ + + + + + + + + + + +
{{ SpecName("CSS3 Backgrounds", "", "") }}{{ Spec2("CSS3 Backgrounds") }}
+

Adds:

+ +
    +
  • Support, on backgrounds, for any type of {{cssxref("<image>")}}, and not only for uri() defined ones.
  • +
  • Support for multiple background images.
  • +
  • The {{ cssxref("background-repeat") }} space and round values, and for the 2-value syntax of this CSS property.
  • +
  • The {{ cssxref("background-attachment") }} local value.
  • +
  • The CSS {{ cssxref("background-origin") }}, {{ cssxref("background-size") }}, and {{ cssxref("background-clip") }} properties.
  • +
  • Support for curved border corners, with the CSS {{ cssxref("border-radius") }}, {{ cssxref("border-top-left-radius") }}, {{ cssxref("border-top-right-radius") }}, {{ cssxref("border-bottom-left-radius") }}, and {{ cssxref("border-bottom-right-radius") }} properties.
  • +
  • Support for the use of an {{cssxref("<image>")}} as the border with the CSS {{ cssxref("border-image") }}, {{ cssxref("border-image-source") }}, {{ cssxref("border-image-slice") }}, {{ cssxref("border-image-width") }}, {{ cssxref("border-image-outset") }}, and {{ cssxref("border-image-repeat") }} properties.
  • +
  • Support for shadows of the element with the CSS {{ cssxref("box-shadow") }} property.
  • +
+
+ +

The CSS4 iteration of the Backgrounds and Borders specification is already in progress, though it still hasn't reached the First Public Working Draft stage, it plans to add the ability to clip a border (with the CSS {{ cssxref("border-clip") }}, {{ cssxref("border-clip-top") }}, {{ cssxref("border-clip-right") }}, {{ cssxref("border-clip-bottom") }}, and {{ cssxref("border-clip-left") }} properties) or to control the shape of the border in a corner (using the CSS {{ cssxref("border-corner-shape") }} property).

+ + + + + + + + + + + +
{{ SpecName("CSS3 Multicol", "", "") }}{{ Spec2("CSS3 Multicol") }}
Adds support for easy multi-column layouts using the CSS {{ cssxref("columns") }}, {{ cssxref("column-count") }}, {{ cssxref("column-fill") }}, {{ cssxref("column-gap") }}, {{ cssxref("column-rule") }}, {{ cssxref("column-rule-color") }}, {{ cssxref("column-rule-style") }}, {{ cssxref("column-rule-width") }}, {{ cssxref("column-span") }}, {{ cssxref("column-width") }}, {{ cssxref("break-after") }}, {{ cssxref("break-before") }}, and {{ cssxref("break-inside") }}.
+ + + + + + + + + + + +
{{ SpecName("CSS3 Speech", "", "") }}{{ Spec2("CSS3 Speech") }}
Defines the speech media type, an aural formatting model and numerous properties specific for speech-rendering user agents.
+ + + + + + + + + + + +
{{ SpecName("CSS3 Images", "", "") }}{{ Spec2("CSS3 Images") }}
+

Defines the {{cssxref("<image>")}} data type.

+ +

Extends the url() syntax to support image slices using media fragments.

+ +

Adds:

+ +
    +
  • The dppx unit to the {{cssxref("<resolution>")}} data type.
  • +
  • The image() function as a more flexible alternative to url() to define an image from an url.
    + At risk : due to insufficient browser support, standardization of the image() function may be postponed to the next iteration of this module .
  • +
  • Support for linear-gradient(), repeating-linear-gradient(), radial-gradient() and repeating-radial-gradient().
  • +
  • The ability to define how a replaced element should fit in its element, using the CSS {{ cssxref("object-fit") }} property.
    + At risk : due to insufficient browser support, standardization of the {{ cssxref("object-fit") }} and property may be postponed to the next iteration of this module .
  • +
  • The ability to override the resolution and orientation of an external image using the CSS {{ cssxref("image-resolution") }} and {{ cssxref("image-orientation") }} properties.
    + At risk : due to insufficient browser support, standardization of the {{ cssxref("image-resolution") }} and {{ cssxref("image-orientation") }} properties may be postponed to the next iteration of this module .
  • +
+
+ +

The CSS Image Values and Replaced Content Level 4 which will supersede CSS Image Level 3 is in development and is a {{Spec2("CSS4 Images")}}.

+ + + + + + + + + + + +
{{ SpecName("CSS3 Values", "", "") }}{{ Spec2("CSS3 Values") }}
+

Makes initial and inherit keywords usable on any CSS property.

+ +

Formally defines the CSS data types of CSS 2.1, that were implicitely defined by their grammar token and some textual precisions.

+ +

Adds:

+ +
    +
  • Definition for new font-relative length units: rem and ch .
  • +
  • Definition for viewport-relative length units: vw, vh, vmax, and vmin .
  • +
  • Precision about the real size of the absolute length units, which are not really absolute, but defined in relation with the reference pixel .
  • +
  • Definition for {{ cssxref("<angle>") }}, {{cssxref("<time>")}}, {{cssxref("<frequency>")}}, {{cssxref("<resolution>")}}.
  • +
  • Normative value to the definition of {{cssxref("<color>")}}, {{cssxref("<image>")}}, and {{ cssxref("<position>") }}.
  • +
  • Definition for the {{ cssxref("calc", "calc()") }}, {{ cssxref("attr", "attr()")}}, and toggle() functional notations.
    + At risk: due to insufficient browser support, standardization of the calc(), attr(), and toggle() functional notations may be postponed to the next iteration of this module.
  • +
+
+ +

Several types definition, like <ident> and <custom-ident>, have been deferred to CSS Values and Units Module Level 4.

+ + + + + + + + + + + +
{{ SpecName("CSS3 Flexbox", "", "") }}{{ Spec2("CSS3 Flexbox") }}
Add a flexbox layout to the CSS {{ cssxref("display") }} property and several new CSS properties to control it: {{ cssxref("flex") }}, {{ cssxref("flex-align") }}, {{ cssxref("flex-direction") }}, {{ cssxref("flex-flow") }}, {{ cssxref("flex-item-align") }}, {{ cssxref("flex-line-pack") }}, {{ cssxref("flex-order") }}, {{ cssxref("flex-pack") }}, and {{ cssxref("flex-wrap") }}.
+ + + + + + + + + + + +
{{ SpecName("CSS3 Conditional", "", "") }}{{ Spec2("CSS3 Conditional") }}
Adds features for conditional processing of parts of style sheets, conditioned on capabilities of the browser or the document the style sheet is being applied to. It consists mainly in allowing nested at-rules inside {{ cssxref("@media") }} and the adding of a new CSS at-rule, {{ cssxref("@supports") }}, and a new DOM method {{domxref("CSS.supports()")}}.
+ + + + + + + + + + + +
{{ SpecName("CSS3 Text Decoration", "", "") }}{{ Spec2("CSS3 Text Decoration") }}
+

Extends:

+ +
    +
  • the CSS {{ cssxref("text-decoration") }} property by making it a shorthand for the CSS {{ cssxref("text-decoration-line") }}, {{ cssxref("text-decoration-color") }}, and {{ cssxref("text-decoration-style") }} properties. And adds the {{ cssxref("text-decoration-skip") }}, and {{ cssxref("text-underline-position") }} properties.
  • +
+ +

Adds:

+ +
    +
  • Support for East-Asian-script emphasis marks with the CSS {{ cssxref("text-emphasis") }}, {{ cssxref("text-emphasis-style") }}, {{ cssxref("text-emphasis-color") }}, and {{ cssxref("text-emphasis-position") }} properties.
  • +
  • Support for script shadows with the CSS {{ cssxref("text-shadow") }} property.
  • +
+ +

Clarifies:

+ +
    +
  • The paint order of the decorations.
  • +
+ +

At risk: due to insufficient browser support, standardization of the text-decoration-skip, line positioning rules and the ability to place both emphasis marks and ruby above the same base text may be postponed to the next iteration of this module.

+
+ + + + + + + + + + + +
{{ SpecName("CSS3 Fonts", "", "") }}{{ Spec2("CSS3 Fonts") }}
+

Amends the CSS2.1 Font matching algorithm to be closer to what is really implemented.

+ +

Adds:

+ +
    +
  • Support for downloadable fonts via the CSS {{ cssxref("@font-face") }} at-rule.
  • +
  • The control of the contextual inter-glyph spacing via the CSS {{ cssxref("font-kerning") }} property.
  • +
  • The choice of language-specific glyphs via the CSS {{ cssxref("font-language-override") }} property.
  • +
  • The choice of glyphs with specific OpenType features via the CSS {{ cssxref("font-feature-settings") }} property.
  • +
  • The control of the aspect ratio to use when fallback fonts are selected via the CSS {{ cssxref("font-size-adjust") }} property.
  • +
  • The choice of alternative font faces using the CSS {{ cssxref("font-stretch") }}, {{ cssxref("font-variant-alternates") }}, {{ cssxref("font-variant-caps") }}, {{ cssxref("font-variant-east-asian") }}, {{ cssxref("font-variant-ligatures") }}, {{ cssxref("font-variant-numeric") }}, and {{ cssxref("font-variant-position") }} properties. It also extends the related CSS {{ cssxref("font-variant") }} shorthand property and introduces the {{ cssxref("@font-feature-values") }} at-rule.
  • +
  • The control of the automatic generation of an oblique or bold face when none are found via the CSS {{ cssxref("font-synthesis") }} property.
  • +
+
+ + + + + + + + + + + +
{{ SpecName("CSS3 Cascade", "", "") }}{{ Spec2("CSS3 Cascade") }}
+

Adds:

+ +
    +
  • The initial, unset values for properties.
  • +
  • The CSS {{ cssxref("all") }} property.
  • +
  • The scoping mechanism.
  • +
+ +

Clarifies:

+ +
    +
  • Interaction of media-dependent @import statements and style sheet loading requirements.
  • +
+
+ + + + + + + + + + + +
{{ SpecName("CSS3 Writing Modes", "", "") }}{{ Spec2("CSS3 Writing Modes") }}
Defines the writing modes of both horizontal and vertical scripts and clarifies how the CSS {{ cssxref("direction") }} and {{ cssxref("unicode-bidi") }} properties interact with the new CSS {{ cssxref("text-orientation") }} property, and extends them where needed.
+ + + + + + + + + + + +
{{ SpecName("CSS Shapes", "", "") }}{{ Spec2("CSS Shapes") }}
Defines geometric shapes, which can be applied to floats. These shapes describe areas, around which inline content wraps instead of wrapping around the bounding box.
+ + + + + + + + + + + +
{{ SpecName("CSS Masks", "", "") }}{{ Spec2("CSS Masks") }}
Defines a way for partially or fully hiding portions of visual elements. It describes how to use another graphical element or image as a luminance or alpha mask.
+ +

Modules in the refining phase

+ +

Specifications that are deemed to be in the refining phase are already fairly stable. Though changes are still expected, they shouldn't create incompatibilities with current implementations; they should mainly define behavior in edge cases.

+ + + + + + + + + + + +
{{ SpecName("Web Animations", "", "") }}{{ Spec2("Web Animations") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Counter Styles", "", "") }}{{ Spec2("CSS3 Counter Styles") }}
 
+ + + + + + + + + + + +
{{ SpecName("Compositing", "", "") }}{{ Spec2("Compositing") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Syntax", "", "") }}{{ Spec2("CSS3 Syntax") }}
Clarifies how charsets are determined; minor changes in parsing and tokenization algorithms.
+ + + + + + + + + + + +
{{ SpecName("CSS Will Change", "", "") }}{{ Spec2("CSS Will Change") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Transitions", "", "") }}{{ Spec2("CSS3 Transitions") }}
Allows the definition of transitions effects between two properties values by adding the CSS {{ cssxref("transition") }}, {{ cssxref("transition-delay") }}, {{ cssxref("transition-duration") }}, {{ cssxref("transition-property") }}, and {{ cssxref("transition-timing-function") }} properties.
+ + + + + + + + + + + +
{{ SpecName("CSS3 Animations", "", "") }}{{ Spec2("CSS3 Animations") }}
Allows the definition of animations effects by adding the CSS {{ cssxref("animation") }}, {{ cssxref("animation-delay") }},{{ cssxref("animation-direction") }}, {{ cssxref("animation-duration") }}, {{ cssxref("animation-fill-mode") }}, {{ cssxref("animation-iteration-count") }}, {{ cssxref("animation-name") }}, {{ cssxref("animation-play-state") }}, and {{ cssxref("animation-timing-function") }} properties, as well as the {{ cssxref("@keyframes") }} at-rule.
+ + + + + + + + + + + +
{{ SpecName("CSS3 Transforms", "", "") }}{{ Spec2("CSS3 Transforms") }}
+

Adds:

+ +
    +
  • the support of bi-dimensional transforms to be applied to any element using the CSS {{ cssxref("transform") }} and {{ cssxref("transform-origin") }} properties. The supported transforms are: matrix(), translate(), translateX(), translateY(), scale(), scaleX(), scaleY(), rotate(), skewX(), and skewY().
  • +
  • the support of tri-dimensional transforms to be applied to any element by adding the CSS {{ cssxref("transform-style") }}, {{ cssxref("perspective") }}, {{ cssxref("perspective-origin") }}, and {{ cssxref("backface-visibility") }} properties and extended the {{ cssxref("transform") }} property with the following transforms are: matrix 3d(), translate3d(), translateZ()scale3d(), scaleZ(), rotate3d(), rotateX()rotateY(), rotateZ(), and perspective().
  • +
+ +

Note: this specification is a merge of CSS 2D-Transforms, CSS 3D-Transforms and SVG transforms.

+
+ + + + + + + + + + + +
{{ SpecName("CSS3 Fragmentation", "", "") }}{{ Spec2("CSS3 Fragmentation") }}
Defines how partitions of a Web page should happen, that is page, column breaks, and widows and orphans handling. +

Adds:

+ +
    +
  • Support for defining the behavior of decorations, that is borders and background colors or images, when a box is breaked (at a page, column or line-break) with the CSS {{ cssxref("box-decoration-break") }} property.
  • +
+
+ + + + + + + + + + + +
{{ SpecName("CSS3 Text", "", "") }}{{ Spec2("CSS3 Text") }}
+

Extends:

+ +
    +
  • the CSS {{ cssxref("text-transform") }} property with the value full-width.
  • +
  • the CSS {{ cssxref("text-align") }} property with the value start, end, start end, and match-parent for a better support of documents with multiple directionalities of text.
  • +
  • the CSS {{ cssxref("text-align") }} property with a {{cssxref("<string>")}} value to align on that character. This is useful to align number on the decimal point.
  • +
  • the CSS {{ cssxref("word-spacing") }} and {{ cssxref("letter-spacing") }} properties with range constraints to control flexibility in justification.
  • +
+ +

Adds:

+ +
    +
  • Control on how whitespaces are displayed using the CSS {{ cssxref("text-space-collapse") }} and {{ cssxref("tab-size") }} properties.
  • +
  • Control on line breaks and word boundaries using the CSS {{ cssxref("line-break") }}, {{ cssxref("word-break") }}, {{ cssxref("hyphens") }}, {{ cssxref("text-wrap") }}, {{ cssxref("overflow-wrap") }}, and {{ cssxref("text-align-last") }} properties.
  • +
  • Control on how justification is happening, in order to support more type of scripts, using the CSS {{ cssxref("text-justify") }} property.
  • +
  • Control on edge effect using the CSS {{ cssxref("text-indent") }} and {{ cssxref("hanging-punctuation") }} properties.
  • +
+
+ +

A few features present in early CSS Text Level 3 draft have being postponed to the next iteration of this module .

+ + + + + + + + + + + +
{{ SpecName("CSS3 Variables", "", "") }}{{ Spec2("CSS3 Variables") }}
Defines a mechanism allowing to define variables in CSS.
+ + + + + + + + + + + +
{{ SpecName("Compositing", "", "") }}{{ Spec2("Compositing") }}
 
+ +

Modules in the revising phase

+ +

Modules that are in the revising phase are much less stable than those in the refining phase. Often the syntax is still under scrutiny and may evolve a lot, in a non-compatible way. Alternative syntaxes are tested and often implemented.

+ + + + + + + + + + + +
{{ SpecName("CSS3 Basic UI", "", "") }}{{ Spec2("CSS3 Basic UI") }}
+

Adds:

+ +
    +
  • The ability to tweak the box model using the CSS {{ cssxref("box-sizing") }} property.
    + At risk: due to insufficient browser support, standardization of the padding-box value may be postponed to the next iteration of this module .
  • +
  • Allow the styling of forms according their content using the CSS {{ cssxref(":indeterminate") }}, {{ cssxref(":default") }}, {{ cssxref(":valid") }}, {{ cssxref(":invalid") }}, {{ cssxref(":in-range") }}, {{ cssxref(":out-of-range") }}, {{ cssxref(":required") }}, {{ cssxref(":optional") }}, {{ cssxref(":read-only") }}, and {{ cssxref(":read-write") }} pseudo-classes and the {{ cssxref("::value") }}, {{ cssxref("::choices") }}, {{ cssxref("::repeat-item") }}, and {{ cssxref("::repeat-index") }} pseudo-elements.
    + At risk: due to insufficient browser support, standardization of the pseudo-elements {{ cssxref("::value") }}, {{ cssxref("::choices") }}, {{ cssxref("::repeat-item") }}, and {{ cssxref("::repeat-index") }} may be postponed to the next iteration of this module .
  • +
  • Support for icons, defined by the CSS {{ cssxref("icon") }} property simultaneously with the new icon value of the CSS {{ cssxref("content") }} property.
    + At risk: due to insufficient browser support, standardization of the {{ cssxref("icon") }} property and the icon value may be postponed to CSS4.
  • +
  • Support for the CSS {{ cssxref("outline-offset") }} property giving more control on the position of the outline.
  • +
  • Support for the CSS {{ cssxref("resize") }} property allowing Web authors to control if and how elements should be resized.
  • +
  • Support for the CSS {{ cssxref("text-overflow") }} property defining how text overflows, if needed.
    + At risk: due to insufficient browser support, the 2-value syntax of this property as well as the support for {{cssxref("<string>")}} values may be postponed to the next iteration of this module .
  • +
  • The ability to define the hotspot of a cursor as well as the new none, context-menu, cell, vertical-text, alias, copy, no-drop, not-allowed, nesw-resize, nwse-resize, col-resize, row-resize, all-scroll, zoom-in, zoom-out, extending the {{ cssxref("cursor") }} property.
  • +
  • The ability to specify the sequential navigation order (that is the tabbing order ) using the CSS {{ cssxref("nav-index") }}, {{ cssxref("nav-up") }}, {{ cssxref("nav-right") }}, {{ cssxref("nav-left") }}, {{ cssxref("nav-down") }} properties.
    + At risk: due to insufficient browser support, standardization of the navigation properties may be postponed to the next iteration of this module .
  • +
  • The ability to control the usage of an IME editor, using the CSS {{ cssxref("ime-mode") }} property.
    + At risk: due to insufficient browser support, standardization of the {{ cssxref("ime-mode") }} property may be postponed to the next iteration of this module .
  • +
+
+ +

An early list of what could be in the next iteration of the CSS Basic User Interface Module is available.

+ + + + + + + + + + + +
{{ SpecName("CSS3 Grid", "", "") }}{{ Spec2("CSS3 Grid") }}
Add a grid layout to the CSS display property and several new CSS properties to control it: {{cssxref("grid")}}, {{cssxref("grid-area")}}, {{cssxref("grid-auto-columns")}}, {{cssxref("grid-auto-flow")}}, {{cssxref("grid-auto-position")}}, {{cssxref("grid-auto-rows")}}, {{cssxref("grid-column")}}, {{cssxref("grid-column-start")}}, {{cssxref("grid-column-end")}}, {{cssxref("grid-row")}}, {{cssxref("grid-row-start")}}, {{cssxref("grid-row-end")}}, {{cssxref("grid-template")}}, {{cssxref("grid-template-areas")}}, {{cssxref("grid-template-rows")}}, and {{cssxref("grid-template-columns")}}.
+ + + + + + + + + + + +
{{ SpecName("CSS3 Box Alignment", "", "") }}{{ Spec2("CSS3 Box Alignment") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Paged Media", "", "") }}{{ Spec2("CSS3 Paged Media") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSSOM View", "", "") }}{{ Spec2("CSSOM View") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS4 Selectors", "", "") }}{{ Spec2("CSS4 Selectors") }}
 
+ +

Modules in the exploring phase

+ + + + + + + + + + + +
{{ SpecName("CSS4 Images", "", "") }}{{ Spec2("CSS4 Images") }}
+

Extends:

+ +
    +
  • the image() functional notation to describe the directionality of the image (rtl or ltr), allowing for bidi-sensitive images.
  • +
  • the {{ cssxref("image-orientation") }} property by adding the keyword from-image, allowing to follow EXIF data stored into images to be considered.
  • +
+ +

Adds:

+ +
    +
  • the image-set() functional notation to allow the definition to equivalent images at different resolution allowing for resolution-negotiated selection of images.
  • +
  • the element() functional notation allowing the use of part of the page as image.
  • +
  • the cross-fade() functional notation allowing to refer to intermediate images when transitioning between two images and defines the interpolation between two images.
  • +
  • the conic-gradient() and repeating-conic-gradient() functional notation describing a new type of gradient.
  • +
  • the {{cssxref("image-rendering")}} property that allow to define how resize of the object should be handled.
  • +
+
+ + + + + + + + + + + +
{{ SpecName("CSS3 Device", "", "") }}{{ Spec2("CSS3 Device") }}
Adds a new at-rule, {{ cssxref("@viewport") }}, allowing to specify the size, zoom factor, and orientation of the viewport that is used as the base for the initial containing block.
+ + + + + + + + + + + +
{{ SpecName("CSS3 GCPM", "", "") }}{{ Spec2("CSS3 GCPM") }}
Adds the ability to tailor printed version of a document by allowing to control header, footer but also references tables like indexes or tables of content.
+ + + + + + + + + + + +
{{ SpecName("CSS Exclusions", "", "") }}{{ Spec2("CSS Exclusions") }}
Extends the floats mechanism to define exclusion regions in any positioning scheme. Adds the notion of shapes, in which content must flows.
+ + + + + + + + + + + +
{{ SpecName("CSS3 Lists", "", "") }}{{ Spec2("CSS3 Lists") }}
Extends the list counter mechanism so that list markers can be styled and Web developers can define new list counter schemes.
+ + + + + + + + + + + +
{{ SpecName("CSS3 Regions", "", "") }}{{ Spec2("CSS3 Regions") }}
Defines a new mechanism allowing content to flow across, eventually non-contiguous, multiple areas called regions.
+ + + + + + + + + + + +
{{ SpecName("CSS3 Device", "", "") }}{{ Spec2("CSS3 Device") }}
Adds a new at-rule, {{ cssxref("@viewport") }}, allowing to specify the size, zoom factor, and orientation of the viewport that is used as the base for the initial containing block.
+ + + + + + + + + + + +
{{ SpecName("Filters 1.0", "", "") }}{{ Spec2("Filters 1.0") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Template", "", "") }}{{ Spec2("CSS3 Template") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Sizing", "", "") }}{{ Spec2("CSS3 Sizing") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS Line Grid", "", "") }}{{ Spec2("CSS Line Grid") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Positioning", "", "") }}{{ Spec2("CSS3 Positioning") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Ruby", "", "") }}{{ Spec2("CSS3 Ruby") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSSOM", "", "") }}{{ Spec2("CSSOM") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Overflow", "", "") }}{{ Spec2("CSS3 Overflow") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Font Loading", "", "") }}{{ Spec2("CSS3 Font Loading") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Display", "", "") }}{{ Spec2("CSS3 Display") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS Scope", "", "") }}{{ Spec2("CSS Scope") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS4 Media Queries", "", "") }}{{ Spec2("CSS4 Media Queries") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS Non-element Selectors", "", "") }}{{ Spec2("CSS Non-element Selectors") }}
 
+ + + + + + + + + + + +
{{ SpecName("Geometry Interfaces", "", "") }}{{ Spec2("Geometry Interfaces") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Inline", "", "") }}{{ Spec2("CSS3 Inline") }}
 
+ +

Modules in the rewriting phase

+ +

Modules that are in the rewriting phase are outdated and require to be rewritten. The syntax is still under scrutiny and may evolve a lot, in a non-compatible way. Alternative syntaxes are tested and often implemented.

+ + + + + + + + + + + +
{{ SpecName("CSS3 Box", "", "") }}{{ Spec2("CSS3 Box") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Content", "", "") }}{{ Spec2("CSS3 Content") }}
 
+ + + + + + + + + + + +
{{ SpecName("CSS3 Inline Layout", "", "") }}{{ Spec2("CSS3 Inline Layout") }}
 
+ +

 

diff --git a/files/id/archive/index.html b/files/id/archive/index.html new file mode 100644 index 0000000000..6361867424 --- /dev/null +++ b/files/id/archive/index.html @@ -0,0 +1,18 @@ +--- +title: Arsipkan konten usang +slug: Archive +translation_of: Archive +--- +

Di sini, di MDN, kami mencoba untuk menghindari penghapusan konten secara langsung yang mungkin berguna bagi orang-orang yang menargetkan platform, sistem operasi, dan browser lawas. Mungkin target pemirsa Anda adalah orang-orang yang menggunakan perangkat keras lama, misalnya, dan tidak dapat melakukan upgrade ke browser terbaru dan terbaik. Atau untuk "alasan", perusahaan Anda diharuskan menggunakan perangkat lunak yang sangat tua dan Anda perlu membangun konten Web yang berjalan pada perangkat lunak itu. Atau mungkin Anda hanya ingin tahu tentang sejarah fitur usang atau API, dan bagaimana cara kerjanya.

+ +

Ada banyak alasan dokumentasi yang lebih tua bisa bermanfaat. Jadi, kami telah menetapkan area ini untuk mengarsipkan dokumentasi yang lebih tua. Materi di zona Konten yang Diarsipkan ini seharusnya tidak digunakan untuk membuat situs Web baru atau aplikasi untuk peramban modern. Itu hanya untuk referensi sejarah saja.

+ +
+

Catatan untuk penulis: Kita perlu mencoba untuk menjaga bagian halaman di sini diatur bukan semua dibuang ke dalam satu folder besar. Cobalah untuk membuat bagan pohon  untuk kategori materi. Selain itu, hanya memindahkan halaman di sini yang sangat usang. Jika ada orang yang secara realistis memerlukan informasi dalam produk yang hidup, mungkin tidak tepat untuk memindahkannya ke sini. Secara umum, sebaiknya Anda mendiskusikannya di saluran MDN Web Docs sebelum memindahkan konten di sini.

+
+ +

{{SubpagesWithSummaries}}

+ + + +

{{ListSubpages("/en-US/docs/Archive", 2, 0, 1)}}

diff --git a/files/id/archive/meta_docs/index.html b/files/id/archive/meta_docs/index.html new file mode 100644 index 0000000000..55e2f91374 --- /dev/null +++ b/files/id/archive/meta_docs/index.html @@ -0,0 +1,11 @@ +--- +title: Arsip MDN "meta-documentation" +slug: Archive/Meta_docs +tags: + - Archive + - MDN +translation_of: Archive/Meta_docs +--- +

Di sini Anda akan menemukan arsip "meta-documentation"; Yaitu dokumentasi tentang bagaimana menulis dokumentasi tentang MDN. Artikel di sini sudah usang dan seharusnya tidak lagi direferensikan; Kami mempertahankannya di sini untuk referensi sementara kami memigrasikan beberapa konten ke tempat baru, namun sangat sedikit hal ini berguna.

+ +

{{LandingPageListSubpages}}

diff --git a/files/id/archive/mozilla/index.html b/files/id/archive/mozilla/index.html new file mode 100644 index 0000000000..132253aacf --- /dev/null +++ b/files/id/archive/mozilla/index.html @@ -0,0 +1,8 @@ +--- +title: Archived Mozilla and build documentation +slug: Archive/Mozilla +translation_of: Archive/Mozilla +--- +

In progress. These articles are archived, obsolete documents about Mozilla, Gecko, and the process of building Mozilla projects.

+ +

{{SubpagesWithSummaries}}

diff --git a/files/id/archive/mozilla/xul/index.html b/files/id/archive/mozilla/xul/index.html new file mode 100644 index 0000000000..17aa6ed66c --- /dev/null +++ b/files/id/archive/mozilla/xul/index.html @@ -0,0 +1,84 @@ +--- +title: XUL +slug: Archive/Mozilla/XUL +tags: + - NeedsTranslation + - TopicStub + - XUL +translation_of: Archive/Mozilla/XUL +--- +
XUL Tutorial
+A guided tutorial that will help you get started with XUL, originally from XULPlanet.
+ +
+

XUL (XML User Interface Language) is Mozilla's XML-based language for building user interfaces of applications like Firefox. The term XUL is sometimes used to refer to the whole Mozilla platform (e.g. XUL applications are applications using XUL and other components of the platform).

+ +

XUL Controls lists some of the common controls provided by XUL.

+
+ + + + + + + + +
+

Documentation

+ +
+
XUL Tutorial
+
A guided tutorial that will help you get started with XUL, originally from XULPlanet.
+
XUL Reference
+
XUL elements, attributes, properties, methods, and event handlers.
+
XUL Controls
+
A quick list of all of the available XUL controls.
+
The Joy of XUL
+
Describes the key features and components of XUL.
+
Menus and Popups Guide
+
A guide on using menus and popup panels.
+
Template Guide
+
A detailed guide on XUL templates, which is a means of generating content from a datasource.
+
Drag and Drop
+
How to perform drag and drop operations.
+
+ +
+
XUL Periodic Table
+
This collection of XUL demos was available as a web page, but can no longer be viwed in Firefox since support for Remote XUL was disabled.  There is a XULRunner application containing the XUL Periodic Table which can be opened with Gecko based browsers. You can get it here. See: XULRunner_tips#Using_Firefox_3_to_run_XULRunner_applications for instructions on running XULRunner apps in Firefox.
+
Changes to XUL
+
New XUL features and changes to existing features are included in the Firefox developer release notes.
+
+ +

View All...

+
+

Community

+ + + +

Tools

+ + + +

View All...

+ + + + +
+ +

 

diff --git a/files/id/archive/mozilla/xul/international_characters_in_xul_javascript/index.html b/files/id/archive/mozilla/xul/international_characters_in_xul_javascript/index.html new file mode 100644 index 0000000000..d3ddd60359 --- /dev/null +++ b/files/id/archive/mozilla/xul/international_characters_in_xul_javascript/index.html @@ -0,0 +1,23 @@ +--- +title: International characters in XUL JavaScript +slug: Archive/Mozilla/XUL/International_characters_in_XUL_JavaScript +translation_of: Archive/Mozilla/XUL/International_characters_in_XUL_JavaScript +--- +

Introduction

+

Gecko 1.8, as used in Firefox 1.5 and other applications, added support for non-ASCII characters in JavaScript files loaded from XUL files.

+

This means that such script files can use any character from virtually any language of the world. For example, they can contain a line:

+
var text = "Ein schönes Beispiel eines mehrsprachigen Textes: 日本語";
+
+

This mixes German and Japanese characters.

+

Earlier versions always interpreted JS files loaded from XUL as ISO-8859-1 (Latin-1), in both local and remote cases. Unicode escapes, as discussed below, have always worked.

+

How the character encoding is determined in Gecko 1.8 and later

+

When the JavaScript file is loaded from a chrome:// URL, a Byte Order Mark ({{todo}})({{ interwiki('wikipedia', 'Byte_Order_Mark', 'BOM') }}) is used to determine the character encoding of the script. Otherwise, the character encoding will be the same as the one used by the XUL file (which can be specified using an encoding attribute in the <?xml?> tag). By default this will use UTF-8, which can represent virtually all characters in the world.

+

If the script file is loaded via HTTP, the HTTP header can contain a character encoding declaration as part of the Content-Type header, for example:

+
Content-Type: application/javascript; charset=UTF-8
+
+

If no charset parameter is specified, the same rules as above apply.

+

Cross-version compatibility

+

If you want the same code to work in both Gecko 1.8 and earlier versions, you must limit yourself to ASCII. However, you can use unicode escapes – the earlier example rewritten using them would be:

+
var text = "Ein sch\u00F6nes Beispiel eines mehrsprachigen Textes: \u65E5\u672C\u8A9E";
+
+

An alternative might be to use property files via {{interface("nsIStringBundle")}} or the XUL <stringbundle> element; this would allow for localization of the XUL. This can not be done in XUL files loaded from the web, only in privileged code, e.g. in extensions.

diff --git a/files/id/archive/mozilla/xul/school_tutorial/index.html b/files/id/archive/mozilla/xul/school_tutorial/index.html new file mode 100644 index 0000000000..4ae723e85a --- /dev/null +++ b/files/id/archive/mozilla/xul/school_tutorial/index.html @@ -0,0 +1,59 @@ +--- +title: XUL School Tutorial +slug: Archive/Mozilla/XUL/School_tutorial +tags: + - Add-ons + - Extensions + - NeedsTranslation + - References + - TopicStub + - Tutorials + - XUL +translation_of: Archive/Add-ons/Overlay_Extensions/XUL_School +--- +

XUL School is a comprehensive add-on development tutorial, focusing on Firefox extension development. It is recommended that you read through all of it at least once. While Firefox changes rapidly, the content in this tutorial should be up to date and valid.

+
+
Introduction
+
+
Basic functionality
+
+
Intermediate functionality
+
+
Advanced topics
+
+
Appendices
+
+
+

The XUL School project was developed by Appcoast (formerly Glaxstar). The project is now published here following its sharing licenses. Its contents have been modified from the original source as necessary.

diff --git a/files/id/archive/mozilla/xul/school_tutorial/perkenalan/index.html b/files/id/archive/mozilla/xul/school_tutorial/perkenalan/index.html new file mode 100644 index 0000000000..5ce760d1be --- /dev/null +++ b/files/id/archive/mozilla/xul/school_tutorial/perkenalan/index.html @@ -0,0 +1,32 @@ +--- +title: Perkenalan +slug: Archive/Mozilla/XUL/School_tutorial/Perkenalan +translation_of: Archive/Add-ons/Overlay_Extensions/XUL_School/Introduction +--- +
+ {{Next("XUL_School/Getting_Started_with_Firefox_Extensions")}}
+

Selamat datang di Tutorial Sekolah XUL !

+

Tutorial ini dimaksudkan untuk menjadi batu loncatan yang akan mengubah Anda menjadi seorang pengembang ekstensi Firefox profesional dalam waktu singkat . Kami telah dituangkan tahun pengalaman XUL ke dalamnya , menyediakan banyak solusi untuk masalah pengembang ekstensi pada umumnya.

+

XUL School was created by Appcoast (formerly Glaxstar), one of the few companies dedicated to building high-quality Firefox extensions. A team of over a dozen XUL developers conformed Glaxstar at the time this tutorial was created, and the combined experiences of years creating Firefox extensions are reflected here.

+

With this tutorial you'll learn how to develop Firefox extensions. You'll learn how to quickly do the most common tasks in extension development, comparing several different approaches to solve them. In most cases we'll provide code samples that you can easily copy and adapt to your needs, as well as some working example extensions. The tutorial aims to be as brief as possible, often falling back on Mozilla documentation for more detailed information. You can think of it as a quick guide to the expansive world that is the Mozilla platform. Most links in this documentation are meant to be clicked and read.

+

We'll start with a brief introduction to some key concepts, in case you're not familiar with Mozilla and Firefox.

+

Mozilla and Firefox

+

The term Mozilla can be used to refer to several concepts: the Mozilla project, the Mozilla Foundation, the Mozilla Corporation and the old Mozilla browser. Even Firefox is sometimes referred to as "Mozilla". If you're unfamiliar with these terms, it's good that you take some time and learn a little about Mozilla. This will help you understand the culture that surrounds the Mozilla community.

+

Mozilla has spawned several products and projects, the most notable being the Mozilla Firefox web browser. Firefox is one of the most successful open source projects in history, combining the openness, standards-compliance and sophistication of open source with the focus on user experience and powerful outreach more commonly seen in less open companies.

+

Version 1.0 of Firefox was released in November 2004, version 2.0 in October 2006, and version 3.0 in June 2008. This tutorial was written after Firefox 3 was released, and has been updated with time. While most of it should still work for creating extensions Firefox 3 (and even Firefox 2), it is strongly recommended that you aim to support modern Firefox versions, to encourage users to stay up to date with security fixes. A release that is more than 6 months old is likely vulnerable to published security bugs.

+

Firefox and other Mozilla applications can be seen as composed of two different parts: a user interface layer that is distinct for each project, and a common platform on top of which the interface layer is built. The user interface is built with technology known as XUL, and the platform is known as XULRunner.

+

XUL

+

XUL (pronounced "zool") is one of many technologies used for creating Mozilla-based products and extensions. It is only one part of the development landscape, but given that it's practically exclusive to Mozilla, it tends to be used to identify all Mozilla-related development. You'll sometimes read terms like "XUL applications" and "XUL extensions", but rarely will they refer to projects that are exclusively built with XUL. It usually means that the projects were built using Mozilla technologies. Even this project, called XUL School, covers several other technologies such as JavaScript, CSS, XBL and XPCOM.

+

XULRunner

+

XULRunner includes the Gecko rendering engine, the Necko networking library, and several other components that provide OS-independent file management, accessibility, and localization, among others. It is this very powerful platform that has allowed such a fast growth of the development community surrounding Mozilla and Firefox.

+

XULRunner is available in binary form at the XULRunner page, and it is the base for several projects, such as Songbird, Miro and Eudora. There's a very comprehensive list of XULRunner applications in the XULRunner Hall of Fame.

+

Gecko

+

The Gecko engine is the part of Firefox used to render web pages and its own user interface. You can identify the level of compatibility of web standards in Gecko-based browsers looking at their User Agent string, which should include the Gecko version. Gecko versions are somewhat independent from Firefox versions, and you can see a mapping of Firefox versions and Gecko versions at the Gecko page. The User Agent String for Firefox at the time of this writing (in US English, Mac OS X) is:

+

Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1

+

The highlighted section is the Gecko version: 7.0.1. You can read and copy the user agent string of any Firefox window, choosing "Help > Troubleshooting Information" from the main menu.

+

On to the Tutorial

+

With the basic concepts out of the way, we can now get right into extension development. You are probably still wondering what exactly is an extension, what can it do, and how can you make them. Well, this whole tutorial is devoted to explaining that to you.

+

Welcome to the world of extension development. Now let's get to it.

+
+ {{Next("XUL_School/Getting_Started_with_Firefox_Extensions")}}
+

This tutorial was kindly donated to Mozilla by Appcoast.

diff --git a/files/id/archive/mozilla/xul/school_tutorial/the_essentials_of_an_extension/index.html b/files/id/archive/mozilla/xul/school_tutorial/the_essentials_of_an_extension/index.html new file mode 100644 index 0000000000..9fa34889f3 --- /dev/null +++ b/files/id/archive/mozilla/xul/school_tutorial/the_essentials_of_an_extension/index.html @@ -0,0 +1,344 @@ +--- +title: The Essentials of an Extension +slug: Archive/Mozilla/XUL/School_tutorial/The_Essentials_of_an_Extension +translation_of: Archive/Add-ons/Overlay_Extensions/XUL_School/The_Essentials_of_an_Extension +--- +

{{ PreviousNext("XUL_School/Getting_Started_with_Firefox_Extensions", "XUL_School/Setting_Up_a_Development_Environment") }}

+

The install.rdf File

+

In the last section we looked at the contents of the Hello World extension. Now we'll look into its files and code, starting with the install.rdf file. You can open it with any text editor.

+

The file is formatted in a special flavor of XML called RDF. RDF used to be the central storage mechanism for Firefox, but it is now being replaced for a simpler database system. We'll discuss both of these storage systems further ahead in the tutorial.

+

Now let's look at the important parts of the file.

+
+
+
<em:id>helloworld@xulschool.com</em:id>
+
+
+

This is the unique identifier for the extension. Firefox needs this to distinguish your extension from other extensions, so it is required that you have an ID that is unique.

+

There are two accepted standards for add-on ids. One is the email-like format in the Hello World example, which should be something like <project-name>@<yourdomain>. The other standard practice is to use a generated UUID string, which is extremely unlikely to be duplicated. Unix-based systems have a command line tool called uuidgen that generates UUIDs. There are also downloadable tools for all platforms that generate them. The enclosing brackets are just notation, and they're just common practice. As long as your id has some uniqueness to it, it's OK to use either form.

+
+
+
<em:name>XUL School Hello World</em:name>
+<em:description>Welcome to XUL School!</em:description>
+<em:version>0.1</em:version>
+<em:creator>Appcoast</em:creator>
+<em:homepageURL>https://developer.mozilla.org/en/XUL_School</em:homepageURL>
+
+
+

This is the data that is displayed before and after the extension is installed, that you can see in the Add-ons Manager. There are many other tags that can be added, for contributors and translators. The full specification of the install.rdf file has all the details.

+

Since extensions can be translated to multiple languages, it is often necessary to translate the extension's description, or even its name. A localized description and name can be added with the following code:

+
+
+
<em:localized>
+  <Description>
+    <em:locale>es-ES</em:locale>
+    <em:name>XUL School Hola Mundo</em:name>
+    <em:description>Bienvenido a XUL School!</em:description>
+  </Description>
+</em:localized>
+
+
+

The es-ES locale string indicates that this is the Spanish (es) localization for Spain (ES). You can add as many <em:localized> sections as you need. For Firefox 2, localizing this file is a little more complicated. We'll discuss localization further ahead in this section.

+
+
+
<em:type>2</em:type>
+
+
+

This specifies that the add-on being installed is an extension. You can read about different possible types in the install.rdf specification.

+
+
+
<em:targetApplication>
+  <Description>
+    <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
+    <em:minVersion>4.0</em:minVersion>
+    <em:maxVersion>10.*</em:maxVersion>
+  </Description>
+</em:targetApplication>
+
+
+
+

This node specifies the target application and target versions for the extension, specifically Firefox, from version 4 up to version 10. The UUID is Firefox's unique ID. Other Mozilla and Mozilla-based applications such as Thunderbird and Seamonkey have their own. You can have an extension that works on multiple applications and versions. For example, if you create a Firefox extension, it would normally take little effort to port it to SeaMonkey, which has very similar features and UI.

+

The min and max version specify the version range in which the extension can be installed. Here's more about the version format. If the application or version range don't match, you won't be allowed to install the extension, or the extension will be installed in a disabled state. Users can disable version checks through preferences or installing add-ons like the Add-on Compatibility Reporter. Beginning with Firefox 11, add-ons will default to compatible and Firefox will mostly ignore the version range. Testing your add-ons with every Firefox version is always recommended, though.

+

This is the information Firefox and other Mozilla applications need to install an add-on. Any errors or missing information will cause the installation process to fail, or the extension to be installed in a disabled state.

+

The chrome.manifest File

+
+

Chrome is the set of user interface elements of the application window that are outside of a window's content area. Toolbars, menu bars, progress bars, and window title bars are all examples of elements that are typically part of the chrome.

+
+

Taken from Chrome Registration.

+

In other words, the chrome is everything you see in Firefox. All Firefox windows can be seen as having two parts: (1) the chrome and (2) possibly a content area, like the one that displays web pages in a Firefox tab. Windows like the Downloads window are pure chrome. Most of the code for an extension resides in the chrome folder, just like in the Hello World example.

+

As we saw in the directory structure of the unpacked extension, the chrome is composed of 3 sections: content, locale and skin. The 3 are necessary for most extensions. If we open the chrome.manifest file (again, any text editor will do), we see that the same 3 sections are mentioned:

+
+
+
content   xulschoolhello              content/
+skin      xulschoolhello  classic/1.0 skin/
+locale    xulschoolhello  en-US       locale/en-US/
+
+
+
+

The chrome.manifest file tells Firefox where to look for chrome files. The text is spaced to look like a table, but that is not necessary. The parser ignores repeated spaces.

+

The first word in a line tells Firefox what it is that is being declared (content, skin, locale, or others mentioned later on). The second is the package name, which we will explain shortly.

+

Skin and locale packages have a third value to specify what locale or what skin they are extending. There can be multiple skin and locale entries relating to different skins and locales. The most common case is having one skin entry for the global skin, classic/1.0, and multiple locale entries, one for each translation. Finally, the location is specified.

+

There are some additional options that can be included in the entries of a chrome.manifest file. They are documented in the Chrome Registration page. Notably, we can have entries that are OS-specific. This is important because the appearance of the browser is very different for each operating system. If our extension needed to look differently on different systems, we could change the manifest file so that it looks like this:

+
+
+
content   xulschoolhello              content/
+skin      xulschoolhello  classic/1.0 skin/unix/
+skin      xulschoolhello  classic/1.0 skin/mac/ os=Darwin
+skin      xulschoolhello  classic/1.0 skin/win/ os=WinNT
+locale    xulschoolhello  en-US       locale/en-US/
+
+
+
+

This way we can have separate skins for Windows, Mac OS X, and Linux (plus other unix-like systems), each defined in a separate directory. Since most other systems are Unix-based, the "unix" skin is the default, with no flags.

+

The Chrome

+

As mentioned earlier, the chrome is composed of 3 sections: content, locale and skin. The content is the most important section, holding user interface (XUL) and script (JS) files. The skin section has the files that define most of the look and feel of the UI (using CSS and images, just like web pages). Finally, the locale section holds all text used in the extension, in DTD and properties files. This division allows other developers to create themes that replace skins, and translators to create localizations in different languages, all of this without having to change your extension or your code. This gives Firefox extensions a great deal of flexibility.

+

Chrome files are accessed through the chrome protocol. This is what a chrome URI looks like:

+
+
+
chrome://packagename/section/path/to/file
+
+
+

So, for instance, if I want to access the file browserOverlay.xul in the extension, the chrome URI would be chrome://xulschoolhello/content/browserOverlay.xul.

+

If you have too many files in the content and you want to organize them in subdirectories, there's nothing you need to change in chrome.manifest, all you need is to add the right path after content in the URI.

+

Skin and locale files work in the same way, and you don't need to specify skin names or locale names. So, to access the DTD file in the Hello World extension, the chrome path is chrome://xulschoolhello/locale/browserOverlay.dtd. Firefox knows what locale to look for.

+

Here's an interesting experiment. Open a new Firefox tab, type chrome://mozapps/content/downloads/downloads.xul on your location bar and press ENTER. Surprised? You just opened the Downloads window in a Firefox tab! You can access any chrome file by just typing its URI in the location bar. This can come in handy if you want to inspect script files that are part of Firefox, other extensions, or your own. Most of these files are opened as text files, with the exception of XUL files, which are executed and displayed like you would normally see them on a window.

+

Content

+

There are 2 files in the content directory. Let's look at the XUL file first.

+

XUL files are XML files that define the user interface elements in Firefox and Firefox extensions. XUL was inspired by HTML, so you'll see many similarities between the two. However, XUL is also an improvement over HTML, having learned from many of the mistakes made during the evolution of HTML. XUL allows you to create richer and more interactive interfaces than the ones you can create with HTML, or at least XUL makes it easier.

+

XUL files usually define one of two things: windows or overlays. The file you opened before, downloads.xul, has the code that defines the Downloads window. The XUL file included in the Hello World extension is an overlay. An overlay extends an existing window, adding new elements to it or replacing some of the elements in it. The line that we skipped in the chrome.manifest file states that this XUL file is an overlay for the main browser window:

+
+
+
overlay chrome://browser/content/browser.xul  chrome://xulschoolhello/content/browserOverlay.xul
+
+
+

With this line, Firefox knows that it needs to take the contents of browserOverlay.xul and overlay it on the main browser window, browser.xul. You can declare overlays for any window or dialog in Firefox, but overlaying the main browser window is the most common case by far.

+

Now let's look at the contents of our XUL file. We'll skip the first few lines because they relate to skin and locale, and we'll cover them later.

+
+
+
<overlay id="xulschoolhello-browser-overlay"
+  xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+
+
+

The root element in the file is an overlay. Other XUL documents use the window or dialog tag. The element has a unique id, which you should have on most elements in your XUL. The second attribute is the namespace, which is something you should always define in your XUL root element. It says that this node and all child nodes are XUL. You only need to change namespace declarations when you mix different types of content in the same document, such as XUL with HTML or SVG.

+
+
+
+ You may have noticed the naming we use on several places, such as the id xulschoolhello-browser-overlay. This is the namespacing standard that we use to avoid conflicts with Firefox and other extensions, as well as making some development tasks easier. We namespace all ids and style classes in overlay elements because they will be mixed with other elements in the main browser window. If we used generic ids like container or input, they will likely conflict with ids used within Firefox, or with ids from other extension overlays. Using namespaces minimizes compatibility problems with other extensions. We use camel casing for file names, and all lower case with dashes for element ids and CSS style class names, but you're free to use your own system.
+
+
+
+
+
<script type="application/x-javascript"
+  src="chrome://xulschoolhello/content/browserOverlay.js" />
+
+
+

Just like in HTML, this includes a JavaScript script file. You can have as many script elements in a XUL document as you need. We'll look into its code later.

+
+
+
+ You also probably noticed how we format our code, and wonder about the rules we follow. Our general rule on line length is not having lines longer than 80 characters. This feels very restrictive, specially with XML files, but the number was chosen to allow pretty much any text editor to handle these files easily. Even old command line editors work well with files that cut their lines at 80 characters. The tabulation is very straightforward: 2 blank space indents. We never use actual tab characters, with the exception of Makefiles, which will be covered later on. Most of our coding standards are based on Mozilla's or other known and used standards.
+
+
+

 We'll skip some code that is covered in the locale section, moving on to the most important part of the content:

+
+
+
<menubar id="main-menubar">
+  <menu id="xulschoolhello-hello-menu" label="&xulschoolhello.hello.label;"
+    accesskey="&xulschoolhello.helloMenu.accesskey;" insertafter="helpMenu">
+    <menupopup>
+      <menuitem id="xulschoolhello-hello-menu-item"
+        label="&xulschoolhello.hello.label;"
+        accesskey="&xulschoolhello.helloItem.accesskey;"
+        oncommand="XULSchoolChrome.BrowserOverlay.sayHello(event);" />
+    </menupopup>
+  </menu>
+</menubar>
+
+<vbox id="appmenuSecondaryPane">
+  <menu id="xulschoolhello-hello-menu-2" label="&xulschoolhello.hello.label;"
+    accesskey="&xulschoolhello.helloMenu.accesskey;"
+    insertafter="appmenu_addons">
+    <menupopup>
+      <menuitem id="xulschoolhello-hello-menu-item-2"
+        label="&xulschoolhello.hello.label;"
+        accesskey="&xulschoolhello.helloItem.accesskey;"
+        oncommand="XULSchoolChrome.BrowserOverlay.sayHello(event);" />
+    </menupopup>
+  </menu>
+</vbox>
+
+
+
+

This is the code that adds the Hello World menu to the browser window.

+

There are two similar code blocks, because in modern versions of Firefox, particularly on Windows, a single Firefox menu button is presented, with simplified menu options, rather than an extensive menu bar. The second code block covers the common menu button case; the first code block covers all other cases. Check Menu Bar under the Options menu of the menu button to toggle display of the classic menu on Windows and some Linux distributions.

+

In order to write this code, we needed some knowledge of the XUL code in browser.xul. We needed to know that the id of the right pane in the unified menu is appmenuSecondaryPane. We're adding a menu of our own, and telling Firefox to add it in that pane, right after the Add-ons item. That's the purpose of the attribute:

+
+
+
insertafter="appmenu_addons"
+
+
+
+

appmenu_addons is the id of the menu element that corresponds to the Add-ons menu item in the main menu. We'll see later how we can find out things like the ids of browser elements, but for now let's look at the elements that compose the Hello World menu.

+

For the classic menu, we added the Hello World menu right in the "root" of the menu so that it would be very easy for you to spot it, but this is not a recommended practice. Imagine if all extensions added menus to the top menu; having a few extensions would make it look like an airplane dashboard, full of knobs and switches. In the case of the unified menu, things are a little more difficult due to lack of options. If your menu item fits in the Web Developer section, it is recommended that you add it there. Otherwise, the root menu might be your only recourse.

+

One recommended location for menus in the classic menu vase is under the Tools menu, so the code should really look like this:

+
+
+
<menupopup id="menu_ToolsPopup">
+  <menu id="xulschoolhello-hello-menu" label="&xulschoolhello.hello.label;"
+    accesskey="&xulschoolhello.helloMenu.accesskey;"
+    insertbefore="devToolsEndSeparator">
+    <menupopup>
+      <menuitem id="xulschoolhello-hello-menu-item"
+        label="&xulschoolhello.hello.label;"
+        accesskey="&xulschoolhello.helloItem.accesskey;"
+        oncommand="XULSchoolChrome.BrowserOverlay.sayHello(event);" />
+    </menupopup>
+  </menu>
+</menupopup>
+
+
+
+

We're overlaying the menu that is deeper into the XUL tree, but it doesn't matter because all we need is the id of the element we want to overlay. In this case it is the menupopup element that's inside of the Tools menu element. The insertbefore attribute tells Firefox to add the menu at the bottom of the dev tools section, above its end separator. We'll discuss more about menus later on in the tutorial.

+

Now let's look at the actual code:

+
+
+
oncommand="XULSchoolChrome.BrowserOverlay.sayHello(event);"
+
+
+
+

This attribute defines an event handler. The command event is the most frequently used in Firefox, since it corresponds to the main action for most UI elements. The value of the attribute is JavaScript code that invokes a function. This function is defined in the JS file that was included with the script tag. The JS function will be called once the user clicks on the menu item in the Hello World menu. All event handlers define a special object named event, which is usually good to pass as an argument to the function. Event handlers are explained in greater depth further ahead.

+

Now let's look at the JavaScript file and see what's going on when the event is fired.

+
+
+
/**
+ * XULSchoolChrome namespace.
+ */
+if ("undefined" == typeof(XULSchoolChrome)) {
+  var XULSchoolChrome = {};
+};
+
+
+

The XULSchoolChrome namespace is defined. All objects and variables we define in this JavaScript are global, meaning that scripts in Firefox and other extensions can see them and interact with them. This also means that if we define an object called MenuHandler or some other generic name, it's likely going to conflict with an existing object. What we do here is define a single global object: XULSchoolChrome. Now we know that all of our objects are inside this object, which is unlikely to be duplicated or overwritten by other extensions.

+

You can read more about the typeof operator. If you're unfamiliar with JavaScript or this particular syntax, initializing an object as {} is the equivalent of initializing it to new Object().

+
+
+
/**
+ * Controls the browser overlay for the Hello World extension.
+ */
+XULSchoolChrome.BrowserOverlay = {
+
+
+

Finally, BrowserOverlay is our object. Naming and referencing  objects in such a long and verbose manner can feel uncomfortable at first, but it's worth the cost.

+
+
+
+ We use Javadoc style comments on all namespaces, objects and object members. This is a similar standard to the one used in Mozilla code, and some tools can generate documentation automatically from Javadoc.
+
+
+
+
+
sayHello : function(aEvent) {
+  let stringBundle = document.getElementById("xulschoolhello-string-bundle");
+  let message = stringBundle.getString("xulschoolhello.greeting.label");
+
+  window.alert(message);
+}
+
+
+

And, finally, this is our function declaration. Three lines of code are all we need for it to work. The first line in the body of the function declares a variable that will hold the stringbundle element defined in the overlay. The variable is declared using let, which is similar to var but with more restricted scope. Here you can read more about let declarations.

+

Just like in regular JS, we can use the DOM (Document Object Model) in order to manipulate the XUL document. First we get a reference of the stringbundle element in the document. This is a special element that allows us to obtain localized strings dynamically, by only providing a "key" that identifies the string. This is what we do on the second line. We call the getString method of the bundle element and get the localized message to be displayed. We then call the window.alert function with the message, just like we would do in an HTML document.

+

Locale

+

There are two types of locale files: DTD and properties, and in this example we use them both. DTD is the most efficient way of showing text in XUL, so you should use it whenever possible. It is somewhat inflexible so it can't be used for dynamically generated text, hence the need for an alternate way of getting localized strings.

+

Looking back at the menu code, you probably noticed some attributes such as this:

+
+
+
label="&xulschoolhello.hello.label;" accesskey="&xulschoolhello.helloItem.accesskey;"
+
+
+

These attributes define the text that you see on the menus, and they are string keys that are defined in our DTD file, browserOverlay.dtd. The DTD file was included in the XUL file with the following code:

+
+
+
<!DOCTYPE overlay SYSTEM "chrome://xulschoolhello/locale/browserOverlay.dtd" >
+
+
+

And in the DTD file you can see the association between keys and localized strings:

+
+
+
<!ENTITY xulschoolhello.hello.label            "Hello World!">
+<!ENTITY xulschoolhello.helloMenu.accesskey    "l">
+<!ENTITY xulschoolhello.helloItem.accesskey    "H">
+
+
+

Notice that on the XUL file you enclose the string key with & and ; while on the DTD file you only specify the key. You may get weird parsing errors or incorrect localization if you don't get this right.

+

Access keys are the shortcuts that allow you to quickly navigate a menu using only the keyboard. They are also the only way to navigate a menu for people with accessibility problems, such as partial or total blindness, or physical disabilities that make using a mouse very difficult or impossible. You can easily recognize the access keys on Windows because the letter that corresponds to the access key is underlined, as in the following image:

+
+

+
+

Most user interface controls have the accesskey attribute, and you should use it. The value of the access key is localized because it should match a letter in the label text. You should also be careful to avoid access key repetition. For example, within a menu or submenu, access keys should not be repeated. In a window you have to be more careful picking access keys because there are usually more controls there. You have to be specially careful when picking access keys on an overlay. In our case, we can't use the letter "H" as an accesskey in the Main menu item, because it would be the same as the access key in the Help menu. Same goes with "W" and the Window menu on Mac OS. So we settled on the letter "l".

+

DTD strings are resolved and set when the document is being loaded. If you request the label attribute value for the Hello World menu using DOM, you get the localized string, not the string key. You cannot dynamically change an attribute value with a new DTD key, you have to set the new value directly:

+
+
+
let helloItem = document.getElementById("xulschoolhello-hello-menu-item");
+
+// The alert will say "Hello World!"
+alert(helloItem.getAttribute("label"));
+// Wrong
+helloItem.setAttribute("label", "&xulschoolhello.hello2.label;");
+// Better
+helloItem.setAttribute("label", "Alternate message");
+// Right!
+helloItem.setAttribute("label", someStringBundle.getString("xulschoolhello.hello2.label"));
+
+
+

This is the reason DTD strings are not a solution for all localization cases, and the reason we often need to include string bundles in XUL files:

+
+
+
<stringbundleset id="stringbundleset">
+  <stringbundle id="xulschoolhello-string-bundle"
+    src="chrome://xulschoolhello/locale/browserOverlay.properties" />
+</stringbundleset>
+
+
+

The stringbundleset element is just a container for stringbundle elements. There should only be one per document, which is the reason why we overlay the stringbundleset that is in browser.xul, hence the very generic id. We don't include the insertbefore or insertafter attributes because the ordering of string bundles doesn't make a difference. The element is completely invisible. If you don't include any of those ordering attributes in an overlay element, Firefox will just append your element as the last child of the parent element.

+

All you need for the string bundle is an id (to be able to fetch the element later) and the chrome path to the properties file. And, of course, you need the properties file:

+
+
+
xulshoolhello.greeting.label = Hi! How are you?
+
+
+

The whitespace around the equals sign is ignored. Just like in install.rdf, comments can be added using the # character at the beginning of the line. Empty lines are ignored as well.

+

You will often want to include dynamic content as part of localized strings, like when you want to inform the user about some stat related to the extension. For example: "Found 5 words matching the search query". Your first idea would probably be to simply concatenate strings, and have one "Found" property and another "words matching..." property. This is not a good idea. It greatly complicates the work of localizers, and grammar rules on different languages may change the ordering of the sentence entirely. For this reason it's better to use parameters in the properties:

+
+
+
xulshoolhello.search.label = Found %S words matching the search query!
+
+
+

Then you use getFormattedString instead of getString in order to get the localized string. Thanks to this we don't need to have multiple properties, and life is easier for translators. You can read more about it on the Text Formatting section of the XUL Tutorial. Also have a look at the Plurals and Localization article, that covers a localization feature in Firefox that allows you to further refine this last example to handle different types of plural forms that are also language-dependent.

+

Skin

+

Styling XUL is very similar to styling HTML. We'll look into some of the differences when we cover the XUL Box Model, and other more advanced topics. There isn't much styling you can do to a minimal menu and a very simple alert message, so the Hello World extension only includes an empty CSS file and the compulsory global skin file:

+
+
+
<?xml-stylesheet type="text/css" href="chrome://global/skin/"  ?>
+<?xml-stylesheet type="text/css"
+  href="chrome://xulschoolhello/skin/browserOverlay.css"  ?>
+
+
+

The global skin CSS file holds the default styles for all XUL elements and windows. Forgetting to include this file in a XUL window usually leads to interesting and often unwanted results. In our case we don't really need to include it, since we're overlaying the main browser XUL file, and that file already includes this global CSS. At any rate it's better to always include it. This way it's harder to make the mistake of not including it. You can enter the chrome path in the location bar and inspect the file if you're curious.

+

This covers all of the files in the Hello World extension. Now you should have an idea of the basics involved in extension development, so now we'll jump right in and set up a development environment. But first, a little exercise.

+

Exercise

+

Make the following changes to the example extension:

+ +

Repackage the XPI. Issue the following command from within the extension root directory on Linux or Mac OS X:

+
zip ../xulschoolhello2.xpi **/*
+
+

On Windows, use a ZIP tool to compress all files and subdirectories within the extension root directory. Name the file with extension .xpi

+

Re-install the XPI. You can just drag the XPI file to the browser and it will be installed locally.

+

Test it and verify your changes worked. If you run into problems at installation, it's likely that you didn't reproduce the XPI structure correctly, maybe adding unnecessary folders.

+
+ Note: Packaging an extension is really just creating a ZIP archive of the contents of the main folder, then changing the filename extension to .XPI. Do not zip the containing folder, just its contents. The content folder, chrome.manifest, install.rdf, and other files and directories should be at the root level of your archive. If you zip the containing folder, your extension will not load.
+

Note that the Tools menu is hidden by default on Firefox 4 and above, on Windows and some Linux distributions. Check Menu Bar under the Options menu of the Firefox menu button to enable it.

+

Once you're done, you can look at this reference solution: Hello World 2.

+

{{ PreviousNext("XUL_School/Getting_Started_with_Firefox_Extensions", "XUL_School/Setting_Up_a_Development_Environment") }}

+

This tutorial was kindly donated to Mozilla by Appcoast.

diff --git a/files/id/archive/mozilla/xulrunner/index.html b/files/id/archive/mozilla/xulrunner/index.html new file mode 100644 index 0000000000..2bc8fd2c15 --- /dev/null +++ b/files/id/archive/mozilla/xulrunner/index.html @@ -0,0 +1,84 @@ +--- +title: XULRunner +slug: Archive/Mozilla/XULRunner +translation_of: Archive/Mozilla/XULRunner +--- +
+ Getting Started with XULRunner
+ A short introduction to XULRunner.
+
+ XULRunner is a Mozilla runtime package that can be used to bootstrap XUL+XPCOM applications that are as rich as Firefox and Thunderbird. It provides mechanisms for installing, upgrading, and uninstalling these applications. XULRunner also provides libxul, a solution which allows the embedding of Mozilla technologies in other projects and products.
+ + + + + + + +
+

Releases

+
+

XULRunner can be downloaded from ftp.mozilla.org. Please read the release notes for installation, uninstallation, and other information.

+

Firefox 3 and later ships with a private XULRunner package, which can run any compatible XULRunner application using the -app switch.

+

Older builds are also available.

+
+

Overview

+ +

Documentation

+
+
+ Getting Started with XULRunner
+
+ Short tutorial on building desktop applications with XULRunner.
+
+ XUL Tutorial
+
+ Once you have a working XULRunner application, use the XUL tutorial to expand it into a fantastic XUL application.
+
+ XULRunner tips
+
+ A collection of tips for working with XULRunner.
+
+ Deploying XULRunner
+
+ An introduction on how to package your application with XULRunner.
+
+ XULRunner Hall of Fame
+
+ Tracks all available applications based on XULRunner.
+
+ Build Documentation
+
+ Learn how to get the source and build it.
+
+ Debug Documentation
+
+ Steps to configure Venkman to debug your App
+
+ XULRunner Guide
+
+ A fairly complete, but outdated, introduction and tutorial for XULRunner which collates much of the documentation found here.
+
+

View all...

+
+

Community

+ + + +

See also

+ +
+

 

diff --git a/files/id/archive/web/index.html b/files/id/archive/web/index.html new file mode 100644 index 0000000000..1784816dc4 --- /dev/null +++ b/files/id/archive/web/index.html @@ -0,0 +1,15 @@ +--- +title: Arsip dokumentasi Web terbuka +slug: Archive/Web +tags: + - Archived + - NeedsTranslation + - TopicStub + - Web +translation_of: Archive/Web +--- +

{{obsolete_header}}

+ +

Dokumentasi yang tercantum di bawah ini adalah arsip, materi usang tentang topik Web terbuka.

+ +

{{LandingPageListSubpages}}

diff --git a/files/id/archive/web/standards-compliant_authoring_tools/index.html b/files/id/archive/web/standards-compliant_authoring_tools/index.html new file mode 100644 index 0000000000..2126ebd25c --- /dev/null +++ b/files/id/archive/web/standards-compliant_authoring_tools/index.html @@ -0,0 +1,25 @@ +--- +title: Standards-Compliant Authoring Tools +slug: Archive/Web/Standards-Compliant_Authoring_Tools +translation_of: Archive/Web/Standards-Compliant_Authoring_Tools +--- +

Creating cross-browser code upfront will save you lots of time quality testing your web content. The following authoring tools adhere to the W3 standards. If you're using older versions of tools that rely on old browser bugs or generate browser-specific code, it may be time to upgrade:

+ +

Some caveats: It appears that tools currently available from Namo generate IE-specific or Netscape 4-specific code that may require extra debugging for compatibility with standards-based browsers. Newer versions of Microsoft FrontPage™ have improved, however be sure not to rely on FrontPage-specific extensions for critical website content or functionality. Some versions of Microsoft Word create invalid HTML code that only works with Internet Explorer. Always be sure to validate your web pages.

+
+

Original Document Information

+ +
+ + diff --git a/files/id/developer_guide/index.html b/files/id/developer_guide/index.html new file mode 100644 index 0000000000..f1a8f48168 --- /dev/null +++ b/files/id/developer_guide/index.html @@ -0,0 +1,145 @@ +--- +title: Developer Guide +slug: Developer_Guide +tags: + - Developing Mozilla + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Developer_guide +--- +

Whether you're an old hand or just getting started, articles you can find starting from this page will help you while you're working on Mozilla development.

+ + + + + + + +
+

Documentation topics

+
+
+ Getting Started
+
+ A step-by-step beginner's guide to getting involved with Mozilla.
+
+
+
+ Working with Mozilla Source Code
+
+ A code overview, how to get the code, and the coding style guide.
+
+ Build Instructions
+
+ How to build Firefox, Thunderbird, SeaMonkey, or other Mozilla applications.
+
+ Development process overview
+
+ An overview of the entire Mozilla development process.
+
+ Managing multiple profiles
+
+ When working with prerelease versions of Firefox, it's often helpful to have multiple Firefox profiles, such as one for each channel, or for different kinds of testing.
+
+ Automated Testing
+
+ How to run Mozilla's automated tests, and how to write new tests.
+
+ How to submit a patch
+
+ After getting your patch written, you need to get it checked into the tree. This article explains the review process and how to get your patch approved.
+
+ Getting documentation updated
+
+ How to ensure that documentation is kept up to date as you develop.
+
+ Mozilla modules and module ownership
+
+ This article provides information about Mozilla's modules, what the role of a module owner is, and how module owners are selected.
+
+ Code snippets
+
+ Useful code samples for a wide variety of things you might need to figure out how to do.
+
+ Mozilla development strategies
+
+ Tips for how to make the most of your time working on the Mozilla project.
+
+ Debugging
+
+ Find helpful tips and guides for debugging Mozilla code.
+
+ Performance
+
+ Performance guides and utilities to help you make your code perform well (and to play nicely with others).
+
+ The Mozilla platform
+
+ Information about the workings of the Mozilla platform.
+
+ Adding APIs to the navigator object {{ gecko_minversion_inline("9.0") }}
+
+ How to augment the {{ domxref("window.navigator") }} object with additional APIs.
+
+ Interface Compatibility
+
+ Guidelines for modifying scriptable and binary APIs in Mozilla.
+
+ Customizing Firefox
+
+ Information about creating customized versions of Firefox.
+
+ Virtual ARM Linux environment
+
+ How to set up an ARM emulator running Linux for testing ARM-specific, but not necessarily platform-specific, code. Useful for mobile developers.
+
+ Obsolete Build Caveats and Tips
+
+ A place to put build tips which are no longer relevant to building the latest version of the code from main but are relevant when building old codebases.
+
+
+

Tools

+
+
+ Bugzilla
+
+ The Bugzilla database used to track issues for Mozilla projects.
+
+ MXR
+
+ Browse and search the Mozilla source code repository on the Web.
+
+ Bonsai
+
+ The Bonsai tool lets you find out who changed what file in the repository, and when they did it.
+
+ Mercurial
+
+ The distributed version-control system used to manage Mozilla's source code.
+
+ Tinderbox
+
+ Tinderbox shows the status of the tree (whether or not it currently builds successfully).  Check this before checking in and out, to be sure you're working with a working tree.
+
+ Crash tracking
+
+ Information about the Socorro and Talkback crash reporting systems.
+
+ Performance tracking
+
+ See performance information for Mozilla projects.
+
+ Callgraph
+
+ A tool to help perform static analysis of the Mozilla code by generating callgraphs automatically.
+
+ Developer forums
+
+ A topic-specific list of discussion forums where you can talk about Mozilla development issues.
+
+ Mozilla Platform Development Cheat Sheet
+
+ Brian Bondy's list of frequently referenced information for platform developers.
+
+
+

 

diff --git a/files/id/developer_guide/virtual_arm_di_lingkungan_linux/index.html b/files/id/developer_guide/virtual_arm_di_lingkungan_linux/index.html new file mode 100644 index 0000000000..8465f45f06 --- /dev/null +++ b/files/id/developer_guide/virtual_arm_di_lingkungan_linux/index.html @@ -0,0 +1,77 @@ +--- +title: Virtual ARM di Lingkungan Linux +slug: Developer_Guide/Virtual_ARM_di_Lingkungan_Linux +tags: + - ARM Linux + - Mengembangkan Mozilla + - Mobile + - Pengujian + - SSH + - Virtual ARM +translation_of: Mozilla/Developer_guide/Virtual_ARM_Linux_environment +--- +

Pengujian dengan Linux di arsitektur ARM menggunakan QEMU

+

Halaman ini menejelaskan bagaimana cara untuk mendapatkan lingkungan virtual ARM dengan QEMU yang berjalan di (Ubuntu) Linux. Ini berguna untuk siapapun yang ingin mencoba kode ARM-specific dan tidak memiliki (atau membutuhkan) perangkat keras ARM untuk pengujian.

+

Prasyarat

+

Petunjuk ini mengasumsikan sistem host yang Anda gunakan adalah Ubuntu Linux juga karena memudahkan kita untuk memasang  perangkat lunak yang diperlukan dari repositori luar.

+

Target board/CPU

+

QEMU mendukung beberapa board dan CPU. Dari semua yang Saya uji, saya hanya bisa mendapatkan Versatile Express board untuk bekerja dengan lebih dari 256 MB RAM, itulah kenapa kita akan menggunakan board ini. Untuk target CPU, Saya menguji dengan Cortex A9 saja (ARMv7).

+

Instalasai perangkat lunak yang dibutuhkan

+
# Tambahkan repositori Linaro, termasuk peralatan mereka dan yang lebih baru
+# versi dari qemu (Anda memerlukan setidaknya qemu 0.15*).
+sudo add-apt-repository ppa:linaro-maintainers/tools
+# Memasang peralatan linaro dan qemu
+sudo apt-get install linaro-image-tools qemu-user-static qemu-system
+
+# Jika Anda ingin mendapatkan cross-compile pada host, pasang juga perangkat ini
+sudo apt-get install gcc-arm-linux-gnueabi g++-arm-linux-gnueab
+

Mengunduh rilis Linaro dan paket perangkat keras

+

Anda dapat menemukan rilis yang cocok dan paket perangkat lunak tarball pada halaman rilis linaro. Beberapa dari itu mungkin bekerja, atau mungkin tidak. Saya menggunakan dua link dibawah ini yang bekerja dengan baik untuk Saua I used the two links below that worked fine for me.

+
wget http://releases.linaro.org/platform/linaro-n/nano/alpha-3/linaro-natty-nano-tar-20110302-0.tar.gz
+wget http://releases.linaro.org/platform/linaro-n/hwpacks/alpha-3/hwpack_linaro-vexpress_20110302-0_armel_supported.tar.gz
+
+

Membuat image

+

''(Langkah-langkah berikut kita pinjam dari https://wiki.linaro.org/PeterMaydell...rsatileExpress dan sedikit dimodifikasi).'' Menggunakan peralatan linaro, Anda dapat dengan mudah membuat SD card image dari paket unduhan (ini akan memakan waktu cukup lama):

+
linaro-media-create --image_file vexpress.img --dev vexpress \
+  --binary linaro-natty-nano-tar-20110302-0.tar.gz \
+  --hwpack hwpack_linaro-vexpress_20110302-0_armel_supported.tar.gz
+
+

Mengekstart kernel dan initrd

+

Image yang dubuat juga berisi kernel dan initrd dari mesin kita. Kita memerlukan kedua file meskipun itu diluar image. Perintah berikut untuk mount image ke "/mnt/tmp":

+
sudo mount -o loop,offset="$(file vexpress.img | awk 'BEGIN { RS=";"; } /partition 2/ { print $7*512; }')" \
+  -t auto vexpress.img /mnt/tmp
+
+

Sekarang salin kernel dan initrd file ke direktori saat ini (CATATAN: Nama file dapat berbeda disetiap pembuatan!):

+
cp /mnt/tmp/vmlinuz-2.6.38-1000-linaro-vexpress .
+cp /mnt/tmp/initrd.img-2.6.38-1000-linaro-vexpress .
+# Buat beberapa symlink untuk memudahkan
+ln -s vmlinuz-2.6.38-1000-linaro-vexpress vmlinuz
+ln -s initrd.img-2.6.38-1000-linaro-vexpress initrd.img
+
+

Memulai QEMU

+

Anda dapat memulai QEMU sekarang dengan perintah berikut:

+
qemu-system-arm -M vexpress-a9 -cpu cortex-a9 -kernel ./vmlinuz \
+  -initrd ./initrd.img -redir tcp:2200::22 -m 512 \
+  -append "root=/dev/mmcblk0p2 vga=normal mem=512M devtmpfs.mount=0 rw" \
+  -drive file=vexpress.img,if=sd,cache=writeback
+
+

Bebrapa penjelasan dari opsi yang tidak jelas pada perintah diatas:

+ +

Setelah memulai mesin, Anda akan bertemu dengan Linux shell dalam layar QEMU setelah beberapa waktu startup

+

Menggunakan SSH

+

Untuk menggunakan SSH, Anda harus terlebih dahulu mengaktifkan jaringan dan memasang paket SSH servere. Mengaktifkan jaringan untuk sementara menggunakan perintah berikut:

+
ifconfig eth0 up
+dhclient eth0
+
+

Sekarang coba pasang SSH:

+
apt-get install openssh-server
+
+

Untuk membuat jaringan berubah menjadi permanen, edit file ''/etc/network/interfaces'' (e.g. dengan ''vi'') dan tambahkan baris berikut:

+
auto eth0
+iface eth0 inet dhcp
+
+

Terakhir, tentukan password untuk root menggunakan perintah ''passwd''. Sekarang jalankan ulang mesin dan lihat apakah Anda bisa melakukan SSH menggunakan ''ssh -p2200 root@localhost'' pada mesin host.

diff --git a/files/id/games/index.html b/files/id/games/index.html new file mode 100644 index 0000000000..fd78f805b8 --- /dev/null +++ b/files/id/games/index.html @@ -0,0 +1,95 @@ +--- +title: Pengembangan games +slug: Games +translation_of: Games +--- +
{{GamesSidebar}}
+ +
+

Memainkan games adalah salah satu aktivitas terpopuler yang dilakukan di komputer. Teknologi baru berkembang secara konstan untuk memungkinkan pengembangan games yang lebih baik sekaligus lebih bertenaga sehingga dapat dijalankan di peramban standar manapun.

+
+ +
+
+

Kembangkan web-games

+ +

Selamat datang di Pusat Pengembangan Game MDN! Disini kami menyediakan sarana-prasarana bagi para pengembang web yang ingin mengembangkan games. Anda akan menemui sejumlah artikel bermanfaat mengenai tutorial dan teknik yang dapat Anda temui di bagian kiri Menu Utama.

+ +

Kami juga menyediakan bagian referensi, sehingga Anda dapat menemukan informasi mengenai semua API yang umum digunakan dalam pengembangan games dengan mudah, ditambah daftar engine dan tools, serta contoh games yang kami sediakan.

+ +
+

Catatan: Anda sebaiknya telah menguasai setidaknya teknologi web dasar — seperti HTML, CSS dan JavaScript — sebelum mencoba untuk membuat webgames. Area Belajar adalah tempat yang bagus untuk belajar dan melatih diri jika Anda benar-benar seorang pemula.

+
+ +
+
+
+ +
+

Port native game to the Web

+ +

Jika Anda seorang pengembang asli (misalnya menulis game di C ++), dan kamu are interested in how you can port your games over to the Web, you should learn more about our Emscripten tool — this is An LLVM to JavaScript compiler, which takes LLVM bytecode (e.g. generated from C/C++ using Clang, or from another language) and compiles that into asm.js, which can be run on the Web.

+ +

Untuk memulai, lihat:

+ + +
+
+ +
+
+

Contoh

+ +

For a list of web game examples, see our examples page. Also check out openwebgames.com for more useful resources and examples!

+
+
+ +

+ +

See also

+ +
+
+
+
Build New Games
+
A collaborative site featuring a large number of open web game development tutorials. Hasn't been very active recently, but still holds some nice resources.
+
Creative JS
+
A collection of impressive JavaScript techniques and experiments, not specific to games, but helpful nonetheless. Hasn't been very active recently, but still holds some nice resources.
+
Game programming patterns
+
An online book, written by Bob Nystrom, which discusses programming patterns in the context of game development with the aim of helping game developers produce more effective, efficient code.
+
Artillery blog
+
HTML5 games company Artillery have some useful articles on their blog.
+
Building games for Firefox OS
+
A quick guide to creating 2D games with HTML5, for distribution on Firefox OS and other mobile platforms.
+
Gamedev.js Weekly
+
Weekly newsletter about HTML5 game development, sent every Friday. Contains the latest articles, tutorials, tools, and resources.
+
HTML5 Game Devs Forum
+
Forums for developers, framework creators and publishers. Ask questions, get feedback, help others.
+
+
+ +
+
+
HTML5 Game Engine
+
List of the most popular HTML5 game frameworks along with their rating, features and samples.
+
JSBreakouts
+
Compare JavaScript Breakout clones in different frameworks to help you choose the right one for you.
+
Tuts+ Game Development
+
Tutorials and articles about game development in general.
+
#BBG IRC chat
+
Talk with the developers directly in real time.
+
HTML5 Gamedev Starter
+
Starter for the new game developers, a curated list of links to various, useful resources around the web.
+
js13kGames
+
JavaScript coding competition for HTML5 game developers with the file size limit set to 13 kilobytes. All the submitted games are available in a readable form on GitHub.
+
Mozilla Hacks blog
+
Games category on the Mozilla Hacks blog containing interesting gamedev related articles.
+
Visual-js game engine
+
2d/3d/webSocket orientend game engine. Comes with tools for windows only. Hosted on bitbucket projects site.  
+
+
+
diff --git a/files/id/games/publishing_games/game_promotion/index.html b/files/id/games/publishing_games/game_promotion/index.html new file mode 100644 index 0000000000..50cd711e48 --- /dev/null +++ b/files/id/games/publishing_games/game_promotion/index.html @@ -0,0 +1,86 @@ +--- +title: Game promotion +slug: Games/Publishing_games/Game_promotion +translation_of: Games/Publishing_games/Game_promotion +--- +
{{GamesSidebar}}
+ +

Mengembangkan dan menerbitkan game Anda tidak cukup. Anda harus memberi tahu dunia bahwa Anda memiliki sesuatu yang menarik yang dapat dinikmati orang-orang. Ada banyak cara untuk mempromosikan game Anda - kebanyakan dari mereka gratis, jadi meskipun Anda berjuang untuk mencari nafkah sebagai seorang indie dev dengan anggaran nol, Anda masih dapat melakukan banyak hal untuk membuat orang tahu tentang permainan baru Anda yang hebat. Mempromosikan permainan membantu banyak ketika mendapatkan penghasilan nanti juga, jadi penting untuk melakukannya dengan benar.

+ +

Kompetisi

+ +

Mengambil bagian dalam kompetisi tidak hanya akan meningkatkan keterampilan gamedev Anda dan membiarkan Anda bertemu pengembang baru untuk berteman dan belajar dari - dan itu juga akan membuat Anda terlibat dalam komunitas. Jika Anda membuat gim yang bagus untuk kompetisi dan memenangkan beberapa hadiah dalam proses gim Anda secara otomatis akan dipromosikan oleh penyelenggara dan peserta lainnya. Anda akan kaya dan terkenal, atau begitulah kata mereka.

+ +

Banyak permainan hebat dimulai sebagai demo yang cepat dan ceroboh yang dikirimkan ke suatu kompetisi. Jika ide dan eksekusi cukup baik, Anda akan berhasil. Kompetisi Plus umumnya membutuhkan permainan untuk mengikuti tema wajib, sehingga Anda bisa berkreasi di sekitar tema jika Anda terjebak untuk ide.

+ +

Situs web dan blog

+ +

Anda harus membuat situs web sendiri yang berisi semua informasi tentang permainan Anda, sehingga orang dapat melihat apa yang telah Anda kerjakan. Semakin banyak informasi yang dapat Anda sertakan dengan lebih baik - Anda harus menyertakan tangkapan layar, deskripsi, trailer, paket pers, persyaratan, platform yang tersedia, detail dukungan, dan banyak lagi. Anda akan mendapatkan poin bonus karena memungkinkan pengguna Anda untuk langsung memainkan game Anda secara online - setidaknya dalam bentuk demo. Juga, Anda harus melakukan beberapa pekerjaan pada SEO untuk memungkinkan orang menemukan game Anda lebih mudah.

+ +

You should also blog about everything related to your gamedev activities. Write about your development process, nasty bugs you encounter, funny stories, lessons learned, and the ups and downs of being a game developer. Continually publishing information about your games will help educate others, increase your reputation in the community, and further improve SEO. A further option is to publish monthly reports that summarize all your progress — it helps you see what you've accomplished throughout the month and what's still left to do, and it keeps reminding people that your game is coming out soon — building buzz is always good.

+ +

While you can create your website from scratch, there are also tools that can help make the process easier.  ManaKeep is a website builder made for indie game developers and provides a great starting point to create your website.  Presskit() is a press kit builder that helps you create a press page to share with the media.

+ +

Social media

+ +

Your social media presence is very important — follow the right hashtags, make friends, engage in conversations, help other devs in need. Honesty is key and you should be authentic, because nobody likes boring press releases or pushy advertisements. When the time comes your community will help you spread the word about your shiny little game.

+ +

You should use at least Twitter and Facebook and be active on appropriate forums — the most popular one is HTML5GameDevs.com. Share your gamedev news and answer questions, so people will value what you're doing and will know that you're ok. Remember to not be too pushy on telling everyone about your games — you're not a walking advertisement.

+ +

Grow your fanbase by talking to them, sharing tips, offering discounts, giving away prizes in competitions, or just complaining at the weather or buggy browser you have to deal with. Act cool, be generous, be yourself and be there for others, and you'll get treated with respect.

+ +

Game portals

+ +

Using game portals is mostly concerned with monetization, but if you're not planning to sell licenses to allow people to purchase your game and are intending to implement adverts or in-app purchases instead, promoting your game across free portals can be effective.

+ +

You can send your games for publication on portals like CrazyGames.comGameDistribution.com, Lagged.comPacoGames.com ,games4html5.com or HTML5Games.com, and there are about 20-30 other notable game portals with and without API. 

+ +

Those portals that have their own API will allow you to authorize users, save their progress and process in-app purchases. You can also sell a full version of the game from inside your browser demo version, which will be a great move considering high competition, some developers even manage to make full browser versions. Most portals offer revenue share deals or will buy non exclusive license.

+ +

Free portals offer traffic, but only the best ones are popular enough to generate revenues from advertisements on in-app purchases. On the other hand they are a perfect tool to make games visible to a broader audience if you have no budget and limited time.

+ +

Press

+ +

You can try and reach the press about your game, but bear in mind that they get a tonne of requests like this every single day, so be humble and patient if they don't answer right away, and be polite when talking to them. Be sure to check first if they are dealing with specific genres of games or platforms, so you don't send them something that is not relevant to them in the first place. If you're honest with your approach and your game is good, then you've got more of a chance of success.

+ +

If you want to learn more about the etiquette of contacting the press you should definitely check out How To Contact Press - a great guide from Pixel Prospector, and the Video Game Journaliser site curated by them for the list of sites to contact.

+ +

Tutorials

+ +

It's good to share your knowledge with other devs — after all you probably learned a thing or two from online articles, so you take the time to pay that knowledge forward. Talking or writing about something you achieved or problems you overcame is something people would be interested it. And you can use your own game as an example, especially in a tutorial when you're showing how to do something you've implemented already. That way everyone benefits — people learn new skills, your game gets promoted, and if you're lucky you can even get paid for writing a tutorial if it's good enough.

+ +

There are portals like Tuts+ Game Development which will be more than happy if you write for them - they pay for the content, but not all topic ideas will be accepted. When writing a tutorial remember to focus on delivering something valuable to the reader. They want to learn something - offer your expertise and use your game as a case study. Focus on one aspect and try to explain it throughout and in detail. Also remember to follow up discussion in comments if people have any questions.

+ +

If portals you contact are not interested in your content because you don't have any experience yet, try writing tutorials and publish them on your own blog first. It's the easiest way to train your writing skills on your own.

+ +

YouTubers

+ +

It's a rising trend — don't underestimate the power of YouTubers playing your game, talking about it and streaming their experience to give you lots of promotion. You should also be realistic however — don't think this alone will skyrocket your downloads or visits, and be prepared to deal with bad reviews as well as good ones.

+ +

There are two options to get coverage from the YouTubers: first is you contact them directly and send a link to your game via email or private message. The second is earned in time - if you're known enough the YouTubers will contact you and ask for the link or build of your game. This Big List of YouTubers is a great place to start. You can find YouTube and Twitch.tv influencers at gameInfluencer.com to help promote your game.

+ +

Events

+ +

If you've gone through all the options listed above you can still find new, creative ways to promote your game — events are another good example. Attending events, both local and global, gives you the ability to meet your fans face to face, as well as other members of the development community. Value the fact that they spent their time seeing you.

+ +

Conferences

+ +

There are many conferences where you can give a talk explaining some technical difficulties you overcame, or how you implemented specific APIs; again — use your games as examples for that. It's important to focus on the knowledge part and tone down the marketing — devs are sensitive on this matter and you may end up with an angry crowd if you just try to sell them something.

+ +

Fairs

+ +

The other event-related option is fairs (or expos) — at such an event you can get a booth among other devs and promote your game to all the attendees passing by. If you do so, try to be unique and original, so you easily stand from the crowd. Do it the right way and everybody will be talking about you and your game. Having a booth gives you the possibility to interact with your fans directly — besides the promotion part you can also test new builds of your game on regular people and fix any bugs (or incorporate any feedback) they uncover. You can't imagine what people may come up with when playing your game, and what obvious issues you've missed while spending hours polishing it.

+ +

Promo codes

+ +

If you're selling the game, then create the ability to distribute promo codes allowing people to access your game for free (or at least a demo or time-limited version), and send them all over the place — to press, youtubers, as competition prizes, etc. If the game reaches certain people you'll get a free advert to thousands of players. It can boost interest in your game more than anything else if you get lucky.

+ +

Fostering the community

+ +

You can help community grow and promote yourself and your games at the same time. Sending out weekly newsletters and organizing online competitions or local meetups will show others that you're passionate about what you do and that they can rely on you. Then when you need any help they will be there for you.

+ +

Summary

+ +

Cara apa pun untuk mempromosikan permainan Anda adalah baik. Anda memiliki banyak opsi untuk dipilih dan sebagian besar di antaranya gratis, jadi ini hanya soal antusiasme dan waktu yang tersedia. Terkadang Anda harus menghabiskan lebih banyak waktu untuk mempromosikan game daripada benar-benar mengembangkannya. Ingatlah bahwa tidak ada gunanya memiliki permainan terbaik di dunia jika tidak ada yang tahu itu ada.

+ +

Sekarang mari kita lanjutkan dengan bagian monetisasi itu , dan dapatkan penghasilan untuk hidup.

diff --git a/files/id/games/publishing_games/index.html b/files/id/games/publishing_games/index.html new file mode 100644 index 0000000000..5559db1bbe --- /dev/null +++ b/files/id/games/publishing_games/index.html @@ -0,0 +1,28 @@ +--- +title: Publishing games +slug: Games/Publishing_games +tags: + - Games + - HTML5 + - JavaScript + - Monetization + - NeedsTranslation + - Promotion + - TopicStub + - distribution + - publishing +translation_of: Games/Publishing_games +--- +
{{GamesSidebar}}

HTML5 games have a huge advantage over native in terms of publishing and distribution — you have the freedom of distribution, promotion and monetization of your game on the Web, rather than each version being locked into a single store controlled by one company. You can benefit from the web being truly multiplatform. This series of articles looks at the options you have when you want to publish and distribute your game, and earn something out of it while you wait for it to become famous.

+ +

Game distribution

+ +

So you've followed a tutorial or two and created an HTML5 game — that's great! Game distribution provides all you need to know about the ways you can distribute your newly created game into the wild — including hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like Google Play or the iOS App Store.

+ +

Game promotion

+ +

Developing and finishing the game is not enough. You have to let the world know that you have made something interesting available, which people will enjoy playing. There are many Game promotion techniques — many of them free — so even if you're struggling to make a living as an indie dev with zero budget you can still do a lot to let people know about your great new game. Promoting the game helps a lot in monetizing it later on too, so it's important to do it effectively.

+ +

Game monetization

+ +

When you spend your time building, publishing and promoting your game, you will at some point consider earning money out of it. Game monetization is essential to anyone who considers their game development work a serious endeavour on the path to becoming an independent game developer able to make a living, so read on and see what your options are. The technology is mature enough; it's just a matter of chosing the right approach.

diff --git a/files/id/games/techniques/index.html b/files/id/games/techniques/index.html new file mode 100644 index 0000000000..66edeebd82 --- /dev/null +++ b/files/id/games/techniques/index.html @@ -0,0 +1,32 @@ +--- +title: Techniques for game development +slug: Games/Techniques +tags: + - Games + - Guide + - NeedsTranslation + - TopicStub +translation_of: Games/Techniques +--- +
{{GamesSidebar}}
{{IncludeSubnav("/en-US/docs/Games")}}
+ +
+

This page lists essential core techniques for anyone wanting to develop games using open web technologies.

+
+ +
+
Using async scripts for asm.js
+
Especially when creating medium to large-sized games, async scripts are an essential technique to take advantage of, so that your game's JavaScript can be compiled off the main thread and be cached for future game running, resulting in a significant performance improvement for your users. This article explains how.
+
Optimizing startup performance
+
How to make sure your game starts up quickly, smoothly, and without appearing to lock up the user's browser or device.
+
Using WebRTC peer-to-peer data channels
+
In addition to providing support for audio and video communication, WebRTC lets you set up peer-to-peer data channels to exchange text or binary data actively between your players. This article explains what this can do for you, and shows how to use libraries that make this easy.
+
Efficient animation for web games
+
This article covers techniques and advice for creating efficient animation for web games, with a slant towards supporting lower end devices such as mobile phones. We touch on CSS transitions and CSS animations, and JavaScript loops involving {{ domxref("window.requestAnimationFrame") }}.
+
Audio for Web Games
+
Audio is an important part of any game — it adds feedback and atmosphere. Web-based audio is maturing fast, but there are still many browser differences to negotiate. This article provides a detailed guide to implementing audio for web games, looking at what works currently across as wide a range of platforms as possible.
+
2D collision detection
+
A concise introduction to collision detection in 2D games.
+
Tilemaps
+
Tiles are a very popular technique in 2D games for building the game world. These articles provide an introduction to tilemaps and how to implement them with the Canvas API.
+
diff --git a/files/id/glossary/404/index.html b/files/id/glossary/404/index.html new file mode 100644 index 0000000000..9c8065b3e3 --- /dev/null +++ b/files/id/glossary/404/index.html @@ -0,0 +1,17 @@ +--- +title: '404' +slug: Glossary/404 +tags: + - Glossary + - HTTP Error + - Infrastructure +translation_of: Glossary/404 +--- +

404 merupakan Standard Kode Respon yang berarti bahwa {{Glossary("Server", "server")}} tidak dapat menemukan resource yang diminta.

+ +

Belajar lebih lanjut

+ + diff --git a/files/id/glossary/ajax/index.html b/files/id/glossary/ajax/index.html new file mode 100644 index 0000000000..2b4e187722 --- /dev/null +++ b/files/id/glossary/ajax/index.html @@ -0,0 +1,22 @@ +--- +title: AJAX +slug: Glossary/AJAX +translation_of: Glossary/AJAX +--- +

AJAX (Asynchronous {{glossary("JavaScript")}} dan {{glossary("XML")}}) merupakan praktik pemrograman yang menggabungkan {{glossary("HTML")}}, {{glossary("CSS")}}, JavaScript, {{glossary("DOM")}}, dan XMLHttpRequest {{glossary("object")}} untuk membangun halaman web yang lebih kompleks. Yang bisa Anda lakukan dengan AJAX yaitu memungkinkan Anda untuk memperbarui bagian dari halaman tanpa harus me-reload keseluruhan halaman. AJAX juga dapat bekerja secara asynchronous, yang berarti kode anda terus berjalan ketika bagian halaman tersebut mencoba untuk memuat kembali konten (dibandingkan secara cara kerja synchronous, di mana kode akan diblokir dari saat berjalan hingga halaman telah selesai dimuat).

+ +

Pelajari juga

+ +

Pengetahuan Umum

+ + + +

Informasi Teknikal

+ + diff --git a/files/id/glossary/algoritma/index.html b/files/id/glossary/algoritma/index.html new file mode 100644 index 0000000000..d43365aeb8 --- /dev/null +++ b/files/id/glossary/algoritma/index.html @@ -0,0 +1,8 @@ +--- +title: Algoritma +slug: Glossary/Algoritma +tags: + - Glosarium +translation_of: Glossary/Algorithm +--- +

Algoritma adalah serangkaian instruksi untuk menyelesaikan suatu masalah

diff --git a/files/id/glossary/api/index.html b/files/id/glossary/api/index.html new file mode 100644 index 0000000000..b0e8c7a52e --- /dev/null +++ b/files/id/glossary/api/index.html @@ -0,0 +1,24 @@ +--- +title: API +slug: Glossary/API +tags: + - CodingScripting + - Glossary + - Infrastructure +translation_of: Glossary/API +--- +

Sebuah API (Application Programming Interface) merupakan set dari fitur dan aturan yang memungkinkan interaksi antar software yang menyediakan API dan komponen software lain. DI pengembangan Web, API umumnya disebut standard set {{glossary("method","methods")}}, {{Glossary("property","properties")}}, event, dan {{Glossary("URL","URLs")}} untuk berinteraksi dengan Konten Web.

+ +

Pelajari Lebih Lanjut

+ +

Pemahaman Umum

+ + + +

Referensi teknikal

+ + diff --git a/files/id/glossary/asynchronous/index.html b/files/id/glossary/asynchronous/index.html new file mode 100644 index 0000000000..8f2c96568d --- /dev/null +++ b/files/id/glossary/asynchronous/index.html @@ -0,0 +1,14 @@ +--- +title: Asynchronous +slug: Glossary/Asynchronous +translation_of: Glossary/Asynchronous +--- +

Asynchronous arti-nya mengacu pada sebuah communication environment (seperti email) di mana setiap bagian/ block  menerima dan memproses pesan - pesan dengan baik sekali, dan memungkinkan dapat menerima 'pesan' lebih dari sekali dan di olah dengan baik sekali dalam proses komunikasi cara ini.

+ +

Pelajari Lebih Dalam

+ +

Technical reference

+ + diff --git a/files/id/glossary/css/index.html b/files/id/glossary/css/index.html new file mode 100644 index 0000000000..c318ba2c3e --- /dev/null +++ b/files/id/glossary/css/index.html @@ -0,0 +1,48 @@ +--- +title: CSS +slug: Glossary/CSS +tags: + - CSS + - Glossary + - Web +translation_of: Glossary/CSS +--- +

CSS (Cascading Style Sheets) merupakan bahasa deklaratif yang mengontrol tampilan halaman web di {{glossary("browser")}}. Browser menerapkan deklarasi CSS pada elemen untuk menampilkannya dengan benar. Sebuah deklarasi style/gaya terdiri dari properti dan nilainya, yang menentukan bagaimana halaman web ditampilkan.

+ +

CSS merupakan salah satu dari tiga inti teknologi web, bersama dengan {{Glossary("HTML")}} dan {{Glossary("JavaScript")}}. CSS umumnya memberi style pada {{Glossary("Element","HTML elements")}}, namun juga dapat digunakan dengan bahasa markup lain seperti {{Glossary("SVG")}} atau {{Glossary("XML")}}.

+ +

Aturan CSS merupakan suatu himpunan {{Glossary("CSS Property","properties")}} yang terkait dengan {{Glossary("selector")}}. Berikut adalah sebuah contoh yang membuat setiap paragraf HTML berwarna kuning dengan warna latar hitam:

+ +
/* Selector "p" menunjukan bahwa semua paragraf pada dokumen akan dipengaruhi aturan ini */
+p {
+  /* Properti "color" mendefinisikan warna teks, pada contoh ini kuning - "yellow". */
+  color: yellow;
+
+  /* Properti "background-color" mendefinisikan warna latar, pada contoh ini hitam - "black". */
+  background-color: black
+}
+ +

Istilah "cascading" mengacu pada aturan-aturan yang mengatur bagaimana selector diprioritaskan untuk mengubah tampilan halaman. Ini merupakan fitur penting, karena sebuah situs yang kompleks dapat memiliki ribuan aturan CSS.

+ +

Pelajari Juga

+ +

Pengetahuan Umum

+ + + +

Referensi Teknikal

+ + + +

Belajar tentang CSS

+ + diff --git a/files/id/glossary/html/index.html b/files/id/glossary/html/index.html new file mode 100644 index 0000000000..3b2eb3d305 --- /dev/null +++ b/files/id/glossary/html/index.html @@ -0,0 +1,44 @@ +--- +title: HTML +slug: Glossary/HTML +translation_of: Glossary/HTML +--- +

HTML (HyperText Markup Language) merupakan sebuah bahasa deskriptif yang menentukan struktur halaman web.

+ +

Sejarah singkat

+ +

Pada tahun 1990, sebagai bagian dari visinya tentang {{glossary("World Wide Web","Web")}}, Tim Berners-Lee mendefinisikan konsep {{glossary("hypertext")}}, yang Berners-Lee buat secara resmi pada tahun selanjutnya melalui sebuah markup yang secara umum berbasis pada {{glossary("SGML")}}. {{glossary("IETF")}} mulai menetapkan HTML secara resmi pada tahun 1993, dan setelah beberapa draf mereka merilis versi 2.0 di tahun 1995. Pada tahun 1994 Berners-Lee mendirikan {{glossary("W3C")}} untuk mengembangkan Web. Di tahun 1996, W3C mengambil alih HTML dan mempublikasikan rekomendasi HTML 3.2 setahun kemudian. HTML 4.0 dirilis pada tahun 1999 dan menjadi standar ISO di tahun 2000.

+ +

Pada saat itu, W3C hampir meninggalkan HTML untuk mendukung {{glossary("XHTML")}}, sehingga memicu pendirian kelompok independen yang disebut {{glossary("WHATWG")}} di tahun 2004. Karena WHATWG, pekerjaan {{glossary("HTML5")}} diteruskan: kedua organisasi tersebut mempublikasikan draf pertama di tahun 2008 dan standar akhir di tahun 2014.

+ +

Konsep dan sintaks

+ +

Sebuah dokumen HTML merupakan sebuah dokumen plaintext yang terstruktur dengan {{glossary("element","elements")}}. Elemen dikelilingi oleh {{Glossary("tag","tags")}} pembuka dan penutup yang sesuai. Masing-masing tag dimulai dan diakhiri oleh sebuah angle bracket  (<>). Ada beberapa tag kosong atau void yang tidak dapat disertakan oleh teks apapun, seperti {{htmlelement("img")}}.

+ +

Anda dapat memperpanjang tag HTML dengan {{Glossary("attribute","attributes")}}, yang menyediakan informasi tambahan yang akan mempengaruhi bagaimana perambah mengimplementasikan elemen:

+ +

Detail of the structure of an HTML element

+ +

Sebuah file HTML biasanya disimpan dengan sebuah ekstensi .htm atau .html, yang dijalani oleh sebuah  {{Glossary("Server","web server")}}, dan dapat ditampilkan oleh {{Glossary("Browser","Web browser")}} apapun.

+ +

Pelajari juga

+ +

Pengetahuan umum

+ + + +

Belajar HTML

+ + + +

Referensi teknis

+ + diff --git a/files/id/glossary/http/index.html b/files/id/glossary/http/index.html new file mode 100644 index 0000000000..24a606d4d6 --- /dev/null +++ b/files/id/glossary/http/index.html @@ -0,0 +1,22 @@ +--- +title: HTTP +slug: Glossary/HTTP +tags: + - Beginner + - Glossary + - HTTP + - Infrastructure +translation_of: Glossary/HTTP +--- +

HTTP (HyperText Transfer Protocol) adalah {{glossary("protocol", "protokol")}} sederhana yang memunginkan transfer file di {{glossary("World Wide Web","Web")}}. HTTP bersifat tekstual (semua komunikasi dilakukan dengan teks biasa) dan stateless (tidak ada komunikasi yang menyadari komunikasi sebelumnya).

+ +
+

Pelajari juga

+ + +
+ +

 

diff --git a/files/id/glossary/identifier/index.html b/files/id/glossary/identifier/index.html new file mode 100644 index 0000000000..370c97cbb9 --- /dev/null +++ b/files/id/glossary/identifier/index.html @@ -0,0 +1,16 @@ +--- +title: Identifier +slug: Glossary/Identifier +translation_of: Glossary/Identifier +--- +

Rangkaian karakter dalam kode yang mengidentifikasikan sebuah {{glossary("variable")}}, {{glossary("function")}}, atau {{glossary("property")}}.

+ +

In {{glossary("JavaScript")}}, Pengidentifikasi dapat berisi hanya karakter alpanumerik (atau "$" atau "_"), dan tidak boleh dimulai dengan angka.  Pengenal berbeda dari string yang berupa string adalah data, sementara pengenal adalah bagian dari kode. Dalam JavaScript, tidak ada cara untuk mengonversi pengenal ke string, namun terkadang memungkinkan untuk mengurai string menjadi pengidentifikasi.

+ +

Belajar lebih lagi

+ +

Pengetahuan umum

+ + diff --git a/files/id/glossary/index.html b/files/id/glossary/index.html new file mode 100644 index 0000000000..59631f62ab --- /dev/null +++ b/files/id/glossary/index.html @@ -0,0 +1,27 @@ +--- +title: Glossary +slug: Glossary +tags: + - Beginner + - Glossary + - Index + - Landing + - NeedsTranslation + - TopicStub +translation_of: Glossary +--- +
{{LearnBox({"title":"Belajar Istilah baru:"})}}
+ +

Teknologi Web terdiri dari daftar panjang and singkatan yang digunakan di setiap dokumentasi dan coding. Glossary ini memberikan definisi dari kata - kata dan singkatan yang perlu anda ketahui untuk berhasil memahami dan membangun web.

+ +

{{GlossaryList({"split":"h3", "css":"multiColumnList"})}}

+ +

Kontribusi ke glossary

+ +

Glossary ini tidak pernah berakhir dalam pengerjaan. Anda bisa membantu membaharuinya dengan menulis entry baru atau memperbaikinya. Cara termudah untuk memulai dengan menekan tombol yang disediakan atau pilih salah satu dari istilah berikut.

+ +

Tambahkan entry baru ke glossary

+ +

{{GlossaryList({"terms":["character encoding","DMZ","event","HMAC","condition","modem","OVP","TTL","Unicode"], "filter":"notdefined", "css":"multiColumnList"})}}

+ +

Jika anda ingin mengetahui lebih lanjut untuk berkontribusi ke glossary, kunjungi halaman status dokumentasi glossary.

diff --git a/files/id/glossary/javascript/index.html b/files/id/glossary/javascript/index.html new file mode 100644 index 0000000000..7ca928900d --- /dev/null +++ b/files/id/glossary/javascript/index.html @@ -0,0 +1,45 @@ +--- +title: JavaScript +slug: Glossary/JavaScript +tags: + - CodingScripting + - Glossary + - JavaScript +translation_of: Glossary/JavaScript +--- +

JavaScript (JS) merupakan bahasa pemrograman yang sering digunakan pada sisi klien (client-side) untuk membuat script pada halaman web secara dinamis, tapi juga sering digunakan pada sisi server ({{Glossary("Server","server")}}-side).

+ +

JavaScript tidak sama dengan {{interwiki("wikipedia", "Java_(programming_language)", "bahasa pemrograman Java")}}. Baik "Java" maupun "JavaScript" merupakan merek dagang atau merek dagang terdaftar Oracle di Amerika Serikat dan negara-negara lainnya. Namun, kedua bahasa pemrograman tersebut mempunyai sintaks, semantik, dan kegunaan yang sangat berbeda.

+ +

Dibuat sebagai bahasa sisi server oleh Brendan Eich (saat itu merupakan perkerja di Netscape Corporation), JavaScript selanjutnya hadir di Netscape Navigator 2.0 pada September 1995. JavaScript menikmati kesuksesan dan {{glossary("Microsoft Internet Explorer", "Internet Explorer 3.0")}} memperkenalkan dukungan JavaScript di bawah nama JScript pada August 1996.

+ +

Di November 1996, Netscape mulai bekerja dengan ECMA International untuk membuat JavaScript sebagai sebuah standar industri. Sejak saat itu, JavaScript yang telah terstandardisasi disebut sebagai ECMAScript dan dispesifikasikan di bawah ECMA-262, di mana edisi terbaru (kedelapan) tersedia pada Juni 2017.

+ +

JavaScript pada umumnya digunakan pada perambah, memungkinkan pengembang untuk memanipulasi halaman web melalui {{Glossary("DOM")}}, memanipulasi data dengan {{Glossary("AJAX")}} dan {{Glossary("IndexedDB")}}, menggambar grafik dengan {{Glossary("canvas")}}, berinteraksi dengan perangkat yang menjalankan perambah melalui bermacam {{Glossary("API","APIs")}}, dan masih banyak lagi. JavaScript adalah salah satu bahasa yang paling sering digunakan di dunia, karena pertumbuhan dan peningkatan performa pada {{Glossary("API","APIs")}} di perambah yang ada baru-baru ini.

+ +

Belakangan ini, JavaScript kembali ke server dengan kesuksesan platform Node.js, yang merupakan runtime environment bersifat cross-platform JavaScript paling populer di luar perambah. Node.js memungkinkan Anda menggunakan JavaScript sebagai bahasa scripting yang mengotomatisasi banyak hal di PC dan membangun  {{Glossary("HTTP")}} dan server {{Glossary("Web Sockets")}} yang fungsional sepenuhnya.

+ +

Pelajari juga

+ +

Pengetahuan umum

+ + + +

Belajar JavaScript

+ + + +

Referensi teknis

+ + diff --git a/files/id/glossary/json/index.html b/files/id/glossary/json/index.html new file mode 100644 index 0000000000..fc0d4af364 --- /dev/null +++ b/files/id/glossary/json/index.html @@ -0,0 +1,24 @@ +--- +title: JSON +slug: Glossary/JSON +translation_of: Glossary/JSON +--- +

JavaScript Object Notation (JSON) merupakan sebuah format pertukaran data.  Meskipun bukanlah merupakan bagian dari  JavaScript,  JSON memiliki kemiripan terhadap bagian dari sintaks {{Glossary("JavaScript")}}. Meski banyak bahasa pemrograman yang mendukung JSON, JSON khususnya berguna untuk aplikasi-aplikasi berbasis JavaScript, termasuk situs dan ekstensi browser.

+ +

JSON dapat merepresentasikan angka, boolean, string, null , array (urutan terurut dari nilai-nilai), dan objek (pemetaan string-nilai) yang terdiri dari nilai-nilai tersebut (atau terdiri dari array dan objek lain). JSON tidak merepresentasikan tipe-tipe data yang lebih kompleks seperti fungsi, ekspresi regular, tanggal, dan lain sebagainya. (Objek Date secara standar melakukan serialisasi terhadap sebuah string  yang mengandung tanggal dalam format ISO, sehingga informasi yang ada tidak sepenuhnya hilang.) Apabila Anda memerlukan JSON untuk merepresentasikan tipe-tipe data tambahan, transformasikanlah nilai-nilai bersamaan ketika mereka diserialisasikan atau sebelum mereka dideserialisasikan.

+ +

Seperti XML, JSON memiliki kemampuan untuk menyimpan data yang bersifat hirarkis, tidak seperti format CSV tradisional. Banyak alat yang menyediakan translasi antara format-format ini seperti JSON to CSV Converter ini.

+ +

Pelajari juga

+ +

Pengetahuan umum

+ + + +

Referensi teknis

+ + diff --git a/files/id/glossary/method/index.html b/files/id/glossary/method/index.html new file mode 100644 index 0000000000..8f10dd9061 --- /dev/null +++ b/files/id/glossary/method/index.html @@ -0,0 +1,29 @@ +--- +title: Method +slug: Glossary/Method +tags: + - CodingScripting + - Glossary + - JavaScript +translation_of: Glossary/Method +--- +

Sebuah method merupakan {{glossary("function")}} yang berupa {{glossary("property")}} dari {{glossary("object")}}. Ada dua jenis method: Instance Method yang berupa built-in tasks yang di jalankan oleh instansi object, atau Static Methods yang berupa tasks yang dapat dijalankan tanpa membutuhkan instansi object.

+ +
+

Catatan: Fungsi di JavaScript sendiri merupakan objek, jadi, pada konteks tersebut, sebuah method merupakan {{glossary("object reference")}} dari function.

+
+ +

Pelajari lebih lanjut

+ +

Pelajari Ini

+ + + +

Referensi teknikal

+ + diff --git a/files/id/glossary/null/index.html b/files/id/glossary/null/index.html new file mode 100644 index 0000000000..42d1799b50 --- /dev/null +++ b/files/id/glossary/null/index.html @@ -0,0 +1,27 @@ +--- +title: 'Null' +slug: Glossary/Null +tags: + - CodingScripting + - Glossary + - Pustaka +translation_of: Glossary/Null +--- +

Dalam ilmu komputer, nilai null mewakili referensi suatu nilai yang tidak ada, umumnya sengaja untuk meng-tiadakan, hampa, atau Invalid {{glossary("object")}} atau pengalamatan. Banyak arti referensi null pada penerapan bahasa pemrogramman lainnya.

+ +

Dalam {{Glossary("JavaScript")}}, null adalah salahsatu dari {{Glossary("Primitive", "Nilai Primitif")}}.

+ +

Rujukan Lain

+ +

Pengetahuan Umum

+ + + +

Referensi Teknik

+ + diff --git a/files/id/glossary/primitive/index.html b/files/id/glossary/primitive/index.html new file mode 100644 index 0000000000..a79af0b9dd --- /dev/null +++ b/files/id/glossary/primitive/index.html @@ -0,0 +1,32 @@ +--- +title: Primitive +slug: Glossary/Primitive +translation_of: Glossary/Primitive +--- +

A primitif (nilai primitif, tipe data primitif) adalah data yang bukan suatu {{Glossary("object", "objek")}} dan tidak memiliki {{glossary("method","metode")}}. Dalam {{Glossary("JavaScript")}}, ada 6 tipe data primitif: {{Glossary("string")}}, {{Glossary("number")}}, {{Glossary("boolean")}}, {{Glossary("null")}}, {{Glossary("undefined")}}, {{Glossary("symbol")}} (baru dalam {{Glossary("ECMAScript")}} 2015).

+ +

Sebagian besar waktu, nilai primitif diwakili secara langsung pada tingkat terendah dalam implementasi bahasa.

+ +

Semua primitif tidak immutable (tidak bisa diubah).

+ +

Objek pembungkus primitif pada JavaScript

+ +

Kecuali untuk null dan undefined, semua nilai primitif memiliki persamaan objek yang membungkus nilai primitif:

+ + + +

Pembungkus metode valueOf() mengembalikan nilai primitif.

+ +

Belajar lebih lagi

+ +

Pengetahuan umum

+ + diff --git a/files/id/glossary/property/index.html b/files/id/glossary/property/index.html new file mode 100644 index 0000000000..dbe9210178 --- /dev/null +++ b/files/id/glossary/property/index.html @@ -0,0 +1,11 @@ +--- +title: Property +slug: Glossary/property +tags: + - Disambiguation + - Glossary +translation_of: Glossary/property +--- +

Pengaertian property bisa diartikan lebih dari satu artian berdasarkan konteks. Mungkin dapat ditujukan ke:

+ +

{{GlossaryDisambiguation}}

diff --git a/files/id/glossary/python/index.html b/files/id/glossary/python/index.html new file mode 100644 index 0000000000..ff93ff587f --- /dev/null +++ b/files/id/glossary/python/index.html @@ -0,0 +1,19 @@ +--- +title: Python +slug: Glossary/Python +translation_of: Glossary/Python +--- +

Python adalah bahasa pemrograman tujuan umum tingkat tinggi. Ini menggunakan pendekatan multi-paradigma, yang berarti mendukung prosedural, berorientasi objek dan beberapa konstruksi pemrograman fungsional. 

+ +

Diciptakan oleh Guido van Rossum sebagai penerus bahasa lain (disebut ABC) antara tahun 1985 dan 1990, dan saat ini digunakan pada sejumlah besar domain, seperti pengembangan web, sebagai bahasa script untuk aplikasi lain dan untuk membangun aplikasi yang sebenarnya.

+ +

Python dikembangkan di bawah lisensi open source yang disetujui OSI, membuatnya dapat digunakan dan didistribusikan secara bebas, bahkan untuk penggunaan komersial. Lisensi Python dikelola oleh Python Software Foundation

+ +

Learn More

+ +

 

+ + diff --git a/files/id/glossary/seo/index.html b/files/id/glossary/seo/index.html new file mode 100644 index 0000000000..af4c5243be --- /dev/null +++ b/files/id/glossary/seo/index.html @@ -0,0 +1,42 @@ +--- +title: SEO +slug: Glossary/SEO +tags: + - Glossary + - Intro + - SEO + - Search + - WebMechanic + - open +translation_of: Glossary/SEO +--- +

SEO (Search Engine Optimization) adalah proses membuat situs web lebih terlihat dalam hasil pencarian, juga disebut meningkatkan peringkat pencarian.

+ +

Mesin pencari {{Glossary("Crawler", "crawl")}} web, mengikuti tautan dari halaman ke halaman, dan mengindeks konten yang ditemukan. Saat Anda mencari, mesin pencari menampilkan konten yang diindeks. Crawler mengikuti aturan. Jika Anda mengikuti aturan-aturan itu dengan cermat ketika melakukan SEO untuk sebuah situs web, Anda memberikan situs peluang terbaik untuk muncul di antara hasil pertama, meningkatkan lalu lintas dan kemungkinan penghasilan (untuk e-niaga dan iklan).

+ +

Mesin pencari memberikan beberapa pedoman untuk SEO, tetapi mesin pencari besar menjaga peringkat hasil sebagai rahasia dagang. SEO menggabungkan pedoman mesin pencari resmi, pengetahuan empiris, dan pengetahuan teoritis dari karya ilmiah atau paten.

+ +

Metode SEO terbagi dalam tiga kelas besar:

+ +
+
teknis
+
Tandai konten menggunakan semantik {{Glossary("HTML")}}. Saat menjelajahi situs web, perayap hanya akan menemukan konten yang ingin Anda indeks.
+
penulisan
+
Tulis konten menggunakan kosakata pengunjung Anda. Gunakan teks dan juga gambar sehingga crawler dapat memahami subjek.
+
kepopuleran
+
Anda mendapatkan sebagian besar lalu lintas ketika situs mapan lain menautkan ke situs Anda.
+
+ +

Belajarlah lagi

+ +

Pengetahuan umum

+ + + +

Pelajari SEO

+ + diff --git a/files/id/glossary/statement/index.html b/files/id/glossary/statement/index.html new file mode 100644 index 0000000000..d13f2c7c30 --- /dev/null +++ b/files/id/glossary/statement/index.html @@ -0,0 +1,21 @@ +--- +title: Statement +slug: Glossary/Statement +translation_of: Glossary/Statement +--- +

Dalam bahasa pemrograman komputer, sebuah statemen/pernyataan adalah sebuah baris kode yang memerintahkan sebuah tugas. Setiap program terdiri dari serangkaian pernyataan.

+ +

Pengetahuan umum

+ + + +

Referensi teknis

+ + + + diff --git a/files/id/glossary/svg/index.html b/files/id/glossary/svg/index.html new file mode 100644 index 0000000000..6a25d78c8b --- /dev/null +++ b/files/id/glossary/svg/index.html @@ -0,0 +1,37 @@ +--- +title: SVG +slug: Glossary/SVG +tags: + - Glossary + - Graphics + - SVG +translation_of: Glossary/SVG +--- +

Scalable Vector Graphics (SVG) merupakan format gambar vektor 2D berbasis sintaks {{Glossary("XML")}}.

+ +

{{Glossary("W3C")}} mulai mengerjakan SVG pada akhir 1990s, namun SVG baru menjadi populer ketika {{Glossary("Microsoft Internet Explorer", "Internet Explorer")}} 9 keluar dengan dukungan SVG. Semua {{Glossary("browser","browsers")}} sekarang mendukung SVG.

+ +

Berbasis pada sintaks {{Glossary("XML")}}, SVG dapat diberikan gaya dengan menggunakan {{Glossary("CSS")}} dan dibuat semakin interaktif dengan menggunakan {{Glossary("JavaScript")}}. HTML5 saat ini memungkinkan direct embedding pada {{Glossary("Tag","tags")}} SVG pada dokumen {{Glossary("HTML")}}.

+ +

Sebagai sebuah format gambar vektor, grafis SVG dapat dirubah skalanya tanpa batas, sehingga membuat SVG sangat berharga dalam {{Glossary("responsive design")}}, karena Anda dapat membuat antarmuka elemen dan grafis yang dapat menyesuaikan pada segala ukuran layar. SVG juga menyediakan banyak alat-alat yang berguna, seperti clipping, masking, filter, dan animasi.

+ +

Pelajari juga

+ +

Pengetahuan umum

+ + + +

Belajar SVG

+ + + +

Informasi teknis

+ + diff --git a/files/id/glossary/url/index.html b/files/id/glossary/url/index.html new file mode 100644 index 0000000000..0a7c62889a --- /dev/null +++ b/files/id/glossary/url/index.html @@ -0,0 +1,27 @@ +--- +title: URL +slug: Glossary/URL +tags: + - Glossary + - Infrastructure +translation_of: Glossary/URL +--- +

Uniform Resource Locator (URL) adalah sebuah teks string yang menentukan dimana sebuah sumber daya dapat ditemukan di internet.

+ +

Dalam konteks {{Glossary("HTTP")}}, URL disebut sebagai "alamat Web" atau "tautan". Browser Anda menampilkan URL pada address bar, seperti https://developer.mozilla.org

+ +

URL juga dapat digunakan untuk mentransfer file ({{Glossary("FTP")}}) , email ({{Glossary("SMTP")}}), dan aplikasi lainnya.

+ +

Pelajari juga

+ +

Pengetahuan umum

+ + + +

Pelajari ini

+ + diff --git a/files/id/glossary/variable/index.html b/files/id/glossary/variable/index.html new file mode 100644 index 0000000000..1e1e3c4392 --- /dev/null +++ b/files/id/glossary/variable/index.html @@ -0,0 +1,21 @@ +--- +title: Variable +slug: Glossary/Variable +translation_of: Glossary/Variable +--- +

Variabel merupakan nama lokasi untuk menyimpan {{Glossary("Value", "value")}}. Dengan begitu nilai tertentu dapat di akses melalui nama variabel yang telah ditentukan.

+ +

Lainnya

+ +

Pengetahuan Umum

+ + + +

Referensi Teknis

+ + diff --git a/files/id/glossary/xml/index.html b/files/id/glossary/xml/index.html new file mode 100644 index 0000000000..b233a5fba7 --- /dev/null +++ b/files/id/glossary/xml/index.html @@ -0,0 +1,11 @@ +--- +title: XML +slug: Glossary/XML +tags: + - Glossary + - XML +translation_of: Glossary/XML +--- +

eXtensible Markup Language (XML) adalah bahasa markup generik yang dispesifikasi oleh W3C. Industri teknologi informasi (IT) menggunakan banyak bahasa yang berdasarkan pada XML sebagai bahasa yang bersifat data-description.

+ +

Tag XML menyerupai tag HTML, tapi XML lebih fleksibel karena memungkinkan pengguna mendefinisikan tagnya sendiri. Cara bertindak XML ini seperti sebuah meta-language, di mana XML dapat digunakan untuk mendefinisikan bahasa lain, seperti {{Glossary("RSS")}}. Selain itu, HTML merupakan bahasa representasi, yang berarti XML adalah bahasa data-description. Ini berarti bahwa XML memiliki jangkauan aplikasi yang lebih luas dari sekedar Web. Misalnya, Web services dapat menggunakan XML untuk pertukaran permintaan dan tanggapan.

diff --git a/files/id/learn/accessibility/index.html b/files/id/learn/accessibility/index.html new file mode 100644 index 0000000000..7206a2393b --- /dev/null +++ b/files/id/learn/accessibility/index.html @@ -0,0 +1,63 @@ +--- +title: Accessibility +slug: Learn/Accessibility +translation_of: Learn/Accessibility +--- +
{{LearnSidebar}}
+ +

Learning some HTML, CSS, and JavaScript is useful if you want to become a web developer. Beyond mechanical use, it's important to learn how to use these technologies responsibly so that all readers might use your creations on the web. To help you achieve this, this module will cover general best practices (which are demonstrated throughout the HTML, CSS, and JavaScript topics), cross browser testing, and some tips on enforcing accessibility from the start. We'll cover accessibility in special detail.

+ +

Overview

+ +

When someone describes a site as "accessible," they mean that any user can use all its features and content, regardless of how the user accesses the web — even and especially users with physical or mental impairments.

+ + + +

By default, HTML is accessible, if used correctly. Web accessibility involves ensuring that content remains accessible, regardless of who and how the web is accessed.

+ +

Prerequisites

+ +

To get the most out of this module, it would be a good idea to either work through at least the first two modules of the HTML, CSS, and JavaScript topics, or perhaps even better, work through the relevant parts of the accessibility module as you work through the related technology topics.

+ +
+

Note: If you are working on a computer/tablet/other devices where you don't have the ability to create your own files, you can try out most of the code examples in an online coding program such as JSBin or Glitch.

+
+ +

Guides

+ +
+
What is accessibility?
+
This article starts off the module with a good look at what accessibility is — this includes what groups of people we need to consider and why, what tools different people use to interact with the web, and how we can make accessibility part of our web development workflow.
+
HTML: A good basis for accessibility
+
A great deal of web content can be made accessible just by making sure the correct HTML elements are always used for the correct purpose . This article looks in detail at how HTML can be used to ensure maximum accessibility.
+
CSS and JavaScript accessibility best practices
+
CSS and JavaScript, when used properly, also have the potential to allow for accessible web experiences, but if misused they can significantly harm accessibility. This article outlines some CSS and JavaScript best practices that should be considered to ensure that even complex content is as accessible as possible.
+
WAI-ARIA basics
+
Following on from the previous article, sometimes making complex UI controls that involve unsemantic HTML and dynamic JavaScript-updated content can be difficult. WAI-ARIA is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. Here we'll show how to use it at a basic level to improve accessibility.
+
Accessible multimedia
+
Another category of content that can create accessibility problems is multimedia — video, audio, and image content need to be given proper textual alternatives, so they can be understood by assistive technologies and their users. This article shows how.
+
Mobile accessibility
+
With web access on mobile devices being so popular, and popular platforms such as iOS and Android having fully-fledged accessibility tools, it is important to consider the accessibility of your web content on these platforms. This article looks at mobile-specific accessibility considerations.
+
+ +

Assessments

+ +
+
Accessibility troubleshooting
+
+

In the assessment for this module, we present to you a simple site with several accessibility issues that you need to diagnose and fix.

+
+
+ +

See also

+ + diff --git a/files/id/learn/common_questions/bagaimana_cara_kerja_internet/index.html b/files/id/learn/common_questions/bagaimana_cara_kerja_internet/index.html new file mode 100644 index 0000000000..b4431bfc93 --- /dev/null +++ b/files/id/learn/common_questions/bagaimana_cara_kerja_internet/index.html @@ -0,0 +1,98 @@ +--- +title: Bagaimana cara kerja Internet +slug: Learn/Common_questions/Bagaimana_cara_kerja_Internet +tags: + - Pemula + - Tutorial + - Web + - WebMechanics +translation_of: Learn/Common_questions/How_does_the_Internet_work +--- +
+

Artikel ini membahas apa itu Internet dan bagaimana ia bekerja.

+
+ + + + + + + + + + + + +
Prasyarat:Tidak ada, namun kami mendorong Anda untuk membaca Artikel tentang menetapkan tujuan proyek terlebih dahulu
Tujuan:Anda akan mempelajari dasar-dasar infrastruktur teknis Web dan perbedaan antara Internet dan Web.
+ +

Ikhtisar

+ +

Internet merupakan tulang punggung dari Web, infrastruktur teknis yang memungkinkan Web tersedia. Pada dasarnya, Internet adalah jaringan besar komputer yang berkomunikasi bersama-sama.

+ +

Sejarah Internet agak tidak jelas. Ini dimulai pada 1960-an sebagai proyek penelitian yang didanai oleh tentara AS, kemudian berkembang menjadi infrastruktur publik pada 1980-an dengan dukungan dari banyak universitas publik dan perusahaan swasta. Berbagai teknologi yang mendukung Internet telah berevolusi dari waktu ke waktu, tetapi cara kerjanya tidak banyak berubah: Internet adalah cara untuk menghubungkan komputer bersama-sama dan memastikan bahwa, apa pun yang terjadi, mereka menemukan cara untuk tetap terhubung.

+ +

Active Learning

+ + + +

Menyelam lebih dalam

+ +

Sebuah jaringan sederhana

+ +

Ketika dua komputer perlu berkomunikasi, Anda harus menghubungkannya, baik secara fisik (biasanya dengan menggunakan Kabel Ethernet) atau nirkabel (seperti sistem WiFi atau Bluetooth). Semua komputer modern dapat memungkinkan koneksi tersebut.

+ +
+

Catatan: Untuk sisa artikel ini, kita hanya akan berbicara tentang kabel fisik, tetapi jaringan nirkabel bekerja dengan cara yang sama.

+
+ +

Two computers linked together

+ +

Jaringan seperti itu tidak terbatas pada dua komputer. Anda dapat menghubungkan banyak komputer sesuai keinginan. Tapi dapat menjadi rumit dengan mudah. Jika Anda mencoba menghubungkan, katakanlah, sepuluh komputer, Anda memerlukan 45 kabel, dengan sembilan colokan per komputer!

+ +

Ten computers all together

+ +

Untuk mengatasi masalah ini, setiap komputer di jaringan terhubung ke komputer kecil khusus yang disebut router. Router ini hanya memiliki satu pekerjaan: perumpamaannya seperti pemberi sinyal di stasiun kereta api, memastikan bahwa pesan yang dikirim dari komputer tertentu tiba di komputer tujuan yang tepat. Untuk mengirim pesan ke komputer B, komputer A harus mengirim pesan ke router, yang pada gilirannya meneruskan pesan ke komputer B dan memastikan pesan tidak dikirim ke komputer C.

+ +

Setelah kita menambahkan router ke sistem, jaringan dari 10 komputer kita membutuhkan 10 kabel: satu pasang untuk setiap komputer dan router dengan 10 colokan.

+ +

Ten computers with a router

+ +

Jaringan dalam jaringan

+ +

Sejauh ini bagus. Tapi bagaimana dengan menghubungkan ratusan, ribuan, miliaran komputer? Tentu saja satu router tidak dapat menskalakan sejauh itu, tetapi, jika Anda membaca dengan seksama, kami mengatakan bahwa router adalah komputer seperti yang lain, jadi apa yang membuat kita tidak bisa menghubungkan dua router bersama? Tidak ada, jadi ayo lakukan itu.

+ +

Two routers linked together

+ +

Dengan menghubungkan tiap komputer ke router, kemudian tiap router ke router, kita dapat menskalakan tanpa batas.

+ +

Routers linked to routers

+ +

Jaringan semacam itu sangat dekat dengan apa yang kita sebut Internet, tetapi kita kehilangan sesuatu. Kita membangun jaringan itu untuk tujuan kita sendiri. Ada jaringan lain di luar sana: teman-teman Anda, tetangga Anda, siapa pun dapat memiliki jaringan komputer sendiri. Tapi itu tidak benar-benar memungkinkan untuk memasang kabel di antara rumah Anda dan seluruh dunia, jadi bagaimana Anda menangani ini? Nah, sudah ada kabel yang terhubung ke rumah Anda, misalnya, tenaga listrik dan telepon. Infrastruktur telepon sudah menghubungkan rumah Anda dengan siapa pun di dunia sehingga itu adalah kabel yang sempurna yang kita butuhkan. Untuk menghubungkan jaringan kita ke infrastruktur telepon, kita memerlukan peralatan khusus yang disebut modem. Modem ini mengubah informasi dari jaringan kita menjadi informasi yang dapat dikelola oleh infrastruktur telepon dan sebaliknya.

+ +

A router linked to a modem

+ +

Maka kita terhubung ke infrastruktur telepon. Langkah selanjutnya adalah mengirim pesan dari jaringan kami ke jaringan yang ingin dijangkau. Untuk melakukan itu, kita akan menghubungkan jaringan ke Penyedia Layanan Internet (ISP). ISP adalah perusahaan yang mengelola beberapa router khusus yang menghubungkan semua bersama-sama dan juga dapat mengakses router ISP lain. Jadi pesan dari jaringan kita dibawa melalui jaringan jaringan ISP ke jaringan tujuan. Internet terdiri dari seluruh infrastruktur jaringan ini.

+ +

Full Internet stack

+ +

Mencari komputer

+ +

Jika Anda ingin mengirim pesan ke komputer, Anda harus menentukan komputer mana. Jadi setiap komputer yang terhubung ke jaringan memiliki alamat unik untuk mengidentifikasinya, yang disebut "alamat IP" (di mana IP adalah singkatan dari Internet Protocol). Ini adalah alamat yang dibuat dari serangkaian empat angka yang dipisahkan oleh titik-titik, misalnya: 192.168.2.10.

+ +

Itu boleh-boleh saja untuk komputer, tetapi kita manusia memiliki waktu yang sulit mengingat alamat semacam itu. Untuk mempermudah, kita bisa mengubah alamat IP dengan nama yang dapat dibaca manusia disebut nama domain. Misal, google.com adalah nama domain yang digunakan di atas alamat IP 173.194.121.32. Jadi menggunakan nama domain adalah cara termudah bagi kita untuk mencapai komputer melalui Internet.

+ +

Show how a domain name can alias an IP address

+ +

Internet dan Web

+ +

Seperti yang Anda lihat, ketika kita menjelajah Web dengan browser Web, kita biasanya menggunakan nama domain untuk mencapai situs web. Apakah itu berarti Internet dan Web adalah hal yang sama? Tidak sesederhana itu. Seperti yang kita lihat, Internet adalah infrastruktur teknis yang memungkinkan miliaran komputer terhubung bersama-sama. Di antara komputer tersebut, beberapa komputer (disebut server Web) dapat mengirim pesan yang dapat dimengerti oleh browser web. Internet adalah infrastruktur, sedangkan Web adalah layanan yang dibangun di atas infrastruktur. Perlu dicatat ada beberapa layanan lain yang dibangun di atas Internet, seperti email dan IRC.

+ +

Langkah selanjutnya

+ + diff --git a/files/id/learn/common_questions/berfikir_sebelum_membuat_kode/index.html b/files/id/learn/common_questions/berfikir_sebelum_membuat_kode/index.html new file mode 100644 index 0000000000..c50aeff182 --- /dev/null +++ b/files/id/learn/common_questions/berfikir_sebelum_membuat_kode/index.html @@ -0,0 +1,180 @@ +--- +title: Bagaimana saya mulai mendesain situs web saya? +slug: Learn/Common_questions/Berfikir_sebelum_membuat_kode +tags: + - Beginner + - Composing + - Menulis + - NeedsActiveLearning + - Pemula + - needsSchema +translation_of: Learn/Common_questions/Thinking_before_coding +--- +

Artikel ini mencakup langkah pertama yang sangat penting dari setiap proyek: tentukan apa yang ingin Anda capai dengannya.

+ + + + + + + + + + + + +
Prasyarat:None
Tujuan:Belajar untuk menentukan tujuan untuk memberikan arahan untuk proyek website Anda.
+ +

Ikhtisar

+ +

Ketika memulai dengan proyek web, banyak orang fokus pada sisi teknis. Tentu saja Anda harus terbiasa dengan teknik kesenian Anda, tetapi yang penting adalah apa yang ingin Anda capai. Ya, tampaknya sudah jelas, tetapi terlalu banyak proyek gagal bukan karena kurangnya pengetahuan teknis, tetapi karena kurangnya tujuan dan visi.

+ +

Jadi, ketika Anda mendapatkan ide dan ingin mengubahnya menjadi sebuah situs web, ada beberapa pertanyaan yang harus Anda jawab sebelum yang lain:

+ + + +

Semua ini disebut ide proyek dan merupakan langkah pertama yang diperlukan untuk mencapai tujuan Anda, apakah Anda seorang pemula atau pengembang yang berpengalaman.

+ +

Active Learning

+ +

Belum ada pembelajaran aktif yang tersedia. Tolong, pertimbangkan untuk berkontribusi.

+ +

Menyelam lebih dalam

+ +

Sebuah proyek tidak pernah dimulai dengan sisi teknis. Musisi tidak akan pernah membuat musik apa pun kecuali mereka terlebih dahulu memiliki gagasan tentang apa yang ingin mereka mainkan — dan hal yang sama berlaku untuk pelukis, penulis, dan pengembang web. Teknik menempati urutan kedua.

+ +

Teknik jelas sangat penting. Musisi harus menguasai instrumen mereka. Tetapi musisi yang baik tidak akan pernah bisa menghasilkan musik yang bagus tanpa ide. Karena itu, sebelum terjun ke sisi teknis — misalnya, kode dan alat — Anda harus mundur dulu dan memutuskan secara terperinci apa yang ingin Anda lakukan.

+ +

Diskusi satu jam dengan teman adalah awal yang baik, tetapi tidak memadai. Anda harus duduk dan menyusun ide-ide Anda untuk mendapatkan pandangan yang jelas tentang jalan apa yang harus Anda ambil untuk mewujudkan ide-ide Anda. Untuk melakukan ini, Anda hanya perlu pena dan kertas dan beberapa waktu untuk menjawab setidaknya pertanyaan-pertanyaan berikut.

+ +
+

Catatan: Ada banyak cara untuk melaksanakan ide proyek. Kita tidak bisa meletakkan semuanya di sini (keseluruhan buku tidak akan cukup). Apa yang akan kami sajikan di sini adalah metode sederhana untuk menangani apa yang para profesional sebut sebagai Project Ideation, Project Planning, danProject Management.

+
+ +

Apa yang sebenarnya ingin saya capai?

+ +

Ini adalah pertanyaan yang paling penting untuk dijawab, karena itu mendorong segalanya. Buat daftar semua tujuan yang ingin Anda capai. Bisa apa saja: menjual barang untuk menghasilkan uang, mengekspresikan pendapat politik, bertemu teman baru, bermain musik dengan musisi, mengumpulkan gambar kucing, atau apa pun yang Anda inginkan.

+ +

Misalkan Anda seorang musisi. Anda bisa berharap demikian:

+ + + +

Setelah Anda memiliki daftar seperti itu, Anda perlu memprioritaskan. Pesanlah tujuan dari yang paling penting hingga yang tidak penting:

+ +
    +
  1. Mencari teman laki-laki/perempuan.
  2. +
  3. Biarkan orang lain mendengarkan musik Anda.
  4. +
  5. Bicara tentang musik Anda.
  6. +
  7. Temui musisi lain.
  8. +
  9. Jual barang.
  10. +
  11. Ajarkan musik melalui video.
  12. +
  13. Publikasikan foto kucing Anda.
  14. +
+ +

Melakukan latihan sederhana ini — menulis tujuan dan menyortirnya — akan membantu Anda keluar ketika Anda harus mengambil keputusan. (Haruskah saya menerapkan fitur ini, gunakan layanan ini, buat desain ini?)

+ +

Jadi sekarang Anda memiliki daftar tujuan yang diprioritaskan, mari beralih ke pertanyaan berikutnya.

+ +

Bagaimana sebuah situs web dapat membawa saya ke tujuan saya?

+ +

Jadi Anda memiliki daftar sasaran dan Anda merasa perlu situs web untuk mencapai sasaran itu. Apakah kamu yakin?

+ +

Mari kita lihat kembali contoh kita. Kami memiliki lima tujuan yang terhubung dengan musik, satu tujuan yang terkait dengan kehidupan pribadi (menemukan pasangan Anda yang signifikan), dan foto-foto kucing yang sama sekali tidak terkait. Apakah masuk akal untuk membangun satu situs web untuk mencakup semua tujuan itu? Apakah itu perlu? Lagi pula, skor layanan web yang ada dapat membawa Anda ke tujuan Anda tanpa membangun situs web baru.

+ +

Menemukan seorang gadis / pacar adalah kasus utama di mana lebih masuk akal untuk menggunakan sumber daya yang ada daripada membangun situs yang sama sekali baru. Mengapa? Karena kita akan menghabiskan lebih banyak waktu membangun dan memelihara situs web daripada benar-benar mencari seorang gadis / pacar. Karena tujuan kita adalah yang paling penting, kita harus menghabiskan energi kita untuk meningkatkan alat yang ada daripada memulai dari awal. Sekali lagi, ada begitu banyak layanan web yang sudah tersedia untuk menampilkan foto yang tidak sepadan dengan upaya untuk membangun situs baru hanya untuk menyebarkan berita tentang betapa lucunya kucing kita.

+ +

Lima tujuan lainnya semuanya terhubung dengan musik. Tentu saja ada banyak layanan web yang dapat menangani tujuan ini, tetapi masuk akal dalam hal ini untuk membangun situs web khusus kami sendiri. Situs web semacam itu adalah cara terbaik untuk mengumpulkan semua hal yang ingin kami terbitkan di satu tempat (baik untuk tujuan 3, 5, dan 6) dan mempromosikan interaksi antara kami dan publik (baik untuk tujuan 2 dan 4). Singkatnya, karena semua tujuan ini berkisar pada topik yang sama, memiliki segalanya di satu tempat akan membantu kita memenuhi tujuan kita dan membantu pengikut kita terhubung dengan kita.

+ +

Bagaimana situs web dapat membantu saya mencapai tujuan saya? Dengan menjawab itu, Anda akan menemukan cara terbaik untuk mencapai tujuan Anda dan menyelamatkan diri dari usaha yang sia-sia.

+ +

Apa yang perlu dilakukan, dan dalam urutan apa, untuk mencapai tujuan saya?

+ +

Sekarang setelah Anda tahu apa yang ingin Anda capai, saatnya untuk mengubah tujuan-tujuan tersebut menjadi langkah-langkah yang dapat ditindaklanjuti. Sebagai catatan tambahan, tujuan Anda tidak harus ditentukan. Mereka berevolusi dari waktu ke waktu bahkan dalam perjalanan proyek, terutama jika Anda menghadapi hambatan yang tidak terduga atau hanya mengubah pikiran Anda.

+ +

Daripada melalui penjelasan panjang, mari kita kembali ke contoh kita dengan tabel ini:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TujuanHal yang harus dilakukan
+

Biarkan orang lain mendengarkan musik Anda

+
+
    +
  1. Rekam musik
  2. +
  3. Siapkan beberapa file audio yang dapat digunakan online (Bisakah Anda melakukan ini dengan layanan web yang ada?)
  4. +
  5. Berikan orang akses ke musik Anda di beberapa bagian situs web Anda
  6. +
+
Bicara tentang musik Anda +
    +
  1. Tulis beberapa artikel untuk memulai diskusi
  2. +
  3. Tentukan bagaimana tampilan artikel
  4. +
  5. Publikasikan artikel-artikel di situs web (Bagaimana melakukan ini?)
  6. +
+
Bertemu musisi lain +
    +
  1. Berikan cara agar orang lain menghubungi Anda (Email? Facebook? Telepon? Mail?)
  2. +
  3. Tetapkan bagaimana orang akan menemukan saluran kontak itu dari situs web Anda
  4. +
+
Jual barang +
    +
  1. Buat barangnya 
  2. +
  3. Simpan barangnya
  4. +
  5. Temukan cara untuk menangani pengiriman
  6. +
  7. Temukan cara untuk menangani pembayaran
  8. +
  9. Buat mekanisme di situs Anda agar orang memesan
  10. +
+
Ajarkan musik melalui video +
    +
  1. Rekam pelajaran video 
  2. +
  3. Siapkan file video yang dapat dilihat secara online (Sekali lagi, dapatkah Anda melakukan ini dengan layanan web yang ada?)
  4. +
  5. Berikan orang akses ke video Anda di beberapa bagian situs web Anda
  6. +
+
+ +

Dua hal yang perlu diperhatikan. Pertama, beberapa item ini tidak terkait dengan web (mis., Rekam musik, tulis artikel). Seringkali aktivitas offline itu lebih penting daripada sisi web proyek. Dalam penjualan, misalnya, jauh lebih penting dan memakan waktu untuk menangani persediaan, pembayaran, dan pengiriman daripada membangun situs web tempat orang dapat memesan.

+ +

Kedua, menetapkan langkah-langkah yang dapat ditindaklanjuti mengarah ke pertanyaan baru yang perlu Anda jawab. Biasanya ternyata ada lebih banyak pertanyaan daripada yang kita duga sebelumnya. (Misalnya, haruskah saya belajar bagaimana melakukan semua ini sendiri, meminta seseorang untuk melakukannya untuk saya, atau menggunakan layanan pihak ketiga?)

+ +

Kesimpulan

+ +

Seperti yang Anda lihat, ide sederhana "Saya ingin membuat situs web" menghasilkan daftar tugas yang panjang, yang hanya tumbuh lebih lama saat Anda memikirkannya. Segera mungkin terlihat luar biasa, tetapi jangan panik. Anda tidak perlu menjawab semua pertanyaan dan Anda tidak perlu melakukan semuanya dalam daftar Anda. Yang penting adalah memiliki visi tentang apa yang Anda inginkan dan bagaimana menuju ke sana. Setelah Anda memiliki visi yang jelas itu, Anda perlu memutuskan bagaimana dan kapan melakukannya. Sederhanakan tugas-tugas besar menjadi langkah-langkah kecil yang dapat ditindaklanjuti. Dan langkah-langkah kecil itu akan menambah pencapaian besar.

+ +

Dari artikel ini, Anda sekarang dapat membuat rencana kasar untuk membuat situs web. Langkah selanjutnya mungkin membaca how the Internet works.

diff --git a/files/id/learn/common_questions/index.html b/files/id/learn/common_questions/index.html new file mode 100644 index 0000000000..b63f533a9a --- /dev/null +++ b/files/id/learn/common_questions/index.html @@ -0,0 +1,135 @@ +--- +title: Pertanyaan Umum +slug: Learn/Common_questions +tags: + - CodingScripting + - Infrastructure + - Learn + - NeedsTranslation + - TopicStub + - Web + - WebMechanics +translation_of: Learn/Common_questions +--- +
{{LearnSidebar}}
+ +

Bagian Area Pembelajaran ini dirancang untuk memberikan jawaban atas pertanyaan umum yang mungkin muncul, yang bukan merupakan bagian dari jalur pembelajaran inti terstruktur (misal artikel pembelajaran HTML atau CSS). Artikel ini dirancang untuk bekerja sendiri.

+ +

Bagaimana Web bekerja

+ +

Bagian ini mencakup mekanika web —pertanyaan yang berkaitan dengan pengetahuan umum tentang ekosistem Web dan bagaimana cara kerjanya.

+ +
+
+

Bagaimana cara kerja Internet?

+
+
Internet merupakan tulang punggung dari Web, infrastruktur teknis yang memungkinkan Web. Pada dasarnya, Internet adalah jaringan besar komputer yang berkomunikasi bersama-sama. Artikel ini membahas bagaimana internet bekerja, pada tingkat dasar.
+
+

 Apa perbedaan antara webpage, website, web server, dan search engine?

+
+
Pada artikel ini kami akan menjelaskan beragam konsep yang berhubungan dengan: webpage, website, web server, dan search engine. Konsep ini akan membingungkan bagi pemula yang baru mempelajari tentang Web, atau (pernah) melakukan kesalahan. Yuk, kita pelajari satu persatu konsep tersebut.
+
+

Apa yang dimaksud URL?

+
+
Dengan {{Glossary("Hypertext")}} dan {{Glossary("HTTP")}}, URL sebuah konsep utama dari Web. Mekanisme ini digunakan oleh {{Glossary("Browser","browsers")}} untuk memperoleh sumber publikasi pada web.
+
+

Apa yang dimaksud nama domain?

+
+
Nama domain adalah bagian dari infrastruktur Internet. Nama domain ini merupakan alamat sebuah web yang dapat dibaca oleh manusia yang berasal dari web server yang tersedia di Internet.
+
+

Apa yang dimaksud dengan web server?

+
+
Kata "Web server" dapat diartikan sebagai sebuah perangkat keras (hardware) atau perangkat lunak (software) yang melayani website kepada klien diseluruh dunia, atau keduanya dapat bekerja sekaligus. Pada artikel ini kita akan mempelajari bagaimana web server bekerja, dan mengapa hal ini sangat penting.
+
+ +
+
Di artikel ini, kita akan mempelajari apa yang dimaksud dengan hyperlink dan kenapa hal ini begitu penting.
+
+ +

Peralatan dan pengaturan

+ +

Pertanyaan yang berhubungan dengan peralatan/software yang dapat anda gunakan untuk membangun website.

+ +
+
+

Berapa banyak biaya yang dibutuhkan untuk membuat website?

+
+
Ketika anda akan launching sebuah website, anda (mungkin) biasa saja tidak akan mengeluarkan biaya apapun. Di artikel ini, kita akan berdiskusi berapa banyak biaya yang dibutuhkan dan apa saja yang anda dapatkan dari yang anda bayar (atau yang anda dapat secara gratis).
+
+

Software yang Saya butuhkan untuk membuat sebuah website?

+
+
Di artikel ini kami akan menjelaskan komponen software apa saja yang anda butuhkan untuk mengedit, upload, atau menampilkan sebuah website.
+
+

Text editor apa saja yang  tersedia?

+
+
Di artikel ini kami menjelaskan hal utama tentang pemilihan dan instalasi text editor untuk pengembangan web.
+
+

What are browser developer tools?

+
+
Every browser features a set of devtools for debugging HTML, CSS, and other web code. This article explains how to use the basic functions of your browser's devtools.
+
+

How do you make sure your website works properly?

+
+
So you've published your website online — very good! But are you sure it works properly? This article provides some basic troubleshooting steps.
+
+

How do you set up a local testing server?

+
+
+
+

This article explains how to set up a simple local testing server on your machine, and the basics of how to use it.

+
+
+
+

How do you upload files to a web server?

+
+
This article shows how to publish your site online with FTP tools — one of the most common ways to get a website online so others can access it from their computers.
+
+

How do I use GitHub Pages?

+
+
This article provides a basic guide to publishing content using GitHub's gh-pages feature.
+
+

How do you host your website on Google App Engine?

+
+
Looking for a place to host your website? Here's a step-by-step guide to hosting your website on Google App Engine.
+
+

What tools are available to debug and improve website performance?

+
+
This set of articles shows you how to use the Developer Tools in Firefox to debug and improve performance of your website, using the tools to check the memory usage, the JavaScript call tree, the amount of DOM nodes being rendered, and more.
+
+ +

Design and accessibility

+ +

This section lists questions related to aesthetics, page structure, accessibility techniques, etc.

+ +
+
+

How do I start to design my website?

+
+
This article covers the all-important first step of every project: define what you want to accomplish with it.
+
+

What do common web layouts contain?

+
+
When designing pages for your website, it's good to have an idea of the most common layouts. This article runs thorugh some typical web layouts, looking at the parts that make up each one.
+
+

What is accessibility?

+
+
This article introduces the basic concepts behind web accessibility.
+
+

How can we design for all types of users?

+
+
This article provides basic techniques to help you design websites for any kind of user — quick accessibility wins, and other such things.
+
+

What HTML features promote accessibility?

+
+
This article describes specific features of HTML that can be used to make a web page more accessible to people with different disabilities.
+
+ +

HTML, CSS and JavaScript questions

+ +

For common solutions to HTML/CSS/JavaScript problems, try the following articles:

+ + diff --git a/files/id/learn/common_questions/pages_sites_servers_and_search_engines/index.html b/files/id/learn/common_questions/pages_sites_servers_and_search_engines/index.html new file mode 100644 index 0000000000..622e047b09 --- /dev/null +++ b/files/id/learn/common_questions/pages_sites_servers_and_search_engines/index.html @@ -0,0 +1,118 @@ +--- +title: >- + What is the difference between webpage, website, web server, and search + engine? +slug: Learn/Common_questions/Pages_sites_servers_and_search_engines +translation_of: Learn/Common_questions/Pages_sites_servers_and_search_engines +--- +
+

In this article, we describe various web-related concepts: web pages, websites, web servers, and search engines. These terms are often confused by newcomers to the web or are incorrectly used. Let's learn what they each mean!

+
+ + + + + + + + + + + + +
Prerequisites:You should know how the Internet works.
Objective:Be able to describe the differences between a web page, a website, a web server, and a search engine.
+ +

Summary

+ +

As with any area of knowledge, the web comes with a lot of jargon. Don't worry, we won't overwhelm you with all of it (we have a glossary if you're curious). However, there are a few basic terms you need to understand at the outset, since you'll hear these expressions all the time as you read on. It's easy to confuse these terms sometimes since they refer to related but different functionalities. In fact, you'll sometimes see these terms misused in news reports and elsewhere, so getting them mixed up is understandable!

+ +

We'll cover these terms and technologies in more detail as we explore further, but these quick definitions will be a great start for you:

+ +
+
web page
+
A document which can be displayed in a web browser such as Firefox, Google Chrome, Opera, Microsoft Internet Explorer or Edge, or Apple's Safari. These are also often called just "pages."
+
website
+
A collection of web pages which are grouped together and usually connected together in various ways. Often called a "web site" or simply a "site."
+
web server
+
A computer that hosts a website on the Internet.
+
search engine
+
A web service that helps you find other web pages, such as Google, Bing, Yahoo, or DuckDuckGo. Search engines are normally accessed through a web browser (e.g. you can perform search engine searches directly in the address bar of Firefox, Chrome, etc.) or through a web page (e.g. bing.com or duckduckgo.com).
+
+ +

Let's look at a simple analogy — a public library. This is what you would generally do when visiting a library:

+ +
    +
  1. Find a search index and look for the title of the book you want.
  2. +
  3. Make a note of the catalog number of the book.
  4. +
  5. Go to the particular section containing the book, find the right catalog number, and get the book.
  6. +
+ +

Let's compare the library with a web server:

+ + + +

Active learning

+ +

There is no active learning available yet. Please, consider contributing.

+ +

Deeper dive

+ +

So, let's dig deeper into how those four terms are related and why they are sometimes confused with each other.

+ +

Web page

+ +

A web page is a simple document displayable by a {{Glossary("browser")}}. Such documents are written in the {{Glossary("HTML")}} language (which we look into in more detail in other articles). A web page can embed a variety of different types of resources such as:

+ + + +
+

Note: Browsers can also display other documents such as {{Glossary("PDF")}} files or images, but the term web page specifically refers to HTML documents. Otherwise, we only use the term document.

+
+ +

All web pages available on the web are reachable through a unique address. To access a page, just type its address in your browser address bar:

+ +

Example of a web page address in the browser address bar

+ +

Web site

+ +

A website is a collection of linked web pages (plus their associated resources) that share a unique domain name. Each web page of a given website provides explicit links—most of the time in the form of clickable portion of text—that allow the user to move from one page of the website to another.

+ +

To access a website, type its domain name in your browser address bar, and the browser will display the website's main web page, or homepage (casually referred as "the home"):

+ +

Example of a web site domain name in the browser address bar

+ +

The ideas of a web page and a website are especially easy to confuse for a website that contains only one web page. Such a website is sometimes called a single-page website.

+ +

Web server

+ +

A web server is a computer hosting one or more websites. "Hosting" means that all the web pages and their supporting files are available on that computer. The web server will send any web page from the website it is hosting to any user's browser, per user request.

+ +

Don't confuse websites and web servers. For example, if you hear someone say, "My website is not responding", it actually means that the web server is not responding and therefore the website is not available. More importantly, since a web server can host multiple websites, the term web server is never used to designate a website, as it could cause great confusion. In our previous example, if we said, "My web server is not responding", it means that multiple websites on that web server are not available.

+ +

Search engine

+ +

Search engines are a common source of confusion on the web. A search engine is a special kind of website that helps users find web pages from other websites.

+ +

There are plenty out there: Google, Bing, Yandex, DuckDuckGo, and many more. Some are generic, some are specialized about certain topics. Use whichever you prefer.

+ +

Many beginners on the web confuse search engines and browsers. Let's make it clear: A browser is a piece of software that retrieves and displays web pages; a search engine is a website that helps people find web pages from other websites. The confusion arises because, the first time someone launches a browser, the browser displays a search engine's homepage. This makes sense, because, obviously, the first thing you want to do with a browser is to find a web page to display. Don't confuse the infrastructure (e.g., the browser) with the service (e.g., the search engine). The distinction will help you quite a bit, but even some professionals speak loosely, so don't feel anxious about it.

+ +

Here is an instance of Firefox showing a Google search box as its default startup page:

+ +

Example of Firefox nightly displaying a custom Google page as default

+ +

Next steps

+ + diff --git a/files/id/learn/common_questions/set_up_a_local_testing_server/index.html b/files/id/learn/common_questions/set_up_a_local_testing_server/index.html new file mode 100644 index 0000000000..0bc57c45d2 --- /dev/null +++ b/files/id/learn/common_questions/set_up_a_local_testing_server/index.html @@ -0,0 +1,108 @@ +--- +title: Bagaimana Anda menyiapkan server pengujian lokal? +slug: Learn/Common_questions/set_up_a_local_testing_server +tags: + - Express + - Flask + - Node + - Pemula + - Python + - django + - server-side + - servers + - sisi-server +translation_of: Learn/Common_questions/set_up_a_local_testing_server +--- +
+

Artikel ini menjelaskan cara menyiapkan server pengujian lokal sederhana di komputer Anda, dan dasar-dasar penggunaannya.

+
+ + + + + + + + + + + + +
Prasyarat:Anda harus terlebih dahulu mengetahui bagaimana cara kerja Internet, dan apa itu server Web.
Tujuan:Anda akan belajar cara mengatur server pengujian lokal.
+ +

Berkas lokal vs. berkas remote

+ +

Di sebagian besar area pembelajaran, kami memberi tahu Anda untuk hanya membuka contoh Anda secara langsung di browser — ini dapat dilakukan dengan mengklik ganda file HTML, drag and drop ke jendela browser, ataupun memilih File > Open... dan menavigasi ke file HTML. Ada banyak cara untuk mencapai ini.

+ +

Jika alamat web diawali dengan file:// diikuti oleh path menuju file di hard drive lokal anda, maka berkas lokal digunakan. Sebaliknya, jika Anda melihat salah satu contoh kami dihosting di GitHub (atau contoh di beberapa remote server lain), alamat web diawali dengan http:// atau https://, untuk menunjukkan berkas tersebut diterima melalui HTTP.

+ +

Masalah dengan menguji file lokal

+ +

Beberapa contoh tidak akan berjalan jika Anda membukanya sebagai file lokal. Hal ini dapat disebabkan oleh berbagai alasan, yang paling mungkin adalah:

+ + + +

Menjalankan server HTTP lokal sederhana

+ +

Untuk mengatasi masalah async request, kita perlu menguji contoh-contoh tersebut dengan menjalankannya melalui server web lokal. OCara paling mudah untuk melakukan ini untuk tujuan kita adalah menggunakan SimpleHTTPServer module pada Python.

+ +

Untuk melakukannya:

+ +
    +
  1. +

    Install Python. Jika anda menggunakan Linux atau Mac OS X, seharusnya sudah tersedia di sistem Anda. Jika anda pengguna Windows, Anda bisa mendapatkan installer dari situs Python dan ikuti instruksi untuk menginstalnya:

    + +
      +
    • Pergi ke python.org
    • +
    • Di bawah bagian Unduh, klik tautan untuk Python "3.xxx".
    • +
    • Pada bagian bawah halaman, pilih Windows x86 executable installer lalu download.
    • +
    • Setelah download selesai, jalankan file tersebut.
    • +
    • Pada halaman awal installer, pastikan anda menceklis "Add Python 3.xxx to PATH" pada checkbox.
    • +
    • Klik Install, kemudian klik Close ketika instalasi selesai.
    • +
    +
  2. +
  3. +

    Bka command prompt (Windows) / terminal (OS X/Linux) anda. tuk mengecek apakah Python telah terinstal, ketikkan perintah berikut:

    + +
    python -V
    +
  4. +
  5. +

    Ini seharusnya mengembalikan nilai versi. Jika ini OK, arahkan ke direktori yang ada di dalam contoh Anda, menggunakan perintah cd.

    + +
    # masukkan nama direktori untuk memasukkannya, misalnya
    +cd Desktop
    +# gunakan dua titik untuk melompat satu tingkat direktori jika perlu
    +cd ..
    +
  6. +
  7. +

    Ketikkan perintah berikut untuk menjalankan server di direktori tersebut:

    + +
    # Jika versi Python yang dikembalikan di atas adalah 3.X
    +python -m http.server
    +# Jika versi Python yang dikembalikan di atas adalah 2.X
    +python -m SimpleHTTPServer
    +
  8. +
  9. +

    Secara default, ini akan menjalankan konten-konten dalam direktori pada web server local, di port 8000. Anda dapat pergi ke server ini dengan pergi ke url  localhost:8000 di web browser anda. Disini anda akan melihat daftar isi dari direktori — klik pada berkas HTML yang akan anda jalankan.

    +
  10. +
+ +
+

Catatan: Jika anda sudah menjalankan sesuatu di port 8000, anda dapat memilih port lain dengan menjalankan perintah server diikuti dengan nilai port alternatif, misal python -m http.server 7800 (Python 3.x) atau python -m SimpleHTTPServer 7800 (Python 2.x). Anda kemudian dapat mengakses konten Anda di localhost:7800.

+
+ +

Menjalankan bahasa sisi server secara lokal

+ +

Modul SimpleHTTPServer (python 2.0) http.server (python 3.0) pada Python sangat berguna, tetapi tidak tahu cara menjalankan kode yang ditulis dalam bahasa seperti Python, PHP atau JavaScript. Untuk mengatasinya Anda akan butuh sesuatu yang lebih — apa yang Anda perlukan tergantung pada bahasa sisi server yang Anda coba jalankan. Beberapa contoh antara lain:

+ + + +
$ cd jalan/ke/kode/php/anda
+$ php -S localhost:8000
diff --git a/files/id/learn/css/index.html b/files/id/learn/css/index.html new file mode 100644 index 0000000000..b20c1b0586 --- /dev/null +++ b/files/id/learn/css/index.html @@ -0,0 +1,67 @@ +--- +title: Learn to style HTML using CSS +slug: Learn/CSS +tags: + - Beginner + - CSS + - CodingScripting + - Debugging + - Landing + - NeedsContent + - NeedsTranslation + - Style + - Topic + - TopicStub + - length + - specificity +translation_of: Learn/CSS +--- +
{{LearnSidebar}}
+ +

Cascading Stylesheets — or {{glossary("CSS")}} — is the first technology you should start learning after {{glossary("HTML")}}. While HTML is used to define the structure and semantics of your content, CSS is used to style it and lay it out. So for example, you can use CSS to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features.

+ +

Learning pathway

+ +

You should really learn the basics of HTML before attempting any CSS. We'd recommend that you work through our Introduction to HTML module first — you can then learn about:

+ + + +

Once you understand the very fundamentals of HTML, we recommend that you learn HTML and CSS at the same time, moving back and forth between the two topics. This is because HTML is far more interesting and much more fun to learn when you apply CSS, and you can't really learn CSS without knowing HTML.

+ +

Before starting this topic, you should also have at least basic familiarity with using computers and using the Web passively (i.e. just looking at it, consuming the content). You should have a basic work environment set up as detailed in Installing basic software, and understand how to create and manage files, as detailed in Dealing with files — both are parts of our Getting started with the web complete beginner's module.

+ +

It is recommended that you work through Getting started with the web before attempting this topic, however, it isn't absolutely necessary; much of what is covered in the CSS basics article is also covered in our Introduction to CSS module, albeit in a lot more detail.

+ +

Modules

+ +

This topic contains the following modules, in a suggested order for working through them. You should definitely start with the first one.

+ +
+
Introduction to CSS
+
This module gets you started with the basics of how CSS works, including selectors and properties, writing CSS rules, applying CSS to HTML, how to specify length, color, and other units in CSS, cascade and inheritance, box model basics, and debugging CSS.
+
Styling text
+
Here we look at text styling fundamentals, including setting font, boldness, and italics, line and letter spacing, and drop shadows and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links.
+
Styling boxes
+
Next up, we look at styling boxes, one of the fundamental steps towards laying out a web page. In this module we recap the box model then look at controlling box layouts by setting padding, borders and margins, setting custom background colors, images and other features, and fancy features such as drop shadows and filters on boxes.
+
CSS layout
+
At this point we've already looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it's time to look at how to place your boxes in the right place in relation to the viewport, and one another. We have covered the necessary prerequisites so you can now dive deep into CSS layout, looking at different display settings, traditional layout methods involving float and positioning, and new, fangled layout tools like flexbox.
+
Responsive design (TBD)
+
With so many different types of devices able to browse the Web these days, responsive web design (RWD) has become a core web development skill. This module will cover the basic principles and tools of RWD, explain how to apply different CSS to a document depending on device features like screen width, orientation, and resolution, and explore the technologies available for serving different videos and images depending on such features.
+
+ +

Solving common CSS problems

+ +

Use CSS to solve common problems provides links to sections of content explaining how to use CSS to solve very common problems when creating a webpage.

+ +

From the beginning, the things you'll do most are to apply colors to HTML elements and their backgrounds, change the size, shape, and position of elements, and add and define borders on elements. But there's not much you can't do once you have a solid understanding of even the basics of CSS. One of the best things about learning CSS is that once you know the fundamentals, usually you have a pretty good feel for what can and can't be done, even if you don't actually know how to do it yet!

+ +

See also

+ +
+
CSS on MDN
+
The main entry point for CSS documentation on MDN, where you'll find detailed reference documentation for all features of the CSS language. Want to know all the values a property can take? This is a good place to go.
+
diff --git a/files/id/learn/getting_started_with_the_web/akan_terlihat_seperti_apa_website_anda/index.html b/files/id/learn/getting_started_with_the_web/akan_terlihat_seperti_apa_website_anda/index.html new file mode 100644 index 0000000000..76600c89ea --- /dev/null +++ b/files/id/learn/getting_started_with_the_web/akan_terlihat_seperti_apa_website_anda/index.html @@ -0,0 +1,117 @@ +--- +title: Akan terlihat seperti apa website kamu? +slug: Learn/Getting_started_with_the_web/Akan_terlihat_seperti_apa_website_anda +tags: + - Aset + - Desain + - Fonts + - 'I10n:prioritas' + - Konten + - Pemula + - Pengkomposisian + - Sederhana + - Usang + - belajar + - pelan-pelan +translation_of: Learn/Getting_started_with_the_web/What_will_your_website_look_like +--- +
{{LearnSidebar}}
+{{PreviousMenuNext("Learn/Getting_started_with_the_web/Installing_basic_software", "Learn/Getting_started_with_the_web/Dealing_with_files", "Learn/Getting_started_with_the_web")}}
+ +
+

Akan terlihat seperti apa website kamu? Diskusikan terlebih dahulu perencanaan dan desain pekerjaan yang harus kamu lakukan untuk websitemu sebelum menulis code, termasuk "Informasi apa saja yang websitemu tawarkan?" "Font dan warna apa saja yang kamu inginkan?" "Apa yang websitemu lakukan?"

+
+ +

Hal penting yang pertama: Perencanaan

+ +

Sebelum melakukan sesuatu, kamu pasti perlu ide. Apa yang harus benar-benar websitemu lakukan? Pada dasarnya sebuah website dapat melakukan apapun, tapi untuk percobaan pertama kamu harus membuat sesuatunya sederhana. Kita akan mulai dengan membuat halaman web sederhana dengan judul, gambar, dan beberapa paragraf.

+ +

Untuk memulai, kamu harus menjawab beberapa pertanyaan berikut ini:

+ +
    +
  1. Tentang apa websitemu? Apakah kamu suka anjing, New York, atau Pacman?
  2. +
  3. Informasi apa yang akan kamu sajikan? Tulis sebuah judul dan beberapa paragraf, dan pikirkan gambar yang ingin kamu tampilkan di halaman website.
  4. +
  5. Akan terlihat seperti apa websitemu, dalam kondisi paling sederhana. Apa warna latar belakang? Apa jenis huruf yang tepat: formal, kartun, bold and loud, halus?
  6. +
+ +
+

Catatan: Proyek yang kompleks perlu pedoman rinci yang masuk ke semua rincian warna, jenis huruf, jarak antara item pada halaman, gaya penulisan yang sesuai, dan sebagainya. Hal ini kadang-kadang disebut panduan desain atau buku merk, dan kamu bisa melihat contohnya di Pedoman Firefox OS.

+
+ +

Gambar desainnya

+ +

Selanjutnya, ambil pulpen dan kertas lalu buat sketsa kasar bagaimana tampilan web kamu nantinya. Untuk web pertamamu, tidak banyak yang akan digambar, tapi kamu harus terbiasa melakukan hal ini. Akan sangat membantu — dan gambarnya tidak perlu sebagus lukisan Van Gogh!

+ +

+ +
+

Catatan: Bahkan nyatanya, dalam website yang kompleks, tim desain biasa nya membuat sketsa kasar dulu, setelah itu baru membuat desain digital nya dengan editor grafik atau teknologi web.

+ +

Dalam tim yang membangun web, biasanya ada seorang desainer grafis dan seorang {{Glossary("UX", "user-experience")}} (UX) desainer. Desainer grafis kerjaanya memperindah tampilan website. Desainer UX kerjaanya lebih abstrak dalam menangani pengalaman dan interaksi pengguna dengan website.

+
+ +

Memilih aset

+ +

Sampai disini, lebih baik mulai memilih konten apa yang akan kamu tampilan dalam halaman webmu.

+ +

Teks

+ +

Kamu harus menulis paragraf dan judul di awal. Jangan sampai lupa.

+ +

Warna tema

+ +

Untuk memilih warna, lihat Color Picker dan pilih warna kesukaanmu. Saat kamu mengklik sebuah warna, kamu akan melihat 6-karakter kode yang aneh seperti #660066. Itulah yang disebut kode hex (kependekan dari hexadecimal). Kopi kodenya ke tempat aman supaya bisa dipakai nanti.

+ +

+ +

Gambar

+ +

Untuk memilih gambar, lihat Google Images dan cari sesuatu yang cocok.

+ +
    +
  1. Ketika kamu sudah menemukan yang kamu inginkan, klik gambarnya.
  2. +
  3. Pilih View image.
  4. +
  5. Di halaman selanjutnya, klik kanan pada gambar (Ctrl + klik di Mac), pilih Save Image As..., dan pilih tempat untuk menyimpan gambarnya. Bisa juga dikopi alamat webnya dari bar alamat perambanmu supaya bisa dipakai nanti.
  6. +
+ +

+ +

+ +

Perlu diingat bahwa kebanyakan gambar di web, termasuk Google Images, memiliki hak cipta. Untuk mengurangi kemungkinan kamu melanggar hak cipta, gunakan filter lisensi dari Google. klik di tombol Tool, lalu pilih opsi Usage rights yang muncul di situ. Kamu sebaiknya pilih opsi semacam Labeled for reuse.

+ +

+ +

Font

+ +

Untuk memilih font:

+ +
    +
  1. Pergi ke Google Fonts dan cari di situ sampai kamu menemukan yang pas. kamu juga bisa menyaring yang berada di kanan layar supaya pencarian lebih mudah
  2. +
  3. Klik Add to collection tepat di sebelah nama font.
  4. +
  5. Klik Use di panel bagian bawah.
  6. +
  7. Di halaman selanjutnya, gulung ke bawah ke seksi 3 dan 4, dan kopi baris kode yang diberi Google ke teks editor untuk dipakai nantinya.
  8. +
+ +

+ +

 

+ +

+ +

{{PreviousMenuNext("Learn/Getting_started_with_the_web/Installing_basic_software", "Learn/Getting_started_with_the_web/Dealing_with_files", "Learn/Getting_started_with_the_web")}}

+ +

 

+ +

Dalam modul ini

+ + diff --git a/files/id/learn/getting_started_with_the_web/css_basics/index.html b/files/id/learn/getting_started_with_the_web/css_basics/index.html new file mode 100644 index 0000000000..110abc26fe --- /dev/null +++ b/files/id/learn/getting_started_with_the_web/css_basics/index.html @@ -0,0 +1,291 @@ +--- +title: CSS dasar +slug: Learn/Getting_started_with_the_web/CSS_basics +tags: + - CSS + - CodingScripting + - 'I10n:priority' + - Pemula + - Styling + - Web + - belajar +translation_of: Learn/Getting_started_with_the_web/CSS_basics +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Getting_started_with_the_web/HTML_basics", "Learn/Getting_started_with_the_web/JavaScript_basics", "Learn/Getting_started_with_the_web")}}
+ +
+

CSS (Cascading Style Sheets) adalah kode yang kamu gunakan untuk memberikan gaya pada halaman web kamu. Dasar-dasar CSS akan menjelaskan apa sajakah yang kamu butuhkan untuk memulai. Kami akan menjawab pertanyaan-pertanyaan seperti: Bagaimana saya dapat membuat teks saya menjadi berwarna hitam atau merah? Bagaimana saya dapat membuat konten saya tampil sedemikian rupa pada layar? Bagaimana saya dapat mendekor halaman web saya dengan latar belakang gambar atau warna-warna?

+
+ +

Apakah CSS itu?

+ +

Seperti HTML, CSS bukanlah sebuah bahasa pemrograman. CSS juga bukanlah sebuah bahasa markup — ia adalah suatu bahasa style sheet. Artinya, dengan CSS kamu dapat mengaplikasikan gaya pada elemen-elemen yang ada dalam dokumen HTML. Sebagai contoh, untuk membuat teks pada seluruh elemen paragraf dalam satu halaman HTML menjadi berwarna merah, kamu akan menulis CSS sebagai berikut:

+ +
p {
+  color: red;
+}
+ +

Salin ketiga baris dari kode CSS tersebut ke dalam suatu file baru di teks editor kamu, lalu simpan file tersebut sebagai style.css di direktori styles kamu.

+ +

Namun kita masih perlu untuk mengaplikasikan CSS tersebut ke dokumen HTML kamu. Jika tidak, CSS tersebut tidak akan berpengaruh pada bagaimana browser akan menampilkan dokumen HTML tersebut. (Kalau kamu belum mengikuti proyek kami, bacalah Dealing with files dan HTML basics untuk mencari tahu apa saja yang perlu kamu lakukan sebelumnya.)

+ +
    +
  1. Buka file index.html kamu dan letakkan baris berikut di suatu tempat di bagian head (di antara tag <head> dan </head>): + +
    <link href="styles/style.css" rel="stylesheet" type="text/css">
    +
  2. +
  3. Simpan index.html dan buka halaman tersebut di browser kamu. Seharusnya muncul tampilan seperti ini:
  4. +
+ +

A mozilla logo and some paragraphs. The paragraph text has been styled red by our css.Jika teks paragraf kamu sekarang berwarna merah, selamat! Kamu berhasil menulis CSS pertama kamu.

+ +

Bagian-bagian dari sebuah CSS ruleset

+ +

Mari kita lihat CSS di atas dengan sedikit lebih detil:

+ +

+ +

Struktur di atas merupakan sebuah rule set (atau sering disebut "rule" supaya lebih singkat). Perhatikan nama dari masing-masing bagian di atas:

+ +
+
Selector
+
Nama elemen HTML di awal rule set. Selector menandai satu atau lebih elemen yang akan diberikan gaya (contoh di sini menggunakan elemen p). Untuk memberikan gaya pada elemen lain, kamu bisa mengubah selector sesuai elemen yang kamu inginkan.
+
Declaration
+
Suatu peraturan seperti color: red; yang menentukan properti mana dari elemen yang ingin kamu beri gaya.
+
Properties
+
Cara kamu memberikan gaya terhadap elemen HTML (contoh di sini, color adalah properti dari {elemen {htmlelement("p")}}.) Di dalam CSS, kamu memilih properti mana saja yang ingin kamu berikan gaya di peraturan kamu.
+
Property value
+
Sebelah sisi kanan properti setelah tanda titik dua, kita memiliki nilai properti, yang memilih satu dari banyak kemungkinan penampilan untuk properti yang diberikan (ada banyak sekali nilai-nilai color selain red).
+
+ +

Perhatikan juga bagian-bagian lain dari sintaks di atas:

+ + + +

Untuk memodifikasi banyak nilai properti sekaligus, kamu hanya perlu menggunakan tanda titik-koma sebagai pemisah, seperti ini:

+ +
p {
+  color: red;
+  width: 500px;
+  border: 1px solid black;
+}
+ +

Memilih banyak elemen

+ +

Kamu juga dapat memilih lebih dari satu tipe elemen dan mengaplikasikan sebuah rule set untuk semua tipe elemen. Untuk melakukannya, kamu dapat menuliskan lebih dari satu selector dipisahkan dengan tanda koma. Sebagai contoh:

+ +
p,li,h1 {
+  color: red;
+}
+ +

Beragam tipe selector

+ +

Ada banyak sekali tipe selector yang berbeda. Di atas, kita hanya mempelajari element selectors, yang memilih seluruh elemen dari tipe yang diberikan di dokumen HTML yang diberikan. Namun kita dapat membuat pilihan yang lebih spesifik daripada itu. Berikut adalah beberapa tipe selector lain yang sering dijumpai:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nama selectorApa yang dipilihContoh
Element selector (kadang-kadang juga disebut sebagai tag atau type selector)Seluruh elemen HTML dari tipe yang diberikan.p
+ Memilih <p>
ID selectorElemen pada halaman dengan ID yang diberikan (pada halaman HTML yang diberikan, kamu hanya boleh memiliki satu elemen per ID).#my-id
+ Memilih <p id="my-id"> atau <a id="my-id">
Class selectorSatu atau lebih elemen pada halaman dengan kelas yang ditentukan (banyak class instances yang dapat muncul di sebuah halaman)..my-class
+ Memilih<p class="my-class"> dan <a class="my-class">
Attribute selectorSatu atau lebih elemen pada halaman dengan atribut yang ditentukan.img[src]
+ Memilih <img src="myimage.png"> namun tidak memilih <img>
Pseudo-class selectorSatu atau lebih elemen yang ditentukan, namun hanya ketika elemen tersebut sedang berada pada state tertentu, seperti sedang di-hover.a:hover
+ Memilih <a>, namun hanya ketika mouse pointer sedang meng-hover link.
+ +

Ada banyak sekali selector lain yang dapat dieksplor, dan kamu dapat menemukan daftar yang lebih detil di Selectors guide kami.

+ +

Fonts dan teks

+ +

Setelah mengeksplor dasar-dasar CSS, mari kita tambahkan aturan-aturan lain dan informasi pada file style.css kita agar contoh yang kita buat memiliki tampilan yang lebih baik. Kita dapat memulai dengan membuat fonts dan teks kita untuk terlihat sedikit lebih baik.

+ +
    +
  1. Pertama-tama, kembalilah dan temukan keluaran dari Google Fonts yang kamu simpan di tempat yang aman. Tambahkan elemen {{htmlelement("link")}} di suatu tempat pada bagian head dari index.html kamu (di manapun di antara tag <head> dan </head>). Elemen link tersebut akan terlihat seperti ini: + +
    <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    +
  2. +
  3. Selanjutnya, hapus aturan yang sudah ada yang kamu miliki di file style.css.
  4. +
  5. Tambahkan baris berikut, dan ubah baris placeholder dengan font-family sungguhan yang kamu dapatkan dari Google Fonts. (font-family berarti jenis font yang ingin kamu gunakan untuk teks.) Aturan ini mengatur jenis font dan ukuran font dasar secara global untuk seluruh halaman (karena <html> merupakan parent element dari seluruh halaman, dan semua elemen di dalam halaman tersebut mewarisi font-size dan font-family yang sama): +
    html {
    +  font-size: 10px; /* px means 'pixels': the base font size is now 10 pixels high  */
    +  font-family: placeholder: this should be the rest of the output you got from Google fonts
    +}
    + +
    +

    Catatan: Apapun yang ada di dalam sebuah dokumen CSS antara /* dan */ adalah komentar CSS, yang akan diabaikan oleh browser ketika browser sedang mengolah kode untuk ditampilkan. Komentar berguna bagi kamu untuk menulis catatan-catatan yang membantu terkait apa yang sedang kamu lakukan.

    +
    +
  6. +
  7. Sekarang kita akan menentukan font size untuk elemen-elemen berisi teks yang ada di dalam body HTML ({{htmlelement("h1")}}, {{htmlelement("li")}}, dan {{htmlelement("p")}}). Kita juga akan menengahkan posisi teks pada heading dan menentukan line height serta letter spacing pada konten bagian body agar dapat lebih mudah dibaca: +
    h1 {
    +  font-size: 60px;
    +  text-align: center;
    +}
    +
    +p, li {
    +  font-size: 16px;
    +  line-height: 2;
    +  letter-spacing: 1px;
    +}
    +
  8. +
+ +

Kamu dapat menyesuaikan nilai-nilai px tersebut untuk mendapatkan desain yang kamu inginkan, namun secara umum desain kamu seharusnya akan terlihat seperti ini:

+ +

a mozilla logo and some paragraphs. a sans-serif font has been set, the font sizes, line height and letter spacing are adjusted, and the main page heading has been centered

+ +

Semua tentang boks

+ +

Satu hal yang akan kamu sadari tentang menulis CSS adalah banyak hal dalam CSS sebenarnya terkait dengan boks — mengatur ukuran, warna, posisi, dan lain-lain. Kebanyakan dari elemen-elemen HTML yang ada di halaman kamu dapat dilihat sebagai banyak boks yang saling bertumpuk di atas satu sama lain.

+ +

a big stack of boxes or crates sat on top of one another

+ +

Pada prinsipnya, susunan CSS didasari oleh box model. Masing-masing blok akan menempati tempat di halaman kamu dengan properti sebagai berikut:

+ + + +

three boxes sat inside one another. From outside to in they are labelled margin, border and padding

+ +

Pada bagian ini kita juga menggunakan:

+ + + +

Ayo kita mulai menambahkan lebih banyak CSS pada halaman kita! Terus tambahkan aturan-aturan baru sampai ke bagian bawah halaman, dan jangan takut untuk bereksperimen dengan menggonta-ganti nilai-nilai untuk melihat bagaimana hasilnya.

+ +

Mengganti warna halaman

+ +
html {
+  background-color: #00539F;
+}
+ +

Aturan ini mengatur warna latar belakang seluruh halaman. Gantilah kode warna di atas menjadi warna apapun yang Anda pilih ketika Anda merencanakan situs Anda.

+ +

Mengatur body

+ +
body {
+  width: 600px;
+  margin: 0 auto;
+  background-color: #FF9500;
+  padding: 0 20px 20px 20px;
+  border: 5px solid black;
+}
+ +

Sekarang kita akan mengatur elemen {{htmlelement("body")}}. Ada beberapa deklarasi di sini, jadi mari kita bahas semuanya satu per satu:

+ + + +

Mengatur posisi dan memberikan gaya pada judul halaman utama kita

+ +
h1 {
+  margin: 0;
+  padding: 20px 0;
+  color: #00539F;
+  text-shadow: 3px 3px 1px black;
+}
+ +

Kamu mungkin sudah menyadari bahwa ada jarak yang cukup jelek di bagian atas body. Hal tersebut terjadi karena beberapa browser mengaplikasikan gaya yang bersifat default ke elemen {{htmlelement("h1")}} element (salah satunya), meski kamu belum memberikan CSS apapun sama sekali! Kedengarannya buruk, namun kita juga menginginkan halaman web yang belum diberikan gaya juga memiliki keterbacaan yang mendasar. Untuk menghilangkan jarak tersebut, kita dapat merubah gaya default tersebut dengan mengatur  margin: 0;.

+ +

Selanjutnya, kita mengatur bagian atas dan bawah padding menjadi 20 piksel, dan membuat warna dari teks heading agar sama dengan warna latar belakang HTML.

+ +

Sebuah properti menarik yang kita gunakan adalah text-shadow, di mana properti ini akan mengaplikasikan bayangan teks ke konten teks dari sebuah elemen. Empat nilai dari properti tersebut adalah sebagai berikut:

+ + + +

Cobalah untuk bereksperimen dengan berbagai nilai berbeda dan lihat hasilnya!

+ +

Memposisikan gambar ke tengah

+ +
img {
+  display: block;
+  margin: 0 auto;
+}
+ +

Akhirnya, kita akan memposisikan gambar ke tengah untuk membuatnya terlihat lebih baik. Kita dapat menggunakan trik  margin: 0 auto lagi seperti yang telah kita lakukan pada bagian body, namun ada satu hal lagi yang perlu dilakukan. Elemen {{htmlelement("body")}} adalah block level, di mana elemen tersebut menempati ruang di halaman dan kita juga dapat mengaplikasikan margin dan nilai-nilai spacing lain pada elemen tersebut. Di sisi lain, gambar adalah contoh dari inline element, yang berarti kita tidak dapat melakukan hal yang sama. Sehingga untuk mengaplikasikan margin pada gambar, kita harus memberikan gambar tersebut perlakuan seperti block level menggunakan display: block;.

+ +
+

Catatan: Jangan khawatir jika kamu belum memahami display: block;dan perbedaan antara block-level dan inline. Kamu akan memahaminya seiring dengan waktu kamu mempelajari CSS lebih dalam. Kamu dapat menemukan lebih lanjut tentang nilai-nilai display yang tersedia di halaman referensi display kami.

+
+ +

Kesimpulan

+ +

Jika kamu sudah mengikuti seluruh instruksi di artikel ini, seharusnya kamu memiliki sebuah halaman yang tampak seperti ini (kamu juga dapat melihat versi kami di sini):

+ +

a mozilla logo, centered, and a header and paragraphs. It now looks nicely styled, with a blue background for the whole page and orange background for the centered main content strip.

+ +

Jika Kamu mengalami kebingungan, kamu bisa membandingkan hasilmu dengan contoh sampel kode kami di Github.

+ +

Di sini, kita hanya baru saja membahas sedikit tentang CSS. Untuk mempelajari lebih lanjut, kunjungi halaman CSS Learning topic milik kami.

+ +

{{PreviousMenuNext("Learn/Getting_started_with_the_web/HTML_basics", "Learn/Getting_started_with_the_web/JavaScript_basics", "Learn/Getting_started_with_the_web")}}

+ +

 

+ +

Dalam modul ini

+ + diff --git a/files/id/learn/getting_started_with_the_web/how_the_web_works/index.html b/files/id/learn/getting_started_with_the_web/how_the_web_works/index.html new file mode 100644 index 0000000000..e59c3083bb --- /dev/null +++ b/files/id/learn/getting_started_with_the_web/how_the_web_works/index.html @@ -0,0 +1,96 @@ +--- +title: Bagaimana Web Bekerja +slug: Learn/Getting_started_with_the_web/How_the_Web_works +tags: + - DNS + - HTTP + - IP + - Klien + - Pemula + - Server + - TCP +translation_of: Learn/Getting_started_with_the_web/How_the_Web_works +--- +
{{LearnSidebar}}
+ +

{{Previous("Learn/Getting_started_with_the_web/Publishing_your_website")}}

+ +
+

Bagaimana cara web bekerja menyediakan pandangan sederhana apa yang terjadi ketika anda melihat halaman web di browser komputer atau handphone.

+
+ +

Teori ini bukan dasar menulis kode web dalam jangka pendek, namun sebelum anda memulai anda akan mendapatkan keuntungan dari memahami apa yang terjadi di belakang.

+ +

Klien dan server

+ +

Komputer yang terhubung ke web dinamakan client dan servers. Diagram sederhana dari cara mereka berinteraksi seperti berikut:

+ +

+ + + +

Bagian lain dari toolbox

+ +

Klien dan server yang di jabarkan di atas tidak menceritakan semuanya. Banyak sekali bagian lain yang terlibat, dan kita akan membahasnya.

+ +

Saat ini, mari kita bayangkan bahwa web adalah sebuah jalan. Pada ujung jalan adalah klien, seperti halnya rumah anda. Di ujung jalan yang lain adalah server, seperti halnya pasar atau swalayan dimana anda membeli sesuatu.

+ +

+ +

Sebagai tambahan dari klien dan server, kita juga membutuhkan:

+ + + +

Lalu apa yang terjadi sebenarnya?

+ +

Ketika anda menuliskan alamat web di browser (dianalogikan seperti berjalan ke pasar):

+ +
    +
  1. Browser menuju ke DNS server dan mencari alamat server yang sebenarnya dimana website berada (anda mencari alamat pasar).
  2. +
  3. Browser mengirim pesan HTTP request ke server meminta salinan dari website untuk di kirim ke klien (anda pergi ke pasar dan memesan barang). Pesan ini, dan semua data dikirim diantara klien dan server, di kirim melalui koneksi internet menggunakan TCP/IP.
  4. +
  5. Server menyetujui permintaan klien, server mengirip pesan "200 OK", yang maksudnya "Tentu anda bisa melihat website tersebut! ini dia", dan kemudian mulai mengirim file website ke browser sebagai bagian - bagian kecil yang disebut data paket (pelayan memberikan barang anda, dan anda membawanya ke rumah anda).
  6. +
  7. Browser menggabungkan bagian - bagian halaman web menjadi sebuah halaman web sempurna dan menampilkannya untuk anda (barang sampai dirumah — barang baru, keren!).
  8. +
+ +

Penjelasan DNS

+ +

Alamat web sebenarnya tidak seperti yang kita tuliskan di browser, untaian yang kamu tuliskan di address bar merupakan untaian dari angka seperti ini: 63.245.217.105.

+ +

Ini disebut alamat IP, dan ini mewakili lokasi dari web. Akan tetapi, akan sulit untuk mengingat, itulah mengapa Domain Name System server dibuat. Ini adalah server spesial yang mencocokkan alamat yang kamu tulis di web browser (seperti "mozilla.org") ke alamat (IP) address website yang sebenarnya.

+ +

Website dapat di jangkau secara langsung melalui IP addresses. Coba buka website Mozilla website dengan menuliskan 63.245.217.105 ke address bar.

+ +

A domain name is just another form of an IP address

+ +

Penjelasan Packet

+ +

Sebelumnya kita menggunakan istilah "packet" untuk menjelaskan format dimana data yang dikirim dari server ke klien. Pada dasarnya data dikirim melalui web, dikirim sebagai ribuan bagian kecil, sehingga pengguna web yang berbeda dapat mengunduh website yang sama dalam waktu yang sama. Jika situs web mengirim sebuah bagian yang besar, hanya satu pengguna yang dapat mengunduh dalam waktu tertentu, dimana akan membuat web sangat tidak efisien dan tidak menyenangkan untuk digunakan.

+ +

Lihat juga

+ + + +

Kredit

+ +

Street photo: Street composing, oleh Kevin D.

+ +

{{Previous("Learn/Getting_started_with_the_web/Publishing_your_website")}}

diff --git a/files/id/learn/getting_started_with_the_web/html_basics/index.html b/files/id/learn/getting_started_with_the_web/html_basics/index.html new file mode 100644 index 0000000000..a2bac009f6 --- /dev/null +++ b/files/id/learn/getting_started_with_the_web/html_basics/index.html @@ -0,0 +1,233 @@ +--- +title: HTML dasar +slug: Learn/Getting_started_with_the_web/HTML_basics +tags: + - CodingScripting + - HTML + - 'I10n:prioritas' + - Pemula + - Web + - belajar +translation_of: Learn/Getting_started_with_the_web/HTML_basics +--- +
hyperlink{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Getting_started_with_the_web/Dealing_with_files", "Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web")}}
+ +
+

HTML (Hypertext Markup Language) adalah kode yang digunakan untuk mengatur tata letak tampilan halaman web dan isinya. Contohnya, konten dapat disusun dalam bentuk sebuah paragraf, penomoran berbentuk titik, atau menampilkan gambar dan tabel. Seperti judulnya, artikel ini akan memberi kamu pemahaman mendasar tentang HTML dan fungsinya.

+
+ +

Jadi sebenarnya apa itu HTML?

+ +

HTML bukan sebuah bahasa pemrograman; HTML adalah bahasa markup yang mendefinisikan struktur konten kamu. HTML terdiri atas serangkaian {{Glossary("element", "elements")}}, yang dapat kamu gunakan untuk menyisipkan atau membungkus konten di dalamnya sehingga mempunyai tampilan tertentu sesuai fungsi elemennya. {{Glossary("Tag", "tags")}} penyisip dapat membuat sebuah kata atau gambar hyperlink ke konten lainnya, memiringkan tulisan, memperbesar atau memperkecil font, dan lain-lain. Lihat contoh konten dibawah ini:

+ +
My cat is very grumpy
+ +

Kalau kita ingin baris ini berdiri sendiri, kita bisa bilang bahwa ini adalah satu paragraf dengan menaruhnya di antara tag paragraf:

+ +
<p>My cat is very grumpy</p>
+ +

Anatomi elemen HTML

+ +

Mari kita jelajahi elemen paragraf ini lebih jauh.

+ +

+ +

Bagian utama dari elemen kita adalah:

+ +
    +
  1. Tag pembuka: Terdiri dari nama elemen (contoh di sini menggunakan p), yang ada di antara kurung sudut pembuka dan penutup. Ini menandakan awal elemen atau di mana elemen mulai bekerja — dalam hal ini dimana paragraf dimulai.
  2. +
  3. Tag penutup: Mirip dengan tag pembuka, bedanya di tag penutup ada garis miring di depan nama elemen. Ini meandakan di mana akhir elemen — dalam hal ini di mana paragraf berakhir. Kebiasaan lupa menulis tag penutup meruapakan suatu kesalahan yang biasa dilakukan pemula yang bisa menyebabkan hasil menjadi ngawur.
  4. +
  5. Konten: Konten elemen yang dalam hal ini hanya teks.
  6. +
  7. Elemen: Tag pembuka dan tag penutup serta konten.
  8. +
+ +

Elemen juga boleh memiliki atribut, yang terlihat seperti berikut:

+ +

+ +

Atribut mengandung informasi ekstra tentang elemen. Atribut tidak tampil di konten aktual. Disini, class adalah nama atribut, dan editor-note adalah nilainya. Atribut class berfungsi memberikan penanda (identifier) pada elemen yang nantinya bisa kamu gunakan untuk diberikan informasi gaya dan lain-lain.

+ +

Sebuah atribut harus mempunyai:

+ +
    +
  1. Jarak antara atribut dan nama elemen (atau atribut sebelumnya, kalau elemen sudah mempunyai atribut).
  2. +
  3. Nama atribut, diikuti tanda sama dengan.
  4. +
  5. Petik pembuka dan penutup diantara nilai atribut.        
  6. +
+ +

Elemen Bersarang

+ +

Kamu bisa menempatkan satu elemen ke dalam elemen lain — istilah ini disebut nesting (persarangan). Kalau kita ingin buat penekanan bahwa kucing kita "very grumpy", kita bisa membungkus kata "very" ke dalam elemen {{htmlelement("strong")}} untuk penekanan.

+ +
<p>My cat is <strong>very</strong> grumpy.</p>
+ +

Tapi kamu harus yakin bahwa elemen kamu benar-benar bersarang: contoh di atas kita buka elemen {{htmlelement("p")}} dulu, lalu elemen {{htmlelement("strong")}}, lalu kita tutup elemen {{htmlelement("strong")}}, lalu elemen {{htmlelement("p")}}. Contoh berikut ini tidak benar:

+ +
<p>My cat is <strong>very grumpy.</p></strong>
+ +

Elemen harus terbuka dan tertutup dengan benar sehingga mereka jelas berada di mana dari elemen lain. Kalau mereka tumpang-tindih seperti di atas, maka web browser kamu akan membuat tebakan terbaiknya pada apa yang ingin kamu utarakan, yang menyebabkan hasil ngawur. Jadi jangan begitu!

+ +

Elemen kosong

+ +

Beberapa elemen tidak punya konten, dan disebut elemen kosong. Ambil elemen {{htmlelement("img")}} yang sudah kita punya di HTML kita:

+ +
<img src="images/firefox-icon.png" alt="My test image">
+ +

Elemen ini mengandung 2 attribut, tapi tidak punya tag </img>, dan tidak punya konten. Ini karena elemen image tidak membungkus konten apapun. Tujuannya adalah mengembed image ke dalam halaman HTML di tempat di berada.

+ +

Anatomi dari dokumen HTML

+ +

Sekarang kita akan lihat bagaimana elemen individu digabung membentuk satu halaman HTML utuh. Ayo kunjungi lagi kode di mana kita menaruh contoh index.html kita (yang kita temui dalam artikel Dealing with files):

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My test page</title>
+  </head>
+  <body>
+    <img src="images/firefox-icon.png" alt="My test image">
+  </body>
+</html>
+ +

Di sini kita punya:

+ + + +

Image

+ +

Coba lihat elemen {{htmlelement("img")}} ini lagi:

+ +
<img src="images/firefox-icon.png" alt="My test image">
+ +

Seperti dikatakan sebelumnya, dia mengembed image ke dalam halaman sesuai posisinya via artibut src, yang berisi path ke file image kita.

+ +

Kita juga telah memasukkan artibut alt (alternative). Dalam atribut ini, kamu menentukan teks deskriptif bagi user yang tidak bisa melihat image, yang mungkin karena:

+ +
    +
  1. User tunanetra. Mereka sering menggunakan tools pembaca screen untuk membaca semua semua alt text.
  2. +
  3. Sesuatu terjadi yang mengakibatkan image tidak tampil. Contohnya, coba sengaja ganti path di dalam atribut src menjadi salah. Kalau kamu simpan dan reload halaman, kamu akan melihat sesuatu seperti ini:
  4. +
+ +

+ +

Kata kunci ini mengandung semua "teks deskriptif". Teks alternatif yang kamu tulis sebaiknya menyediakan cukup informasi kepada pembaca tentang image tersebut. Di contoh ini, teks kita "My test image" tidak bagus. Alternatif lain yang jauh lebih baik untuk logo Firefox kita adalah "The Firefox logo: a flaming fox surrounding the Earth."

+ +

Coba gunakan teks alternatif yang lebih baik untuk image kamu.

+ +
+

Catatan: Cari tahu lebih tentang aksesbilitas di Aksesbilitas landing page MDN.

+
+ +

Menandai teks

+ +

Bagian ini mengkover elemen HTML penting yang kamu gunakan untuk menandai teks.

+ +

Headings

+ +

Elemen heading berfungsi menentukan bahwa bagian tertentu konten kamu berupa heading — atau subheading — dari konten kamu. Sama seperti buku yang punya judul utama, judul bab, dan subjudul, dokumen HTML juga begitu. HTML berisi 6 heading level, {{htmlelement("h1")}}–{{htmlelement("h6")}} meskipun kamu hanya menggunakan paling banyak 3–4:

+ +
<h1>My main title</h1>
+<h2>My top level heading</h2>
+<h3>My subheading</h3>
+<h4>My sub-subheading</h4>
+ +

Sekarang coba tambahkan judul yang pas ke halaman HTML di atas elemen {{htmlelement("img")}} kamu.

+ +

Paragraf

+ +

Seperti dijelaskan sebelumnya, elemen {{htmlelement("p")}} berguna untuk wadah paragraf teks; kamu akan sering menggunakan ini ketika menandai konten teks reguler:

+ +
<p>This is a single paragraph</p>
+ +

Tambahkan sampel teks kamu (kamu pasti sudah punya dari What should your website look like?) ke dalam satu atau lebih paragraf, taruh langsung di bawah elemen {{htmlelement("img")}} kamu.

+ +

List

+ +

Kebanyakan konten web adalah lists, dan HTML punya special elemen untuk ini. Penandaan list selalu mengandung paling sedikit 2 elemen. Tipe list paling umum adalah terurut and tak-terurut:

+ +
    +
  1. List tak-terurut ialah list yang urutan itemnya tidak penting, seperti daftar belanja. Ini dibungkus dalam elemen {{htmlelement("ul")}}.
  2. +
  3. List terurut ialah list yang urutan itemnya penting, seperti resep. Ini dibungkus dalam elemen {{htmlelement("ol")}}.
  4. +
+ +

Tiap item dalam list ditaruh di dalam elemen {{htmlelement("li")}} (item list).

+ +

Contohnya, kalau kita ingin mengubah bagian dari fragmen paragraf berikut menjadi list:

+ +
<p>At Mozilla, we’re a global community of technologists, thinkers, and builders working together ... </p>
+ +

Kita bisa memodifikasi markup ini menjadi:

+ +
<p>At Mozilla, we’re a global community of</p>
+
+<ul>
+  <li>technologists</li>
+  <li>thinkers</li>
+  <li>builders</li>
+</ul>
+
+<p>working together ... </p>
+ +

Coba tambahkan suatu list terurut atau tak-terurut ke halaman contoh kamu.

+ + + +

Link sangat penting — mereka yang membuat web terlihat seperti web! Untuk menambahkan link, kita harus menggunakan elemen sederhana — {{htmlelement("a")}} — "a" singkatan dari "anchor". Untuk membuat teks menjadi link di paragraf kamu, ikuti langkah ini:

+ +
    +
  1. Pilih teks berikut. Kita pilih teks "Mozilla Manifesto".
  2. +
  3. Bungkus teks ke dalam elemen {{htmlelement("a")}}, seperti ini: +
    <a>Mozilla Manifesto</a>
    +
  4. +
  5. Berikan elemen {{htmlelement("a")}} atribut href, seperti ini: +
    <a href="">Mozilla Manifesto</a>
    +
  6. +
  7. Isi nilai atribut ini dengan alamat web yang ingin kamu link: +
    <a href="https://www.mozilla.org/en-US/about/manifesto/">Mozilla Manifesto</a>
    +
  8. +
+ +

Kamu mungkin memperoleh hasil tak terduga jika kamu buang bagian https:// atau http://, disebut protocol, di awal alamat web. Setelah membuat link, klik untuk meyakinkan itu bekerja sebagaimana mestinya.

+ +
+

href mungkin terlihat seperti pilihan yang abu-abu untuk nama atribut. Selalu ingat bahwa dia singkatan dari hypertext reference.

+
+ +

Tambahkan link ke halaman kamu sekarang kalau belum.

+ +

Kesimpulan

+ +

Jika kamu ikuti semua instruksi di artikel ini, kamu akan melihat halaman seperti berikut (kamu juga bisa melihat itu di sini):
+
+ A web page screenshot showing a firefox logo, a heading saying mozilla is cool, and two paragraphs of filler text

+ +

Kalau kamu buntu, kamu bisa bandingkan kerjaanmu dengan contoh code yang sudah selesai punya kita di GitHub.

+ +

Di sini, kita telah menyentuh hanya lapisan luar HTML. Untuk lebih lanjut, pergi ke HTML Learning topic kita.

+ +

{{PreviousMenuNext("Learn/Getting_started_with_the_web/Dealing_with_files", "Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web")}}

+ +

 

+ +

Dalam modul ini

+ + diff --git a/files/id/learn/getting_started_with_the_web/index.html b/files/id/learn/getting_started_with_the_web/index.html new file mode 100644 index 0000000000..d788a4d683 --- /dev/null +++ b/files/id/learn/getting_started_with_the_web/index.html @@ -0,0 +1,76 @@ +--- +title: Mulai Bekerja dengan Web +slug: Learn/Getting_started_with_the_web +tags: + - CSS + - Desain + - Guide + - HTML + - 'I10n:prioritas' + - Index + - Pemula + - Petunjuk + - Teori + - publishing +translation_of: Learn/Getting_started_with_the_web +--- +
{{LearnSidebar}}
+ +
{{Next("Learn/Getting_started_with_the_web/Installing_basic_software")}}
+ +
+

Web Memulai dengan web adalah tulisan ringkas untuk memperkenalkan Anda kepada web development. Anda akan mengatur berbagai tool yang kamu butuhkan untuk membuat sebuah halaman web yang sederhana dan mengunggah kode sederhana Anda.

+
+ +

Alur pembuatan website pertama Anda

+ +

Banyak sekali hal yang harus dilakukan untuk membuat web profesional, jadi jika Anda benar-benar baru dalam pengembangan web, kami anjurkan Anda untuk mulai dari hal yang kecil. Anda tidak akan membuat sebuah website layaknya Facebook, namun kali ini kamu akan membuat website sederhana, jadi mari kita mulai.

+ +

Dengan mengerjakan artikel-artikel berikut, Anda menuju dari nol ke membuat halaman web daring pertama Anda. Berangkat!

+ +

Memasang perangkat lunak dasar

+ +

Banyak sekali tool yang bisa kamu pilih untuk membuat sebuah website. Jika kamu baru mulai, kamu mungkin akan kebingungan dengan banyaknya editor kode, framework, atau testing tool yang ada di luar sana. Di Memasang perangkat lunak dasar, kami akan menunjukkan langkah-langkah dalam pemasangan perangkat lunak yang kamu butuhkan untuk membangun website sederhana Anda.

+ +

Akan seperti apa website Anda terlihat?

+ +

Sebelum Anda mulai menulis kode untuk website Anda, Anda harus merencanakan terlebih dahulu. Informasi apa yang akan Anda muat dalam website tersebut? Font (tulisan) dan warna apa yang akan Anda gunakan? Situs Anda akan terlihat seperti apa? Kami menguraikan metode sederhana yang bisa Anda ikuti untuk merencanakan konten dan desain situs web Anda.

+ +

Mengurus berkas

+ +

Sebuah situs terdiri dari banyak file: wacana, kode, stylesheet, konten media, dan seterusnya. Ketika Anda membangun situs, Anda harus mengatur semua berkas dalam struktur yang baik dan memastikan bahwa semua berkas dapat terhubung satu sama lain. Mengurus berkas menjelaskan bagaimana caranya Anda mengatur berkas dengan baik dan persoalan apa sajakah yang harus Anda perhatikan.

+ +

Dasar-dasar HTML

+ +

Hypertext Markup Language (HTML) adalah kode yang Anda gunakan untuk membuat struktur konten website Anda dan memberikannya arti dan tujuan. Contoh, apakah konten yang saya buat terdiri dari paragraf-paragraf, atau terdiri dari daftar-daftar? Apakah saya perlu memasukan gambar-gambar di halaman saya? Apakah saya memiliki tabel data? Tanpa membuat Anda bingung, Dasar-dasar HTML akan memberikan Anda informasi yang cukup untuk membuat Anda familiar dengan HTML.

+ +

Dasar-dasar CSS

+ +

Cascading Stylesheets (CSS) merupakan kode yang dapat kamu pakai untuk memberikan gaya (style) pada website Anda. Contoh, apakah Anda ingin teks berwarna hitam atau merah? Dimanakah seharusnya konten ditampilkan pada layar? Apa latar belakang gambar dan warna yang seharusnya digunakan untuk mendekorasi website Anda? Dasar-dasar CSS akan membantu Anda memulainya.

+ +

Dasar-dasar JavaScript

+ +

JavaScript adalah bahasa pemrograman yang digunakan untuk menambahkan fitur interaktif di website Anda. Seperti permainan, hal yang akan terjadi ketika tombol ditekan atau data dimasukkan ke dalam form (formulir), penambahan efek styling yang dinamis, animasi, dan banyak lagi. Dasar-dasar JavaScript memberikan Anda sebuah ide tentang apa saja yang dapat Anda lakukan dengan bahasa menakjubkan ini, dan cara memulainya.

+ +

Mempublikasikan website Anda

+ +

Setelah Anda menyelesaikan penulisan kode dan penyusunan berkas dalam pembuatan situs, Anda perlu untuk mempublikasikan website Anda secara online sehingga orang-orang dapat mengaksesnya. Publikasi sampel kode Anda menjelaskan bagaimana cara untuk mempublikasikan sampel kode daring Anda dengan sedikit usaha.

+ +

Cara kerja web

+ +

Ketika Anda mengakses situs kesukaan Anda, banyak hal rumit yang terjadi di dalamnya yang mungkin Anda tidak ketahui. Cara kerja web menguraikan hal-hal yang terjadi ketika Anda melihat halaman web pada komputer Anda.

+ +

Sekarang, mari kita atasi hal yang paling membuat pusing, dari manakah Anda harus membeli hosting untuk situs web Anda.

+ +

Jawaban pertanyaan ini mungkin terlihat sedikit bias, tapi kenyataannya Anda harus percaya dengan suatu yang Anda yakini. Terdapat banyak situs web yang dapat menawarkan jasa hosting gratis tapi segala hal yang gratis itu tidak selalu bagus. Harga jasa-jasa ini terus berubah-ubah, karenanya dibawah ini adalah beberapa perusahaan yang Anda dapat jadikan sebagai rujukan. (Harap dicatat daftar dibawah ini diurutkan tidak berdasarkan kepercayaan atau harga atau pelayanan, ini daftar acak dan tanpa niat dibayar perusahaan):

+ +

godaddy.com, hostgator.com, alibabacloud.com, Amazon Web Services, cluestech.com, namecheap.com, bluehost.com dan banyak lagi. Sepertinya ini bukan yang terbaik tapi setidaknya memiliki rekam jejak yang baik.

+ +

Lihat juga

+ + + +

{{Next("Learn/Getting_started_with_the_web/Installing_basic_software")}}

diff --git a/files/id/learn/getting_started_with_the_web/installing_basic_software/index.html b/files/id/learn/getting_started_with_the_web/installing_basic_software/index.html new file mode 100644 index 0000000000..93abc80228 --- /dev/null +++ b/files/id/learn/getting_started_with_the_web/installing_basic_software/index.html @@ -0,0 +1,76 @@ +--- +title: Menginstal perangkat lunak dasar +slug: Learn/Getting_started_with_the_web/Installing_basic_software +tags: + - Browser + - 'I10n:prioritas' + - Pemula + - Setup + - Tools + - WebMechanics + - belajar + - editor teks +translation_of: Learn/Getting_started_with_the_web/Installing_basic_software +--- +
{{LearnSidebar}}
+ +

{{PreviousNext("Learn/Getting_started_with_the_web","Learn/Getting_started_with_the_web/Akan_terlihat_seperti_apa_website_anda")}}

+ +
+

Pada bagian Memasang perangkat lunak dasarini, kami akan menunjukkan kepada Anda apa saja alat yang Anda butuhkan untuk mengembangkan web sederhana, dan cara memasangnya dengan benar.

+
+ +

Alat apa yang digunakan oleh para profesional?

+ + + +

Alat apa saja yang sebenarnya saya butuhkan sekarang?

+ +

Daftar di atas sepertinya sedikit "menakutkan", tapi untungnya, Anda bisa mulai mengembangkan web tanpa harus tahu banyak tentang hal-hal ini. Pada artikel ini, kita akan membuat Anda siap dengan sesuatu yang paling sederhana, yaitu sebuah pengubah teks dan beberapa peramban web.

+ +

Memasang text editor

+ +

Anda mungkin sudah punya text editor bawaan pada komputer Anda. Secara default Windows mempunyai Notepad dan macOS mempunyai TextEdit. Distro Linux beragam; Ubuntu mempunyai gedit secara default.

+ +

Untuk mengembangkan web, Anda bisa melakukan lebih dari Notepad atau TextEdit. Kami sarankan mulai dengan Visual Studio Code, yang merupakan editor teks gratis, yang menawarkan tinjauan langsung (live preview) dan petunjuk kode.

+ +

Memasang peramban modern

+ +

Untuk saat ini, kita akan memasang dua peramban web desktop untuk menguji kode kita. Pilih sistem operasi kamu di bawah ini dan klik link yang relevan untuk mengunduh installer untuk peramban kesukaan Anda:

+ + + +

Sebelum melanjutkan, kamu harus memasang minimum dua dari browser tersebut untuk pengujian.

+ +

Memasang server web lokal

+ +

Beberapa contoh perlu dijalankan oleh server web agar dapat bekerja. Anda dapat mengetahui cara melakukan ini di Bagaimana Anda membuat server pengujian lokal?

+ +

{{PreviousNext("Learn/Getting_started_with_the_web", "Learn/Getting_started_with_the_web/Akan_terlihat_seperti_apa_website_anda")}}

+ +

Dalam modul ini

+ + diff --git a/files/id/learn/getting_started_with_the_web/javascript_basics/index.html b/files/id/learn/getting_started_with_the_web/javascript_basics/index.html new file mode 100644 index 0000000000..f1fb4295df --- /dev/null +++ b/files/id/learn/getting_started_with_the_web/javascript_basics/index.html @@ -0,0 +1,398 @@ +--- +title: Dasar JavaScript +slug: Learn/Getting_started_with_the_web/JavaScript_basics +tags: + - Beginner + - CodingScripting + - JavaScript + - Web + - belajar +translation_of: Learn/Getting_started_with_the_web/JavaScript_basics +--- +
+

{{LearnSidebar}}

+ +

{{PreviousMenuNext("Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web/Publishing_your_website", "Learn/Getting_started_with_the_web")}}

+
+ +
+

JavaScript adalah bahasa pemograman yang digunakan untuk menambahkan fitur interaktif pada website anda, seperti ketika ingin membuat game, melakukan perubahan ketika mengklik tombol, efek dinamik, animasi, dan masih banyak lagi. Tutorial ini adalah dasar dari JavaScript yang akan memberikan gambaran apa yang bisa anda buat dengan JavaScript.

+
+ +

Apakah JavaScript yang Sebenarnya?

+ +

{{Glossary("JavaScript")}} adalah bahasa pemograman yang sangat matang dan dapat dikolaborasikan dengan dokumen {{Glossary("HTML")}} dan digunakan untuk membuat website yang interaktif. JavaScript diciptakan oleh Brendan Eich yang juga co-founder dari Mozilla project, Mozilla Foundation dan Mozilla Corporation.

+ +

Anda dapat melakukan banyak hal dengan JavaScript. Anda akan memulai dari fitur sederhana seperti menentukan layout, membuat respon ketika mengklik button, caousels, dan gallery gambar. Namun pada akhirnya ketika anda sudah mendapat banyak pengetahuan anda juga akan dapat membuat game, animasi 2D dan 3D, aplikasi yang berhubungan dengan database, dan masih banyak lagi.

+ +

JavaScript sendiri adalah bahasa yang cukup komplek namun sangat fleksibel, dan banyak Developer (Programmer) telah menyediakan tool yang berdiri diatas core JavaScript agar anda dapat menggunakan fungsi - fungsi ekstra, tool tersebut sebagai berikut :

+ + + +

Karena artikel ini hanya sebagai pengenalan, kami tidak ingin membingungkan anda pada tingkat ini dengan membahas secara detail tentang apa perbedaan antara inti bahasa javascript dan perbedaan alat yang digunakan di atas. Anda bisa belajar semuanya nanti pada Area Belajar JavaScript , dan pada semua bagian MDN.

+ +

Di bawah ini kami akan memperkenalkan anda pada beberapa aspek dari inti bahasa, dan anda juga bisa bermain dengan beberapa fitur API Browser. Selamat Bersenang-senang!

+ +

Contoh "Hello World"

+ +

Judul diatas terdengar menarik bukan ?. JavaScript adalah salah satu bahasa yang sangar menarik dari banyak teknologi web yang lain. dan jika anda mengikuti tutorial ini dengan baik, anda dapat menambahkan dimensi baru dan hal lain yang kreatif pada website anda. 

+ +

Namun, JavaScript sedikit lebih rumit dari pada HTML dan CSS, dan anda akan belajar sedikit demi sedikit, dan tetaplah belajar pada langkah-langkah kecil yang kami berikan. Untuk memulainya, kami akan menunjukkan bagaimana cara menambah beberapa skrip JavaScript yang sangat sederhana pada halaman Anda, yakni dengan contoh cara membuat "Hello, world!" (contoh standar pada dasar pemrograman.)

+ +
+

Penting: Jika anda belum mengikuti semua kursus kami, download contoh kode berikut dan gunakan untuk memulai.

+
+ +
+

Catatan: Alasan kita menepatkan elemen {{htmlelement("script")}} di bawah file html adalah ketika HTML di muat oleh browser untuk ditampilkan pada sebuah file. Jika JavaScript dimuat pertama kali dan seharusnya mempengatuhi HTML di bawahnya, kemungkinan ini tidak bisa bekerja, oleh karena itu JavaScript dimuat sebelum HTML bekeja seperti seharusnya. Oleh karena itu, strategi yang terbaik biasanya adalah di bawah halaman.

+
+ +
    +
  1. Pertama-tema, buka situs percobaan anda, dan buatlah sebuah file baru bernama main.js. Simpan di dalam folder scripts.
  2. +
  3. Selanjutnya, buka file index.html Anda, dan masukkan elemen berikut pada sebuah baris bari sebelum tag penutup </body>: +
    <script src="scripts/main.js"></script>
    +
  4. +
  5. Ini sama halnya dengan cara kerja elemen {{htmlelement("link")}} untuk CSS — ini menempatkan JavaScript ke halaman, sehingga dapat memberikan pegaruh pada HTML (CSS, dan lainnya pada halaman).
  6. +
  7. Sekarang tambahkan kode berikut pada file main.js: +
    var myHeading = document.querySelector('h1');
    +myHeading.innerHTML = 'Hello world!';
    +
  8. +
  9. Sekarang pastikan file HTML dan JavaScript disimpan, dan muat index.html di browser. Anda seharusnya mendapatkan hasil seperti berikut:
  10. +
+ +

Apa yang Terjadi?

+ +

Jadi text heading anda telah diubah menjadi "Hello world!" mengunakan JavaScript. Kita melakukannya dengan menggunakan fungsi {{domxref("Document.querySelector", "querySelector()")}} untuk mendapatkan referensi untuk heading, dan menyimpannya di variabel myHeading. Ini sama halnya seperti yang kita lakukan saat menggunakan CSS selector — kita menginginkan untuk melakukan sesuatu ke sebuah elemen, maka kita perlu memilihnya terlebih dahulu.

+ +

Setelah itu, kita tambahkan nilai dari variabel myHeading  properti {{domxref("Element.innerHTML", "innerHTML")}}  ( dimana mewakili konten heading) ke "Hello world!".

+ +

Kursus Kilat Bahasa Dasar

+ +

Mari kita jelaskan beberapa fitur dasar dari bahasa JavaScript, untuk memberi anda pemahaman lebih dalam bagaimana semuanya bekerja. Lebih baik lagi, fitur ini umum diterapkan pada semua bahasa pemrograman. Jika anda memahami fundamental ini, anda berada pada jalur untuk menguasai segala pemrograman!

+ +
+

Penting: Pada artikel ini, coba masukkan contoh kode ke konsole browser anda dan lihat apa yang terjadi. Untuk detail tentang konsole browser, lihat Temukan Browser alat pengembang.

+
+ +
+

Catatan: Fitur seperti ini sangat umum pada semua bahasa pemrograman. Jika anda dapat memahami dasar ini, anda akan mampu memulai pemrograman apapun.

+
+ +

Variabel

+ +

{{Glossary("Variable", "Variables")}} merupakan wadah yang dapat anda beri nilai. Anda bisa memulai mendeklarasikan variabel dengan keyword var, diikuti nama yang anda inginkan:

+ +
var myVariable;
+ +
+

Catatan: Semua baris di JS harus diakhiri dengan semi-colon (;), untuk menandakan akhr baris kode. Jika anda tidak menambahkanya, anda bisa mendapatkan hasil yang tidak diinginkan.

+
+ +
+

Catatan: Anda bisa memanggil variabel apa saja, tapi ada beberapa pembatasan (lihat artikel ini tentang aturan penamaan variabel.)

+
+ +
+

Catatan: JavaScript sangat case sensitive — myVariable sangat berbeda dengan variabel myvariable. jika anda mendapatkan masalah pada kode anda, periksa huruf besar/kecil (casing)!

+
+ +

Setelah mendeklarasikan sebuah variabel, anda bisa menambahkan nilai:

+ +
myVariable = 'Bob';
+ +

Anda dapat mengambil nilai dengan memangil nama variabel:

+ +
myVariable;
+ +

Anda bisa melakukan operasi ini dalam satu baris jika anda menginginkanya:

+ +
var myVariable = 'Bob';
+ +

Setelah memberikan nilai pada variabel, setelah itu anda bisa mengubah nilainya:

+ +
var myVariable = 'Bob';
+myVariable = 'Steve';
+ +

Catat bahwa variabel memiliki Tipe data yang berbeda:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
VariabelPenjelasanContoh
{{Glossary("String")}}Teks String. Untuk menamdakan bahwa variabel adalah sebuah string anda perlu menambahkan tanda kutip.var myVariable = 'Bob';
{{Glossary("Number")}}Angka/number. Angka tidak menggunakan tanda kutip.var myVariable = 10;
{{Glossary("Boolean")}}Nilai True/False. true/false merupakan keyword spesial di JS, dan tidak perlu menggunakan kutip.var myVariable = true;
{{Glossary("Array")}}Struktur yang memungkinkan anda menyimpan lebih dari satu nilai dalam sebuah reference.var myVariable = [1,'Bob','Steve',10];
+ Panggil setiap member array seperti ini: myVariable[0], myVariable[1], etc.
{{Glossary("Object")}}Pada dasarnya, semua. Semuanya di javascript adalah sebuah objek, dan dapat disimpan dalam variabel. Ingatlah untuk anda belajar.var myVariable = document.querySelector('h1');
+ All of the above examples too.
+ +

Jadi kenapa kita memerlukan variabel? Baik, variable dibutuhkan dalam berbagai hal menarik di pemrograman. Jika nilainya tidak berubah, maka anda tidak dapat melakukan sesuatu hal yang bersifat dinamis, seperti menyesuaikan pesan salam ke pengunjung website anda, atau mengubah gambar yang tampil di galeri, dan masih banyak lagi.

+ +

Komentar

+ +

Anda dapat menambahkan komentar di kode Javascript, seperti halnya pada CSS. Di JavaScript, sebaris komentar ditulis seperti berikut:

+ +
// Ini adalah komentar
+ +

Namun anda juga dapat menggunakan lebih dari satu baris komentar seperti yang  anda lakukan pada CSS:

+ +
/*
+Ini adalah komentar
+lebih dari satu baris
+*/
+ +

Operator

+ +

{{Glossary("operator")}} pada dasarnya adalah simbol matematika yang bertindak atas dua nilai (atau variabel yang berisi nilai) dan menghasilkan nilai baru. Pada tabel dibawah anda bisa melihat beberapa operator yang sederhana, disertai contoh untuk anda coba di konsole browser.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorPenjelasanSimbolContoh
penambahan / penggabunganDigunakan untuk menambahkan nilai satu dengan lainnya menjadi sebuah nilai baru, atau menggabungkan dua teks string.+6 + 9;
+ "Hello " + "world!";
pengurangan, Perkalian, pembagianYang ini hasilnya sama seperti yang kita kenal di matematika dasar.-, *, /9 - 3;
+ 8 * 2; // perkalian di JS menggunakan tanda bintang (*)
+ 9 / 3;
operator penugasanAnda telah melihat ini sebelumnya, penugasan di JS digunakan untuk memberikan nilai pada variabel.=var myVariable = 'Bob';
Operator kesetaraanMelakukan tes untuk melihat apakah suatu nilai sama dengan nilai pembanding, dan mengembalikan nilai hasil berupa boolean true/false .===var myVariable = 3;
+ myVariable === 4;
Negasi, tidak sama denganSering digunakan bersama operator kesetaraan, operator negasi di JS sama dengan logical NOT — membalik nilai true menjadi false dan sebaliknya.!, !== +

Ekspresi dasarnya bernilai true, namun pada pernamdingan mengembalikan nilai false karena kita menggunakan negasi:

+ +

var myVariable = 3;
+ !myVariable === 3;

+ +

Disini kita mencoba "Apakah  myVariable NOT ( tidak ) sama dengan 3". Mengembalikan nilai false, karena disitu pembandingnya sama dengan 3.

+ +

var myVariable = 3;
+ myVariable !== 3;

+
+ +

Disana masih banyak lagi yang dapat anda pelajari, tapi ini dulu yang kita cukup pahami. Lihat Operator dan ekspressi untuk daftar yang lebih lengkap.

+ +
+

Catatan: Mencampur tipe data akan memyebabkan hasil yang tidak kita duga ketika melakukan perhitungan, jadi hati - hati ketika memberikan nilai pada variabel pastikan memberikan nilai yang sesuai, dan mendapatkan hasil sesuai yang anda inginkan. Misalnya menuliskan "35" + "25" pada konsol. Kenapa anda tidak mendapatkan nilai yang anda inginkan? karena tanda kutip mengubah angka menjadi teks string — anda hanya mendapatkan nilai string yang digabungkan, dan bukan angka yang ditambahkan. Jika anda memasukkan 35 + 25, anda akan mendapatkan nilai yang sesuai.

+
+ +

Kondisional

+ +

Kondisional adalah struktur kode yang memungkinkan anda untuk menguji apakah ekspresi mengembalikan nilai yang benar atau tidak, dan kemudian menjalankan perintah lain tergantung pada hasilnya. Bentuk umum dari kondisional disebut if ... else. Contoh seperti berikut:

+ +
var esKrim = 'coklat';
+if (esKrim === 'coklat') {
+  alert('Yay, Aku suka eskrim coklat!');
+} else {
+  alert('Hahhh, tapi sukanya coklat...');
+}
+ +

Ekspresi didalam if ( ... ) dalah pengujian — disini menggunakan operator kesetaraan (seperti yang dijelaskan sebelumnya) untuk membandingkan variabe esKrim dengan string coklat untuk melihat keduanya sama. Jika hasil perbandingan mengembalikan nilai true, kode blok pertama akan dijalankan. Jika tidak, akan di lewati dan kode blok selanjutnya akan di jalankan, tepatnya setelah statement else.

+ +

Fungsi

+ +

{{Glossary("Function", "Functions")}} merupakan cara encapsulasi fungsi yang ingin anda gunakan kembali, jadi anda dapat memanggil dengan hanya sebuah nama fungsi, dan tidak harus menulis semua kodenya lagi setiap kali anda ingin menggunakannya kembali. Anda telah melihat beberapa fungsi diatas, seperti:

+ +
    +
  1. +
    var myVariable = document.querySelector('h1');
    +
  2. +
  3. +
    alert('Halo!');
    +
  4. +
+ +

Fungsi ini merupakan built-in browser untuk anda gunakan kapanpun.

+ +

Jika anda melihat sesuatu yang mirip dengan nama variabel, tapi menggunakan tanda kurung — () — setelahnya, anda dapat memastikan bahwa itu adalah fungsi. Fungsi terkadang menggunakan {{Glossary("Argument", "arguments")}} — bit data yang dibutuhkan untuk dapat menjalankan fungsinya. Argumen di tulis di dalam tanda kurung, dan dipisahkan dengan koma jika memiliki lebih dari satu argumen.

+ +

Misal, Fungsi alert() membuat kotak pop-up terlihat pada jendela browser, namun kita perlu membaerikan string sebagai sebuah argumen untuk mengatakan pada fungsi alert()pesan apa yang harus di tampilkan pada kotak po-pup.

+ +

Berita bagusnya adalah kita dapat membuat fungsi anda sendiri — pada contoh berikut kita menulis sebuah fungsi sederhana dengan menggunakan dua argumen dan mengalikannya menjadi nilai baru:

+ +
function kalikan(angka1,angka2) {
+  var hasil = angka1 * angka2;
+  return hasil;
+}
+ +

Coba jalankan fungsi diatas pada konsole, kemudian coba gunakan fungsi anda beberapa kali, misal.:

+ +
kalikan(4,7);
+kalikan(20,20);
+kalikan(0.5,3);
+ +
+

Catatan: Statement return mengatakan pada browser untuk mengembalikan nilai variabel hasil keluar dari fungsi sehingga dapat digunakan. Hal ini diperlukan karena variabel yang didefinisikan di dalam blok kode atau cakupan fungsi hanya akan tersedia didalam fungsi itu sendiri. Hal ini disebuat variable {{Glossary("Scope", "scoping")}} (baca lebih lanjut tentang variable scoping disini.)

+
+ +

Events

+ +

Untuk membuat hal yang interaktif pada website, anda perlu menggunakan event — kode struktur ini mendengarkan setiap hal yang terjadi pada browser, dan kemudian memungkinkan anda menjalankan kode sebagai respon pada hal yang terjadi tersebut. Contoh yang paling terjadi adalah click event, dimana di suarakan oleh browser ketika mouse anda mengklik pada elemen seperti link, tombol atau yang lainnya. Untuk menunjukkannya, coba tambahkan kode berikut pada konsol anda, kemudian coba klik pada halaman web tersebut:

+ +
document.querySelector('html').onclick = function() {
+    alert('Ouch! Stop poking me!');
+}
+ +

Banyak sekali cara untuk melampirkan event pada sebuah elemen; disini kita memilih elemen HTML dan membuat properti handler onclick yang sama dengan fungsi anonim (fungsi tanpa nama) yang berisi kode yang ingin kita jalankan ketika event terjadi.

+ +

Catat bahwa

+ +
document.querySelector('html').onclick = function() {};
+ +

sama dengan

+ +
var myHTML = document.querySelector('html');
+myHTML.onclick = function() {};
+ +

Hanya untuk lebih pendek saja menuliskannya.

+ +

Meningkatkan contoh website kita

+ +

Sekarang kita meninjau beberapa dasar JavaScript, mari tambahkan bebrapa fitur dasar ke contoh situs kita untuk memberi anda satu langkah kepada suatu yang mungkin.

+ +

Menambahkan pengubah gambar

+ +

Pada bagian ini kita akan menambahkan gambar lain pada situs kita, dan tambahkan beberapa Javascript sederhana untuk mengubah antara keduanya ketika gambar di-klik.

+ +
    +
  1. Pertama, cari gambar lain yang ingin anda gunakan di situs anda. Pastikan ukurannya sama dengan gambar pertama, atau kurang lebih sama.
  2. +
  3. Simpan gambar pada folder images anda.
  4. +
  5. Pada file main.js , tuliskan kode JavaScript berikut (Jika kode Javascript hello world masih disana, hapus saja): +
    var myImage = document.querySelector('img');
    +
    +myImage.onclick = function() {
    +    var mySrc = myImage.getAttribute('src');
    +    if(mySrc === 'images/firefox-icon.png') {
    +      myImage.setAttribute ('src','images/firefox2.png');
    +    } else {
    +      myImage.setAttribute ('src','images/firefox-icon.png');
    +    }
    +}
    +
  6. +
  7. Simpan semua file dan muat index.html di browser. Sekarang kita klik gambarnya, seharusnya berubah tampilannya menjadi gambar yang satunya!
  8. +
+ +

Kita menyimpan referensi ke elemen gambar Kita dalam variabel myImage. Selanjutnya, Kita membuat fungsi tanpa nama (fungsi "anonim") pada property variabel pengendali event onclick. Sekarang, setiap kali elemen gambar ini diklik:

+ +
    +
  1. Kita mendapatkan nilai atribut src dari gambar.
  2. +
  3. Kita menggunakan kondisional untuk memeriksa apakah nilai src sama dengan path gambar asli: +
      +
    1. Jika ya, kita mengubah nilai src ke path gambar kedua, memaksa gambar lain dimuat dalam elemen {{htmlelement ("image")}}.
    2. +
    3. Jika tidak (artinya harus sudah mengalami perubahan), kita mengubah nilai src kembali ke jalur gambar asli, untuk membalikkannya kembali ke semula.
    4. +
    +
  4. +
+ +

Menambahkan pesan selamat datang yang dinamis

+ +

Selanjutnya, Kita akan menambahkan sedikit kode lagi untuk mengubah judul halaman untuk menyertakan pesan pembuka yang dinamis saat pengguna pertama kali masuk ke situs. Pesan pembuka ini akan bertahan saat pengguna meninggalkan situs dan kemudian kembali lagi. Kita juga akan menyertakan opsi untuk mengubah pengguna dan oleh karena itu pesan selamat datang diperlukan setiap waktu.

+ +
    +
  1. Pada index.html, Tambahkan baris berikut sebelum elemen {{htmlelement("script")}}: + +
    <button>Change user</button>
    +
  2. +
  3. Pada main.js tambahkan kode berikut di bagian bawah file, persis seperti yang tertulis - ini mengacu pada tombol baru yang akan kita tambahkan, judulnya, dan simpan pada variabel: +
    var myButton = document.querySelector('button');
    +var myHeading = document.querySelector('h1');
    +
  4. +
  5. Sekarang tambahkan fungsi berikut untuk mengatur ucapan yang dinamis - ini belum berinteraksi tapi nanti akan kita gunakan: +
    function setUserName() {
    +  var myName = prompt('Please enter your name.');
    +  localStorage.setItem('name', myName);
    +  myHeading.innerHTML = 'Mozilla is cool, ' + myName;
    +}
    + Fungsi ini berisi fungsi prompt() yang menampilkan kotak dialog seperti alert(). Perbedaannya adalah prompt() meminta pengguna untuk memasukkan data, dan menyimpan data tersebut dalam variabel saat tombol dialog OK ditekan. Dalam kasus ini, kita meminta pengguna memasukkan namanya. Selanjutnya, kita memanggil API yang disebut localStorage, yang memungkinkan kita menyimpan data di browser, dan mengambilnya nanti. Kita menggunakan fungsi setItem LocalStorage () untuk membuat dan menyimpan item data yang disebut 'name', dan menetapkan nilainya ke variabel myName yang berisi nama pengguna yang dimasukkan. Akhirnya, kita mengatur innerHTML dari judul ke string, ditambahk nama penggunanya.
  6. +
  7. Selanjutnya, tambahkan blok if ... else — kita bisa memanggil kode inisialisasi, sebagai pengatur saat aplikasi pertama kali dimuat: +
    if(!localStorage.getItem('name')) {
    +  setUserName();
    +} else {
    +  var storedName = localStorage.getItem('name');
    +  myHeading.innerHTML = 'Mozilla is cool, ' + storedName;
    +}
    + Blok kode pertama kali menggunakan operator negasi (logical NOT) untuk memeriksa apakah item data ada - jika tidak ada, fungsi setUserName() dijalankan untuk membuatnya. Jika sudah ada (misalnya pengguna mengaturnya saat mereka mengunjungi situs), kita mengambil nama yang tersimpan dengan menggunakan getItem() dan menetapkan innerHTML dari judul ke string, ditambah nama pengguna, sama seperti yang kita lakukan di dalam setUserName().
  8. +
  9. Terakhir, letakkan pengendali event di bawah onclick pada tombolnya, sehingga saat diklik fungsi setUserName() dijalankan. Hal ini memungkinkan pengguna untuk mengatur nama baru kapan pun mereka mau dengan menekan tombol: +
    myButton.onclick = function() {
    +  setUserName();
    +}
    +
  10. +
+ +

Sekarang saat pertama kali mengunjungi situs, akan meminta nama pengguna kemudian memberi pesan yang dinamis kepada anda. Kemudian Anda bisa mengganti nama kapan saja dengan menekan tombol. Sebagai bonus tambahan, karena namanya tersimpan di dalam localStorage, tetap ada setelah situs ditutup, jadi pesan yang dinamis akan tetap ada saat Anda membuka situs ini lagi!

+ +

Kesimpulan

+ +

Jika Anda telah mengikuti semua petunjuk dalam artikel ini, halaman yang Anda buat harus terlihat seperti ini (Anda juga dapat melihat versi kami di sini):

+ +

+ +

Jika Anda terjebak kebingungan, Anda selalu bisa membandingkan pekerjaan Anda dengan contoh kode yang telah kami selesaikan di Github.

+ +

Di sini, kita hanya benar-benar menenepuk permukaan JavaScript. Jika Anda telah menikmati pembelajarannya dan ingin belajar lebih dalam dengan studi Anda, masuklah ke Panduan JavaScript kami.

+ +

{{PreviousMenuNext("Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web/Publishing_your_website", "Learn/Getting_started_with_the_web")}}

diff --git a/files/id/learn/getting_started_with_the_web/mengelola_file/index.html b/files/id/learn/getting_started_with_the_web/mengelola_file/index.html new file mode 100644 index 0000000000..04cc90ec4b --- /dev/null +++ b/files/id/learn/getting_started_with_the_web/mengelola_file/index.html @@ -0,0 +1,123 @@ +--- +title: Berurusan dengan file +slug: Learn/Getting_started_with_the_web/Mengelola_file +tags: + - CodingScripting + - File + - HTML + - 'I10n:prioritas' + - Panduan + - Pemula + - Teori + - website +translation_of: Learn/Getting_started_with_the_web/Dealing_with_files +--- +
+

{{LearnSidebar}}

+
+ +
{{PreviousMenuNext("Learn/Getting_started_with_the_web/What_will_your_website_look_like", "Learn/Getting_started_with_the_web/HTML_basics", "Learn/Getting_started_with_the_web")}}
+ +
+

Suatu website terdiri atas banyak file, seperti konten teks, kode, stylesheet, konten media, dan lain-lain. Ketika kamu sedang membuat sebuah website, kamu perlu merangkai file-file ini menjadi sebuah struktur yang sesuai pada komputermu, memastikan file-file tersebut saling terhubung antara satu dengan lainnya, dan memastikan semua konten sudah benar sebelum akhirnya kamu unggah mereka ke suatu server. Bagian ini akan membahas isu-isu yang perlu kamu ketahui sehingga kamu dapat membuat struktur file yang sesuai untuk website kamu.

+
+ +

Di mana website kamu berada dalam komputermu?

+ +

Ketika kamu sedang mengerjakan satu website lokal pada komputer pribadimu, kamu harus menyimpan semua file terkait pada satu folder sesuai dengan struktur website yang diunggah ke server. Folder ini dapat kamu simpan di manapun sesukamu, tetapi kamu harus meletakkannya di suatu tempat yang mudah ditemukan, seperti Desktop, pada folder Home, atau pada folder root dari hard drive kamu.

+ +
    +
  1. Pilih tempat untuk menyimpan proyek-proyek websitemu. Buatlah sebuah folder dengan nama web-projects (atau nama lain yang serupa). Di sinilah proyek-proyek websitemu akan disimpan. 
  2. +
  3. Di dalam folder sebelumnya, buat lagi satu folder untuk menyimpan website pertamamu. Berilah nama test-site (atau nama lainnya yang lebih menarik).
  4. +
+ +

Catatan untuk pengaturan huruf kapital dan penggunaan spasi

+ +

Kamu akan menyadari bahwa di artikel ini, kami akan meminta kamu untuk menamai folder dan file dalam huruf kecil tanpa spasi. Hal ini karena:

+ +
    +
  1. Banyak komputer, terutama web server, bersifat case-sensitive (sensitif terhadap huruf kapital dan kecil). Sebagai contoh, jika kamu meletakkan gambar pada situs seperti test-site/GambarSaya.jpg, dan kemudian pada file lain kamu akan memanggil gambar tersebut dengan  test-site/gambarsaya.jpg, maka kemungkinan hal tersebut tidak akan berhasil. 
  2. +
  3. Peramban, web server dan bahasa pemrograman tidak menangani spasi secara konsisten. Contohnya. jika kamu menggunakan spasi pada nama filemu, beberapa sistem akan memperlakukannya sebagai dua nama file. Beberapa server akan mengganti spasi pada nama filemu dengan "%20" (kode karakter untuk spasi pada URI) sehingga akan merusak semua tautanmu. Akan lebih baik bila kamu memisahkan kata-kata menggunakan tanda hubung (-), dibandingkan underscore (_): file-saya.html vs. file_saya.html.
  4. +
+ +

Jawaban singkatnya adalah kamu sebaiknya menggunakan tanda hubung (-) untuk nama file mu. Mesin pencari Google memperlakukan tanda hubung sebagai pemisah kata, namun ia tidak memperlakukan underscore sebagai hal yang sama. Atas dasar hal tersebut, sebaiknya kamu membiasakan diri menulis nama folder dan file dengan huruf kecil, tanpa spasi, dan dengan kata-kata yang dipisahkan oleh tanda hubung, kecuali bila kamu tahu apa yang kamu lakukan. Hal ini dapat membantumu terhindar dari masalah ke depan.

+ +

Bagaimana struktur yang harus kamu gunakan untuk websitemu?

+ +

Berikutnya, mari kita lihat struktur seperti apa yang diperlukan oleh website percobaan kita. Hal yang paling sering kamu temukan pada proyek website apapun yang kita buat adalah sebuah file indeks HTML dan folder untuk menyimpan gambar, file CSS, dan file script. Ayo buat sekarang juga:

+ +
    +
  1. index.html: File ini secara umum berisi halaman beranda, yaitu gambar dan teks yang bisa dilihat orang saat pertama kali membuka websitemu. Dengan menggunakan pengedit teks, buat sebuah file baru bernama index.html dan simpan di dalam folder test-site.
  2. +
  3. Folder images: Folder ini berisi semua gambar yang akan digunakan pada websitemu. Buatlah sebuah folder bernama images di dalam folder test-site
  4. +
  5. Folder styles: Folder ini berisi kode CSS yang digunakan untuk kontenmu (contoh: pengaturan teks dan warna latar belakang). Buat folder bernama styles di dalam folder test-site.
  6. +
  7. Folder scripts: Folder ini berisi semua kode JavaScript yang digunakan untuk menambah fungsionalitas interaktif pada websitemu. Buat folder bernama scripts di dalam folder test-site.
  8. +
+ +
+

Catatan: Pada komputer Windows, kamu mungkin mengalami kesulitan saat melihat nama file, karena Windows memiliki opsi Hide extensions for known file types yang aktif secara default. Umumnya, kamu dapat mematikannya dengan masuk ke Windows Explorer, pilih Folder options..., hilangkan centang pada kotak cek Hide extensions for known file types, lalu klik OK. Untuk informasi spesifik mengenai versi Windowsmu, kamu dapat melakukan pencarian di web.

+
+ +

Jalur/Path file

+ +

Agar file-file dapat berkomunikasi antara satu dengan lainnya, kamu harus menyediakan sebuah path file — sebuah rute sehingga satu file dapat mengetahui di mana lokasi file yang lainnya. Untuk mendemonstrasikannya, kita akan memasukkan sedikit HTML ke dalam file index.html, dan membuatnya menampilkan gambar yang kamu pilih pada artikel "Akan terlihat seperti apa website kamu?" 

+ +
    +
  1. Salin gambar yang kamu pilih sebelumnya ke folder image.
  2. +
  3. Buka file index.html, dan tambahkan kode berikut ke dalam file sama seperti di bawah. Abaikan maksud dari semuanya untuk saat ini — kita akan melihat struktur lebih detilnya di seri berikut. +
    <!DOCTYPE html>
    +<html>
    +  <head>
    +    <meta charset="utf-8">
    +    <title>My test page</title>
    +  </head>
    +  <body>
    +    <img src="" alt="My test image">
    +  </body>
    +</html>
    +
  4. +
  5. Baris <img src="" alt="My test image"> adalah kode HTML yang menyisipkan gambar ke dalam halaman. Kita perlu memberitahu HTML di mana letak gambar tersebut. Gambar berada pada folder images yang sejajar dengan file index.html. Untuk menelusuri struktur file dari index.html ke gambar kita, jalur file yang kita butuhkan adalah images/your-image-filename. Sebagai contoh, gambar tersebut kami namai  firefox-icon.png, sehingga jalur file-nya menjadi images/firefox-icon.png.
  6. +
  7. Sisipkan jalur file tersebut ke dalam kode HTML kamu di antara tanda petik pada kode src="".
  8. +
  9. Simpan file HTML, kemudian buka halaman tersebut pada peramban webmu (double-click file). Kamu akan melihat halaman web barumu menampilkan gambarmu!
  10. +
+ +

A screenshot of our basic website showing just the firefox logo - a flaming fox wrapping the world

+ +

Beberapa aturan umum untuk jalur file:

+ + + +

Untuk sekarang, itulah semua yang perlu kamu ketahui.

+ +
+

Catatan: Sistem file pada Windows biasanya menggunakan garis miring terbalik (\), bukan garis miring (/), contohnya C:\windows. Hal ini tidak masalah pada HTML — bahkan jika kamu sedang mengembangkan websitemu di Windows, kamu tetap dapat menggunakan garis miring di kodemu.

+
+ +

Apa lagi yang harus dilakukan?

+ +

Begitulah untuk saat ini. Struktur foldermu seharusnya terlihat seperti ini:

+ +

A file structure in mac os x finder, showing an images folder with an image in, empty scripts and styles folders, and an index.html file

+ +

{{PreviousMenuNext("Learn/Getting_started_with_the_web/What_will_your_website_look_like", "Learn/Getting_started_with_the_web/HTML_basics", "Learn/Getting_started_with_the_web")}}

+ +

 

+ +

 

+ +

Dalam modul ini

+ + diff --git a/files/id/learn/getting_started_with_the_web/publishing_your_website/index.html b/files/id/learn/getting_started_with_the_web/publishing_your_website/index.html new file mode 100644 index 0000000000..ad9eaa3f64 --- /dev/null +++ b/files/id/learn/getting_started_with_the_web/publishing_your_website/index.html @@ -0,0 +1,111 @@ +--- +title: Publishing your website +slug: Learn/Getting_started_with_the_web/Publishing_your_website +tags: + - Beginner + - 'I10n:priority' + - Learn + - NeedsTranslation + - Web + - publishing +translation_of: Learn/Getting_started_with_the_web/Publishing_your_website +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Getting_started_with_the_web/JavaScript_basics", "Learn/Getting_started_with_the_web/How_the_Web_works", "Learn/Getting_started_with_the_web")}}
+ +
+

Setelah anda selesai menulis kode dan mengatur file yang membentuk website anda, anda perlu menaruh file - file tersebut secara online agar orang lain bisa menemukannya. Artikel ini menunjukan bagaimana kode sederhana anda online dengan sedikit usaha.

+
+ +

Apa pilihannya?

+ +

Menerbitkan sebuah website bukanlah topik yang sederhana, terutama karena banyak sekali cara yang bisa digunakan. Pada artikel ini kita tidak akan membahas keseluruhan cara. Namun, kita akan membahas pro dan kontra dari ketiga strategi yang sangat luas dari pandangan pemula, dan kita akan mencoba salah satu cara untuk digunakan.

+ +

Mencari hosting dan nama domain

+ +

Jika anda ingin mengontrol keseluruhan website anda, maka anda perlu menyisikan uang untuk membeli:

+ + + +

Setiap website professional menerbitkan website dengan cara ini.

+ +

Sebagai tambahan, anda memerlukan program {{Glossary("FTP", "File Transfer Protocol (FTP)")}} (lihat Berapa mahal harganya: software untuk lebih detail) untuk mengirim file website ke server. Program FTP sangat bervariasi, tapi umumnya anda perlu login ke web server anda menggunakan detail yang diberikan oleh perusahaan hosting anda (mis. username, password, host name). Kemudian program akan menampilkan file lokal dan file di web server ada dalam dua jendela, jadi anda bisa mentransfernya dari komputer lokal ke web server dan sebaliknya:

+ +

+ +

Tips mencai hosting dan domain

+ + + +

Menggunakan alat online seperti GitHub, Google App Engine atau Dropbox

+ +

Beberapa alat yang memungkinkan anda menerbitkan website secara online:

+ + + +

Tidak seperti hosting umumnya, alat tersebut dapat digunakan secara gratis, tapi anda hanya mendapatkan fitur terbatas atau yang hanya disediakan.

+ +

Menggunakan IDE berbasis web seperti Thimble

+ +

Banyak sekali aplikasi web yang meniru lingkungan pengembangan situs web, memungkinkan anda untuk menulis HTML, CSS, dan JavaScript, kemudian menampilkan hasil kode itu saat diberikan sebagai situs web - semuanya ada dalam satu tab browser. Secara umum alat ini cukup mudah, bagus untuk dipelajari, dan gratis (untuk fitur dasar), dan mereka meng-host halaman yang anda berikan di alamat web yang unik. Namun, fitur dasarnya cukup terbatas, dan aplikasi biasanya tidak menyediakan ruang hosting untuk aset (seperti gambar).

+ +

Cobalah bermain dengan beberapa contoh ini, dan lihatlah mana yang paling Anda sukai:

+ + + +

+ +

Penerbitan Melalui Github Pages

+ +

Sekarang mari kami menuntun anda melalui cara mudah menerbitkan situs anda melalui GitHub Pages.

+ +
    +
  1. Pertama, daftar akun GitHub dan verifikasi alamat email anda.
  2. +
  3. Selanjutnya, anda perlu membuat repository untuk menempatkan file anda.
  4. +
  5. Pada halaman ini, pada kolom Nama Repository, tulis username.github.io, dimana username merupakan username akun github anda. Sebagai contoh, teman kita rmsubekti perlu menuliskan rmsubekti.github.io.
    + Juga centang Initialize this repository with a README kemudian klik Create repository.
  6. +
  7. Setelah itu, seret konten folder website anda ke repository dan klik Commit changes.
    + +
    +

    Catatan: Pastikan folder website anda memiliki file index.html.

    +
    +
  8. +
  9. +

    Sekarang kunjugi username.github.io dari browser anda untuk melihat website anda di sajikan secara online. Sebagai contoh, untuk username chrisdavidmills, maka kunjugi chrisdavidmills.github.io.

    + +
    +

    Catatan: Mungkin akan memakan waktu sedikit lama agar website anda dapat disajikan. Jika tidak segera disajikan, anda mungkin perlu menunggu beberapa menit kemudian coba lagi.

    +
    +
  10. +
+ +

Pelajari lebih lanjut, kunjungi GitHub Pages Help.

+ +

Bacaan lebih lanjut

+ + + +

{{PreviousNext("Learn/Getting_started_with_the_web/JavaScript_basics", "Learn/Getting_started_with_the_web/How_the_Web_works")}}

diff --git a/files/id/learn/how_to_contribute/index.html b/files/id/learn/how_to_contribute/index.html new file mode 100644 index 0000000000..0a64757fc1 --- /dev/null +++ b/files/id/learn/how_to_contribute/index.html @@ -0,0 +1,108 @@ +--- +title: Cara berkontribusi untuk Area Belajar di MDN +slug: Learn/How_to_contribute +tags: + - Dokumentasi + - MDN + - MDN Meta + - Proyek MDC + - belajar + - kontribusi +translation_of: Learn/How_to_contribute +--- +

{{LearnSidebar}}

+ +

Jika Anda berada disini, itu mungkin karena Anda tertarik berkontribusi dalam Area Belajar MDN. Itu berita bagus!

+ +

Pada halaman ini, Anda akan menemukan semua hal yang Anda butuhkan untuk mulai membantu menigkatkan konten pembelajaran MDN. Ada banyak hal yang dapat Anda lakukan, tergantung pada seberapa waktu yang anda miliki dan apakah Anda seorang pemula, seorang pengembang web, atau seorang guru.

+ +
+

Catatan: Jika Anda telah menjadi kontributor MDN, jangan ragu untuk memeriksa ulang halaman status dokumentasi untuk melacak pekerjaan yang sudah dilakukan dan melihat apa yang menjadi prioritas menulis.

+
+ +
+

Catatan: Kontributor menggunakan Trello board untuk mengorganisir diri. Jika Anda ingin menggunakannya, hanya dengan membuat akun Trello dan ping Jeremie untuk memberikan Anda akses tulis ke papan.

+
+ +

Saya seorang pemula

+ +

Mengagumkan! Pemula sangat penting untuk menciptakan dan memberikan umpan balik pada materi pembelajaran. Anda memiliki perspektif yang unik pada artikel ini sebagai bagian dari target pengunjung, yang dapat membuat Anda menjadi Anggota yang sangat berharga dari tim kami. memang, jika Anda menggunakan salah satu artikel kami untuk mempelajari sesuatu dan Anda terjebak, atau menemukan artikel yang membingungkan dalam berbagai cara, Anda dapat memperbaikinya atau biarkan kami tahu tentang masalahnya sehingga kami dapat memperbaikinya.

+ +

Kontribusi juga merupakan cara yang bagus untuk bersenang-senang sambil belajar hal-hal baru. Jika Anda pernah merasa kebingungan atau memiliki pertanyaan, jangan ragu untuk menghubungi kami di mailing list kami atau Saluran IRC (lihat di bagian bawah halaman ini untuk rincian).
+
+ Berikut adalah beberapa cara yang disarankan untuk Anda dapat berkontribusi:

+ +
+
Tambahkan tag ke artikel kami (5 menit)
+
Pemberian tag konten MDN adalah salah satu cara termudah untuk berkontribusi MDN. Seperti banyak fitur kami menggunakan tag untuk membantu menyajikan informasi dalam konteks, membantu dengan pemberian tag merupakan kontribusi yang sangat berharga. Lihatlah daftar istilah dan artikel pembelajaran tanpa tag untuk memulai.
+
Membaca dan meninjau daftar istilah (15 menit)
+
Sebagai pemula, kita perlu mata segar Anda untuk melihat konten kami. Jika Anda menemukan entri glossary yang sulit untuk dipahami, itu berarti bahwa entrinya perlu ditingkatkan. Jangan ragu untuk membuat perubahan yang Anda anggap perlu. Jika Anda tidak berpikir Anda memiliki keterampilan yang diperlukan untuk mengedit entri sendiri, setidaknya memberitahu kami di mailing list kami.
+
Menulis daftar istilah baru (1 jam)
+
Ini adalah cara yang paling efektif untuk belajar sesuatu yang baru. Pilih sebuah konsep yang ingin  Anda pahami, dan saat Anda belajar tentang hal itu, tulislah daftar istilah tentang hal itu. Menjelaskan sesuatu kepada orang lain adalah cara yang bagus untuk "memperbaiki" pengetahuan ke dalam otak Anda, dan membantu Anda memahami diri sendiri, sambil membantu orang lain. Setiap orang menang!
+
Membaca dan meninjau artikel pembelajaran (2 jam)
+
Hal ini sangat mirip meninjau daftar istilah (lihat di atas); itu hanya membutuhkan waktu lebih lama, karena artikel ini biasanya sedikit lebih lama.
+
+ +

Saya seorang pengembang web

+ +

Fantastis! Keterampilan teknis Anda adalah apa yang kami butuhkan untuk memastikan kami menyediakan konten teknis yang akurat untuk pemula. Karena ini adalah bagian tertentu dari MDN didedikasikan untuk belajar Web, pastikan penjelasan Anda sesederhana mungkin, tanpa begitu sederhana itu tidak akan berguna. Ini lebih penting untuk dimengerti daripada menjadi terlalu tepat.

+ +
+
Membaca dan meninjau daftar istilah (15 menit)
+
Sebagai pengembang web, kita perlu Anda untuk memastikan konten kami secara teknis akurat tanpa terlalu bertele-tele. Jangan ragu untuk membuat perubahan yang Anda anggap perlu. Jika Anda ingin mendiskusikan isi sebelum mengedit, ping kami di mailing list kami atau Saluran IRC.
+
Menulis daftar istilah baru (1 jam)
+
Menjelaskan istilah teknis merupakan cara yang sangat baik untuk belajar menulis yang akurat sekaligus sederhana secara teknis. Para pemula akan berterima kasih kepada Anda atas hal ini. Kami memiliki banyak istilah yang belum terdefinisikan, yang membutuhkan perhatian Anda. Pilih salah satu dan kerjakan.
+
Membaca dan meninjau artikel pembelajaran (2 jam)
+
Ini adalah hal yang sama seperti meninjau entri glossary (lihat di atas); hanya saja membutuhkan sedikit lebih banyak waktu karena artikelnya sedikit panjang.
+
Menulis artikel pembelajaran baru (4 jam)
+
MDN kurang artikel sederhana tentang menggunakan teknologi web (HTML, CSS, JavaScript, dll). Kami juga memiliki konten lama di MDN yang layak untuk dikaji dan dibentuk kembali. Dorong kemampuan Anda sampai batas untuk membuat teknologi web yang dapat digunakan bahkan oleh pemula.
+
Buat latihan, contoh kode atau alat pembelajaran aktif (? hours)
+
Semua artikel pembelajaran kita membutuhkan apa yang kita sebut materi "belajar aktif", karena orang belajar lebih baik dengan melakukanya sendiri. Materi tersebut adalah latihan atau konten interaktif yang membantu pengguna untuk menerapkan dan memanipulasi ricnian konsep dalam sebuah artikel. Ada banyak cara yang mungkin untuk membuat konten pembelajaran yang aktif, dari menciptakan contoh kode dengan JSFiddle atau serupa, untuk membangun konten interaktif yang sepenuhnya dapat diubah dengan Thimble. Lepaskan kreativitas Anda!
+
+ +

Saya seorang Pengajar

+ +

MDN memiliki sejarah panjang keunggulan teknis, tapi kami tidak memiliki rasa yang baik dari cara terbaik untuk mengajarkan konsep untuk pendatang baru. Di sinilah kami perlu Anda, sebagai pengajar atau pendidik. Anda dapat membantu kami memastikan bahwa materi yang kami berikan baik, jalur pendidikan yang masuk akal bagi pembaca kami.

+ +
+
Membaca dan meninjau daftar istilah (15 menit)
+
Periksa daftar istilah dan jangan takut untuk membuat perubahan yang menurut Anda perlu. Jika Anda ingin mendiskusikan konten sebelum mengedit, ping kami di mailing list atau Saluran IRC kami.
+
Menulis daftar istilah baru (1 jam)
+
Jelas, definisi sederhana dari istilah dan ikhtisar dasar konsep dalam daftar istilah penting dalam memenuhi kebutuhan pemula '. Pengalaman Anda sebagai seorang pendidik dapat membantu membuat daftar istilah yang sangat baik; kami memiliki banyak istilah yang belum terdefinisikan yang perlu Anda perhatikan. Pilih satu dan kerjakan.
+
Tambahkan ilustrasi dan/ atau skema artikel (1 jam)
+
Seperti yang anda ketahui, ilustrasi merupakan bagian penting dari isi pembelajaran apapun. Ini adalah sesuatu yang kita sering kekurangan di MDN dan keterampilan Anda dapat membuat perbedaan di area itu. Kunjungi artikel yang kekurangan konten ilustrasi dan pilih salah satu yang Anda inginkan untuk membuat ilustrasi.
+
Membaca dan meninjau artikel pembelajaran (2 jam)
+
Hal ini mirip dengan meninjau daftar istilah (lihat di atas), tetapi membutuhkan lebih banyak waktu karena artikel biasanya sedikit lebih panjang.
+
Menulis artikel pembelajaran baru (4 jam)
+
Kita perlu artikel yang mudah tentang ekosistem Web dan topik fungsional lain di sekitarnya. Karena ini artikel pembelajaran perlu mendidik daripada mencoba untuk benar-benar menutupi segala sesuatu yang perlu diketahui, pengalaman Anda dalam mengetahui apa yang harus diliput dan bagaimana hal itu akan menjadi aset besar.
+
Buat latihan, kuis atau alat pembelajaran interaktif (? jam)
+
Semua artikel pembelajaran kita membutuhkan apa yang kita sebut materi "belajar aktif". Materi tersebut adalah latihan atau konten interaktif yang membantu pengguna belajar untuk menggunakan dan memanipulasi konsep yang dirincikan dalam sebuah artikel. Ada banyak hal yang dapat Anda lakukan di sini, dari membuat kuis untuk membangun konten interaktif yang sepenuhnya dapat diubah dengan Thimble. Lepaskan kreativitas Anda!
+
Buat jalur studi (? jam)
+
Dalam rangka memberikan tutorial yang progresif dan mudah dipahami, kita perlu membentuk konten jalur studi. Ini adalah cara untuk mengumpulkan konten yang ada dan mencari apa kekurangan artikel pembelajaran untuk menuliskannya.
+
diff --git a/files/id/learn/html/howto/index.html b/files/id/learn/html/howto/index.html new file mode 100644 index 0000000000..ef45d155ad --- /dev/null +++ b/files/id/learn/html/howto/index.html @@ -0,0 +1,142 @@ +--- +title: Menggunakan HTML dalam masalah umum +slug: Learn/HTML/Howto +translation_of: Learn/HTML/Howto +--- +
{{LearnSidebar}}
+ +

Daftar berikut menunjukkan solusi untuk masalah umum sehari-hari yang harus kamu selesaikan dengan menggunakan HTML.

+ +
+
+

Struktur Dasar

+ +

Penerapan HTML yang paling dasar adalah struktur dokumen. Jika kamu baru mengenal HTML, kamu harus mulai dengan ini.

+ + + +

Dasar semantik tingkat dasar

+ +

HTML mengkhususkan dalam memberikan informasi semantik untuk dokumen, jadi HTML menjawab banyak pertanyaan yang mungkin kamu miliki tentang bagaimana cara menyampaikan pesan kamu dengan baik di dokumen kamu.

+ + +
+ +
+ + +

Salah satu alasan utama HTML adalah memudahkan navigasi {{Glossary("hyperlink", "hyperlinks")}}, which can be used in many different ways:

+ + + +

Gambar & multimedia

+ + + +

Scripting & styling

+ +

HTML hanya mengatur struktur dokumen. Untuk mengatasi masalah tampilan, gunakan{{glossary("CSS")}}, atau gunakan scripting atau javascript untuk membuat halaman Anda interaktif.

+ + + +

Embedded content

+ + +
+
+ +

Masalah yang tidak umum atau tingkat lanjut

+ +

Selain dasar-dasarnya, HTML sangat kaya dan menawarkan fitur-fitur canggih untuk memecahkan masalah yang kompleks. Artikel ini membantu kamu menangani kasus penggunaan yang kurang umum yang mungkin kamu hadapi:

+ +
+
+

Forms (Formulir)

+ +

Forms adalah struktur HTML kompleks yang dibuat untuk mengirim data dari halaman web ke server web. Kami mendorong kamu untuk membaca panduan lengkap kami. Di sinilah kamu harus memulai:

+ + + +

Tabular information ( Informasi Tabel)

+ +

Beberapa informasi, yang disebut data tabular, perlu diatur ke dalam tabel dengan kolom dan baris. Itu salah satu struktur HTML paling kompleks, dan menguasainya tidaklah mudah:

+ + + +

Data representation (Representasi data)

+ + +
+ +
+

Sematik text tingkat lanjut

+ +
    +
  • Cara membuat garis baru
  • +
  • How to mark changes (added and removed text) — see the {{htmlelement("ins")}} and {{htmlelement("del")}} elements.
  • +
+ +

Advanced images & multimedia

+ + + +

Internationalization

+ +

HTML tidak monolingual. Alat ini menyediakan sesuatu untuk menangani masalah internasionalisasi umum.

+ + + +

Performa

+ + +
+
+ +

     

+ +
+
+
diff --git a/files/id/learn/html/index.html b/files/id/learn/html/index.html new file mode 100644 index 0000000000..8f5726db10 --- /dev/null +++ b/files/id/learn/html/index.html @@ -0,0 +1,58 @@ +--- +title: HTML +slug: Learn/HTML +tags: + - HTML + - Panduan + - Pemula + - Pengenalan + - Topik + - belajar +translation_of: Learn/HTML +--- +
{{LearnSidebar}}
+ +

Untuk membangun websites, Anda harus mengetahui tentang {{Glossary('HTML')}} — teknologi dasar yang digunakan untuk menentukan struktur halaman web,yaitu HTML. HTML adalah kerangka dari suatu halaman web. Anda dapat menggunakan HTML untuk menentukan konten mana yang termasuk dalam paragraf, judul, link, gambar, input form, multimedia player dan lain-lain.

+ +

+ +

Jalur belajar

+ +

Idealnya, Anda harus memulai perjalanan belajar dengan mempelajari HTML. Memulai dengan membaca Introduction to HTML. Anda kemudian dapat melanjutkan untuk belajar tentang topik yang lebih maju seperti:

+ + + +

Sebelum topik dimulai, Anda harus mempunyai paling sedikit akrab menggunakan komputer, dan menggunakan web secara pasif (yaitu hanya melihat, yang mengkonsumsi konten). Anda harus memiliki lingkungan kerja dasar yang diatur seperti yang terperinci dalam Installing basic software, dan memahami bagaimana membuat dan mengelola file, seperti yang dijelaskan dalam Dealing with files — keduanya merupakan bagian dari modul Getting started with the web.

+ +

Dianjurkan agar Anda bekerja melalui Getting started with the web sebelum mencoba topik ini, namun hal itu tidak mutlak diperlukan; sebgaian besar dari apa yang tercakup dalam artikel HTML basics juga dibahas dalam modul Introduction to HTML, meskipun dalam detail lebih banyak.

+ +

Modul

+ +

Topik ini berisi modul berikut, dalam urutan yang disarankan untuk mengerjakannya. Anda pasti harus mulai dengan yang pertama.

+ +
+
Pengenalan tentang HTML
+
Modul ini mengatur panggung, membuat Anda terbiasa dengan konsep dan sintaks penting, melihat penerapan HTML ke teks, cara membuat hyperlink, dan cara menggunakan HTML untuk menyusun halaman web.
+
Multimedia and embedding
+
Modul ini membahas bagaimana menggunakan HTML untuk menyertakan multimedia di halaman web Anda, termasuk berbagai cara agar gambar dapat disertakan, dan bagaimana cara menyematkan video, audio, dan bahkan seluruh halaman Web lainnya.
+
HTML Tables
+
Mewakili data tabular pada halaman web dengan cara yang dapat dimengerti, {{glossary("Accessibility", "accessible")}} bisa menjadi tantangan tersendiri. Modul ini mencakup markup tabel dasar, beserta fitur yang lebih kompleks seperti menerapkan caption dan ringkasan.
+
HTML Forms
+
Forms adalah bagian yang sangat penting dari Web — ini memberikan banyak fungsi yang Anda butuhkan untuk berinteraksi dengan situs web, misalnya. Mendaftar dan masuk, mengirim umpan balik, membeli produk, dan banyak lagi. Modul ini akan membantu Anda memulai dengan membuat bagian-bagian client-side.
+
+ +

Memecahkan masalah HTML biasa

+ +

Gunakan HTML untuk memecahkan masalah umum menyediakan tautan ke bagian konten yang menjelaskan cara menggunakan HTML untuk memecahkan masalah yang sangat umum saat membuat laman web: menangani judul, menambahkan gambar atau video, menekankan konten, membuat formulir dasar, dll.

+ +

Lihat juga

+ +
+
+
HTML (HyperText Markup Language) on MDN
+
Petunjuk utama masuk untuk HTML dokumentasi di MDN, termasuk elemen rinci dan referensi atribut - jika Anda ingin mengetahui atribut elemen atau nilai apa yang dimiliki atribut, misalnya, ini adalah tempat yang tepat untuk memulai.
+
+
diff --git a/files/id/learn/html/multimedia_dan_embedding/adding_vector_graphics_to_the_web/index.html b/files/id/learn/html/multimedia_dan_embedding/adding_vector_graphics_to_the_web/index.html new file mode 100644 index 0000000000..acddef0b53 --- /dev/null +++ b/files/id/learn/html/multimedia_dan_embedding/adding_vector_graphics_to_the_web/index.html @@ -0,0 +1,362 @@ +--- +title: Adding vector graphics to the Web +slug: Learn/HTML/Multimedia_dan_embedding/Adding_vector_graphics_to_the_Web +tags: + - Gambar + - Grafik + - Pemula + - Raster + - SVG + - Vektor + - belajar + - iframe + - img +translation_of: Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}
+ +
+

Grafik vektor sangat berguna dalam banyak keadaan — mereka memiliki ukuran file kecil dan sangat skalabel, sehingga mereka tidak terlalu besar ketika diperbesar atau meledak hingga ukuran besar. Dalam artikel ini kami akan menunjukkan kepada Anda bagaimana memasukkan satu di halaman web Anda.

+
+ + + + + + + + + + + + +
Prerequisites:Anda harus tahu basics of HTML dan bagaimana caranya insert an image into your document.
Objective:Pelajari cara menyematkan gambar SVG (vektor) ke halaman web.
+ +
+

Note: Artikel ini tidak bermaksud mengajarkan Anda SVG; hanya apa itu, dan bagaimana menambahkannya ke halaman web.

+
+ +

Apa itu grafik vektor?

+ +

Di web, Anda akan bekerja dengan dua jenis gambar — gambar raster, dan gambar vektor:

+ + + +

Untuk memberi Anda gambaran tentang perbedaan antara keduanya, mari kita lihat sebuah contoh. Anda dapat menemukan contoh ini langsung di repo Github kami sebagai vector-versus-raster.html — itu menunjukkan dua gambar yang tampaknya identik berdampingan, dari bintang merah dengan bayangan hitam. Perbedaannya adalah yang kiri adalah PNG, dan yang kanan adalah gambar SVG.

+ +

Perbedaannya menjadi jelas ketika Anda memperbesar halaman - gambar PNG menjadi pixelated saat Anda memperbesar karena berisi informasi di mana masing-masing piksel harus (dan apa warna). Ketika diperbesar, setiap piksel hanya bertambah ukurannya untuk mengisi beberapa piksel pada layar, sehingga gambar mulai tampak ganjil. Namun gambar vektor terus terlihat bagus dan segar, karena berapapun ukurannya, algoritma tersebut digunakan untuk mencari tahu bentuk-bentuk pada gambar, dengan nilai-nilai yang hanya diskalakan karena semakin besar.

+ +

Two star images

+ +

Two star images zoomed in, one crisp and the other blurry

+ +
+

Note: Gambar-gambar di atas sebenarnya semua PNG - dengan bintang kiri di setiap kasus mewakili gambar raster, dan bintang kanan mewakili gambar vektor. Again, go to the vector-versus-raster.html demo for a real example!

+
+ +

Selain itu, file gambar vektor jauh lebih ringan daripada raster mereka, karena mereka hanya perlu memegang beberapa algoritma, daripada informasi tentang setiap pixel dalam gambar secara individual.

+ +

What is SVG?

+ +

SVG is an {{glossary("XML")}}-based bahasa untuk menggambarkan gambar vektor. Ini pada dasarnya markup, seperti HTML, kecuali bahwa Anda memiliki banyak elemen berbeda untuk menentukan bentuk yang ingin Anda tampilkan di gambar Anda, dan efek yang ingin Anda terapkan pada bentuk-bentuk itu. SVG adalah untuk menandai grafik, bukan konten. Di ujung paling sederhana dari spektrum, Anda memiliki elemen untuk membuat bentuk sederhana, seperti {{svgelement("circle")}} dan {{svgelement("rect")}}. More advanced SVG features include {{svgelement("feColorMatrix")}} (transform colors using a transformation matrix,) {{svgelement("animate")}} (animate parts of your vector graphic,) and {{svgelement("mask")}} (apply a mask over the top of your image.)

+ +

Sebagai contoh sederhana, kode berikut ini membuat lingkaran dan persegi panjang:

+ +
<svg version="1.1"
+     baseProfile="full"
+     width="300" height="200"
+     xmlns="http://www.w3.org/2000/svg">
+  <rect width="100%" height="100%" fill="black" />
+  <circle cx="150" cy="100" r="90" fill="blue" />
+</svg>
+ +

This creates the following output:

+ +

{{ EmbedLiveSample('What_is_SVG', 300, 200, "", "", "hide-codepen-jsfiddle") }}

+ +

Dari contoh di atas, Anda mungkin mendapat kesan bahwa SVG mudah untuk handcode. Ya, Anda dapat membuat kode tangan SVG sederhana dalam editor teks, tetapi untuk gambar yang kompleks ini dengan cepat mulai menjadi sangat sulit. For creating SVG images, most people use a vector graphics editor like Inkscape or Illustrator. Paket-paket ini memungkinkan Anda untuk membuat berbagai ilustrasi menggunakan berbagai alat grafis, dan membuat perkiraan foto (misalnya fitur Trace Bitmap dari Inkscape.)

+ +

SVG memiliki beberapa keuntungan tambahan selain yang dijelaskan sejauh ini:

+ + + +

Jadi mengapa ada orang yang mau menggunakan grafik raster di atas SVG? Nah, SVG memang memiliki beberapa kelemahan:

+ + + +

Grafik raster bisa dibilang lebih baik untuk gambar presisi kompleks seperti foto, karena alasan yang dijelaskan di atas.

+ +
+

Note: Di Inkscape, simpan file Anda sebagai Plain SVG untuk menghemat ruang. Juga, silakan lihat ini article describing how to prepare SVGs for the Web.

+
+ +

Adding SVG to your pages

+ +

In this section we'll go through the different ways in which you can add SVG vector graphics to your web pages.

+ +

The quick way: {{htmlelement("img")}}

+ +

To embed an SVG via an {{htmlelement("img")}} element, you just need to reference it in the src attribute as you'd expect. You will need a height or a width attribute (or both if your SVG has no inherent aspect ratio). If you have not already done so, please read Images in HTML.

+ +
<img
+    src="equilateral.svg"
+    alt="triangle with all three sides equal"
+    height="87"
+    width="100" />
+ +

Pros

+ + + +

Cons

+ + + +

Troubleshooting and cross-browser support

+ +

For browsers that don't support SVG (IE 8 and below, Android 2.3 and below), you could reference a PNG or JPG from your src attribute and use a {{htmlattrxref("srcset", "img")}} attribute (which only recent browsers recognize) to reference the SVG. This being the case, only supporting browsers will load the SVG — older browsers will load the PNG instead:

+ +
<img src="equilateral.png" alt="triangle with equal sides" srcset="equilateral.svg">
+ +

Anda juga dapat menggunakan SVG sebagai gambar latar belakang CSS, seperti yang ditunjukkan di bawah ini. Dalam kode di bawah ini, browser lama akan tetap dengan PNG yang mereka pahami, sementara browser yang lebih baru akan memuat SVG:

+ +
background: url("fallback.png") no-repeat center;
+background-image: url("image.svg");
+background-size: contain;
+ +

Like the <img> method described above, inserting SVGs using CSS background images means that the SVG can't be manipulated with JavaScript, and is also subject to the same CSS limitations.

+ +

Jika SVG Anda tidak muncul sama sekali, itu mungkin karena server Anda tidak diatur dengan benar. Jika itu masalahnya, ini article will point you in the right direction.

+ +

How to include SVG code inside your HTML

+ +

Anda juga dapat membuka file SVG dalam editor teks, menyalin kode SVG, dan menempelkannya ke dokumen HTML Anda — this is sometimes called putting your SVG inline, or inlining SVG. Pastikan cuplikan kode SVG Anda dimulai dan diakhiri dengan <svg></svg> tags (don't include anything outside those.) Berikut adalah contoh yang sangat sederhana dari apa yang mungkin Anda tempel ke dalam dokumen Anda:

+ +
<svg width="300" height="200">
+    <rect width="100%" height="100%" fill="green" />
+</svg>
+
+ +

Pros

+ + + +

Cons

+ + + + + +

How to embed an SVG with an {{htmlelement("iframe")}}

+ +

Anda dapat membuka gambar SVG di browser Anda seperti halnya halaman web. Jadi menanamkan dokumen SVG dengan <iframe> is done just like we studied in From <object> to <iframe> — other embedding technologies.

+ +

Here's a quick review:

+ +
<iframe src="triangle.svg" width="500" height="500" sandbox>
+    <img src="triangle.png" alt="Triangle with three unequal sides" />
+</iframe>
+ +

Ini jelas bukan metode terbaik untuk memilih:

+ +

Cons

+ + + +

Active Learning: Playing with SVG

+ +

Di bagian pembelajaran aktif ini kami ingin Anda bersenang-senang bermain SVG untuk bersenang-senang. Di bagian Input di bawah ini Anda akan melihat bahwa kami telah menyediakan beberapa sampel untuk Anda mulai. Anda juga dapat pergi ke SVG Element Reference, cari tahu lebih detail tentang mainan lain yang bisa Anda gunakan di SVG, dan coba juga itu. Bagian ini adalah tentang mempraktekkan keterampilan riset Anda, dan bersenang-senang.

+ +

If you get stuck and can't get your code working, you can always reset it using the Reset button.

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 500, "", "", "hide-codepen-jsfiddle") }}

+ +

Summary

+ +

Artikel ini telah memberi Anda tur singkat tentang apa itu vektor grafik dan SVG, mengapa mereka berguna untuk diketahui, dan bagaimana memasukkan SVG ke dalam halaman web Anda. Itu tidak pernah dimaksudkan sebagai panduan lengkap untuk mempelajari SVG, hanya sebuah petunjuk sehingga Anda tahu apa itu SVG jika Anda bertemu dalam perjalanan Anda di Web. Jadi jangan khawatir jika Anda belum merasa sudah ahli SVG. Kami telah menyertakan beberapa tautan di bawah ini yang mungkin membantu Anda jika Anda ingin pergi dan mencari tahu lebih lanjut tentang cara kerjanya.

+ +

Pada artikel terakhir modul ini, kami akan mengeksplorasi gambar responsif secara terperinci, dengan melihat alat-alat HTML yang memungkinkan Anda membuat gambar Anda bekerja lebih baik di berbagai perangkat.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}

+ +

In this module

+ + diff --git a/files/id/learn/html/multimedia_dan_embedding/index.html b/files/id/learn/html/multimedia_dan_embedding/index.html new file mode 100644 index 0000000000..fe111da30c --- /dev/null +++ b/files/id/learn/html/multimedia_dan_embedding/index.html @@ -0,0 +1,73 @@ +--- +title: Multimedia dan Embedding +slug: Learn/HTML/Multimedia_dan_embedding +tags: + - Asesmen + - Audio + - CodingScripting + - Flash + - HTML + - Image + - Landing + - Multimedia + - Panduan + - Pemula + - Pengembedan + - SVG + - Video + - Web + - belajar + - iframe + - imagemap + - img + - responsif +translation_of: Learn/HTML/Multimedia_and_embedding +--- +

{{LearnSidebar}}

+ +

We've looked at a lot of text so far in this course, but the web would be really boring only using text. Let's start looking at how to make the web come alive with more interesting content! This module explores how to use HTML to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire webpages.

+ +

Persyaratan

+ +

Sebelum memulai modul ini, kamu harus punya pengetahuan mendasar tentang HTML dasar, seperti dicover sebelumnya dalam Pengenalan HTML. Kalau kamu belum bekerja melalui modul ini (atau sesuatu yang serupa), kerja dulu di situ, lalu kembali lagi!

+ +
+

Catatan: Kalau kamu bekerja pada komputer/tablet/device lain yang mana kamu tidak bisa membuat filemu sendiri, kamu bisa mencoba (sebagian besar) contoh kode dalam program coding daring macam JSBin atau Thimble.

+
+ +

Petunjuk

+ +

Module ini berisi artikel berikut yang akan mengantar kamu melalui semua fundamental mengembed multimedia dalam halaman web.

+ +
+
Image dalam HTML
+
Ada tipe multimedia lain yang dipertimbangkan, tapi itu logis jika mulai dengan elemen {{htmlelement("img")}} yang untuk mengembed image sederhana ke dalam halaman web. Di artikel ini kita akan melihat bagaimana menggunakan itu lebih dalam, termasuk dasar, menganotasi itu dengan caption menggunakan {{htmlelement("figure")}}, dan bagaimana itu dikaitkan dengan CSS background images.
+
Konten video dan audio
+
Berikutnya, kita akan melihat bagaimana menggunakan elemen {{htmlelement("video")}} dan {{htmlelement("audio")}} HTML5 untuk mengembed video dan audio dalam halaman kita, termasuk dasar, menyediakan akses ke format file berbeda ke peramban berbeda, menambah caption dan subtitle, dan bagaimana menambah fallback untuk peramban jadul.
+
Dari <object> ke <iframe> — teknologi pengembedan lain
+
Pada poin ini kita akan mengambil langkah menyamping, melihat pasangan elemen yang dipakai untuk mengembed beragam tipe konten ke dalam halaman web: elemen {{htmlelement("iframe")}}, {{htmlelement("embed")}} dan {{htmlelement("object")}}. <iframe> dipakai untuk mengembed halaman web lain, dan 2 lainnya untuk mengembed PDF, SVG, dan bahkan Flash — teknologi yang jarang, tapi masih ada saja.
+
Menambah grafis vektor ke web
+
Grafis vektor bisa berfaedah dalam beberapa situasi. Tidak seperti format reguler macam PNG/JPG, mereka tidak terdistorsi/terpixelasi ketika dizoom-in — tetap mulus ketika discale. Artikel ini memperkenalkan kamu ke grafis vektor dan bagaimana memasukkan format {{glossary("SVG")}} populer ke dalam halaman web.
+
Image responsif
+
Dengan berbagai tipe device yang mampu meramban web — dari ponsel mobile ke komputer desktop — konsep esensial untuk menguasai dunia web modern web world ialah desain responsif. Ini menunjukkan kreasi halaman web yang otomatis menyesuaikan fitur mereka dengan beragam ukuran layar, resolusi, dan lain sebagainya. Ini akan dibahas mendetil dalam modul CSS lebih lanjut, tapi untuk sekarang, kita akan melihat tools yang tersedia bagi HTML untuk membuat responsif image, termasuk elemen {{htmlelement("picture")}}.
+
+ +

Asesmen

+ +

Asesmen berikut akan menguhi pemahamanmu tentang HTML dasar yang dicover dalam panduan di atas:

+ +
+
Halaman splash Mozilla
+
Dalam asesmen ini, kita akan menguji pengetahuanmu tentang beberapa teknik yang didiskusikan dalam artikel modul, membuat kamu menambah beberapa image dan video ke halaman splash funky tentang Mozilla!
+
+ +

Lihat juga

+ +
+
Add a hitmap on top of an image
+
Image maps provide a mechanism to make different parts of an image link to different places. (Think of a map linking through to further information about each different country you click on.) This technique can sometimes be useful.
+
Web literacy basics 2
+
+

An excellent Mozilla foundation course that explores and tests some of the skills talked about in this Multimedia and embedding module. Dive deeper into the basics of composing webpages, designing for accessibility, sharing resources, using online media, and working open (meaning that your content is freely available and shareable by others).

+
+
diff --git a/files/id/learn/html/multimedia_dan_embedding/responsive_images/index.html b/files/id/learn/html/multimedia_dan_embedding/responsive_images/index.html new file mode 100644 index 0000000000..e13790b7f4 --- /dev/null +++ b/files/id/learn/html/multimedia_dan_embedding/responsive_images/index.html @@ -0,0 +1,251 @@ +--- +title: Responsive images +slug: Learn/HTML/Multimedia_dan_embedding/Responsive_images +translation_of: Learn/HTML/Multimedia_and_embedding/Responsive_images +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web", "Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page", "Learn/HTML/Multimedia_and_embedding")}}
+ +
+

Pada artikel ini, kita akan belajar tentang konsep gambar responsif - gambar yang bekerja dengan baik pada perangkat dengan ukuran layar, resolusi, dan fitur lain yang sangat berbeda - dan melihat alat apa yang disediakan HTML untuk membantu mengimplementasikannya. Ini membantu meningkatkan kinerja di berbagai perangkat yang berbeda. Gambar responsif hanyalah salah satu bagian dari responsive design, topik CSS masa depan yang dapat Anda pelajari.

+
+ + + + + + + + + + + + +
Prerequisites:Anda harus sudah mengetahui basics of HTML dan cara add static images to a web page.
Objective:Learn how to use features like {{htmlattrxref("srcset", "img")}} and the {{htmlelement("picture")}} element to implement responsive image solutions on websites.
+ +

Why responsive images?

+ +

Let's examine a typical scenario. Situs web tipikal mungkin berisi gambar tajuk dan beberapa gambar konten di bawah tajuk. Gambar header kemungkinan akan menjangkau seluruh lebar header, dan gambar konten akan cocok di suatu tempat di dalam kolom konten. Berikut ini contoh sederhana:

+ +

Our example site as viewed on a wide screen - here the first image works ok, as it is big enough to see the detail in the center.

+ +

Ini bekerja dengan baik pada perangkat layar lebar, seperti laptop atau desktop (you can see the example live and find the source code on Github.) Kami tidak akan banyak membahas CSS dalam pelajaran ini, kecuali untuk mengatakan bahwa:

+ + + +

Namun, masalah muncul ketika Anda mulai melihat situs di perangkat layar sempit. Header di bawah ini terlihat baik-baik saja, tetapi mulai mengambil banyak ketinggian layar untuk perangkat seluler. Dan pada ukuran ini, sulit untuk melihat orang-orang di dalam gambar konten pertama.

+ +

Our example site as viewed on a narrow screen; the first image has shrunk to the point where it is hard to make out the detail on it.

+ +

An improvement would be to display a cropped version of the image which displays the important details of the image when the site is viewed on a narrow screen. A second cropped image could be displayed for a medium width screen device, like a tablet. This is commonly known as the art direction problem.

+ +

In addition, there is no need to embed such large images on the page if it is being viewed on a mobile screen. And conversely, a small raster image starts to look grainy when displayed larger than its original size (a raster image is a set number of pixels wide and a set number of pixels tall, as we saw when we looked at vector graphics). This is called the resolution switching problem.

+ +

Sebaliknya, tidak perlu untuk menampilkan gambar besar di layar secara signifikan lebih kecil dari ukuran yang dimaksudkan. Melakukannya dapat menghabiskan bandwidth; khususnya, pengguna seluler tidak ingin membuang bandwidth dengan mengunduh gambar besar yang ditujukan untuk desktop, ketika gambar kecil dilakukan untuk perangkat mereka. Idealnya, Anda akan memiliki beberapa resolusi yang tersedia dan melayani ukuran yang sesuai tergantung pada perangkat yang mengakses data di situs web.

+ +

Untuk membuat segalanya lebih rumit, beberapa perangkat memiliki layar resolusi tinggi yang membutuhkan gambar lebih besar dari yang Anda harapkan untuk ditampilkan dengan baik. Ini pada dasarnya adalah masalah yang sama, tetapi dalam konteks yang sedikit berbeda.

+ +

Anda mungkin berpikir bahwa gambar vektor akan menyelesaikan masalah ini, dan mereka melakukannya pada tingkat tertentu - mereka berukuran kecil dalam ukuran dan skalanya dengan baik, dan Anda harus menggunakannya sedapat mungkin. Namun, mereka tidak cocok untuk semua jenis gambar. Gambar vektor sangat bagus untuk grafik, pola, elemen antarmuka, dll. Sederhana, tetapi mulai menjadi sangat kompleks untuk membuat gambar berbasis vektor dengan jenis detail yang akan Anda temukan di katakanlah, foto. Format gambar raster seperti JPEG lebih cocok untuk jenis gambar yang kita lihat dalam contoh di atas.

+ +

This kind of problem didn't exist when the web first existed, in the early to mid 90s — back then the only devices in existence to browse the Web were desktops and laptops, so browser engineers and spec writers didn't even think to implement solutions. Responsive image technologies were implemented recently to solve the problems indicated above by letting you offer the browser several image files, either all showing the same thing but containing different numbers of pixels (resolution switching), or different images suitable for different space allocations (art direction).

+ +
+

Note: The new features discussed in this article — {{htmlattrxref("srcset", "img")}}/{{htmlattrxref("sizes", "img")}}/{{htmlelement("picture")}} — are all supported in release versions of modern desktop and mobile browsers (including Microsoft's Edge browser, although not Internet Explorer.) 

+
+ +

How do you create responsive images?

+ +

Di bagian ini, kita akan melihat dua masalah yang diilustrasikan di atas dan menunjukkan bagaimana menyelesaikannya menggunakan fitur gambar HTML yang responsif. Anda harus mencatat bahwa kami akan fokus pada HTML {{htmlelement("img")}}s for this section,  seperti yang terlihat di area konten dari contoh di atas - gambar di header situs hanya untuk dekorasi, dan karenanya diimplementasikan menggunakan gambar latar belakang CSS. CSS arguably has better tools for responsive design than HTML, and we'll talk about those in a future CSS module.

+ +

Resolution switching: Different sizes

+ +

So, what is the problem that we want to solve with resolution switching? We want to display identical image content, just larger or smaller depending on the device — this is the situation we have with the second content image in our example. The standard {{htmlelement("img")}} element traditionally only lets you point the browser to a single source file:

+ +
<img src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy">
+ +

We can however use two new attributes — {{htmlattrxref("srcset", "img")}} and {{htmlattrxref("sizes", "img")}} — to provide several additional source images along with hints to help the browser pick the right one. You can see an example of this in our responsive.html example on Github (see also the source code):

+ +
<img srcset="elva-fairy-480w.jpg 480w,
+             elva-fairy-800w.jpg 800w"
+     sizes="(max-width: 600px) 480px,
+            800px"
+     src="elva-fairy-800w.jpg"
+     alt="Elva dressed as a fairy">
+ +

The srcset and sizes attributes look complicated, but they're not too hard to understand if you format them as shown above, with a different part of the attribute value on each line. Each value contains a comma-separated list, and each part of those lists is made up of three sub-parts. Let's run through the contents of each now:

+ +

srcset mendefinisikan set gambar yang kami akan memungkinkan browser untuk memilih di antara, dan berapa ukuran masing-masing gambar. Setiap rangkaian informasi gambar dipisahkan dari yang sebelumnya dengan koma. Untuk masing-masing, kami menulis:

+ +
    +
  1. An image filename (elva-fairy-480w.jpg)
  2. +
  3. A space
  4. +
  5. The image's intrinsic width in pixels (480w) — note that this uses the w unit, not px as you might expect. This is the image's real size, which can be found by inspecting the image file on your computer (for example, on a Mac you can select the image in Finder and press Cmd + I to bring up the info screen).
  6. +
+ +

sizes mendefinisikan serangkaian kondisi media (mis. lebar layar) dan menunjukkan ukuran gambar apa yang terbaik untuk dipilih, ketika kondisi media tertentu benar - ini adalah petunjuk yang telah kita bicarakan sebelumnya. Dalam hal ini, sebelum setiap koma kami menulis:

+ +
    +
  1. A media condition ((max-width:600px)) — you'll learn more about these in the CSS topic, but for now let's just say that a media condition describes a possible state that the screen can be in. In this case, we are saying "when the viewport width is 600 pixels or less".
  2. +
  3. A space
  4. +
  5. The width of the slot the image will fill when the media condition is true (480px)
  6. +
+ +
+

Note: For the slot width, you may provide an absolute length (px, em) or a length relative to the viewport (vw), but not percentages. You may have noticed that the last slot width has no media condition (this is the default that is chosen when none of the media conditions are true). The browser ignores everything after the first matching condition, so be careful how you order the media conditions.

+
+ +

So, with these attributes in place, the browser will:

+ +
    +
  1. Look at its device width
  2. +
  3. Work out which media condition in the sizes list is the first one to be true
  4. +
  5. Look at the slot size given to that media query
  6. +
  7. Load the image referenced in the srcset list that most closely matches the chosen slot size
  8. +
+ +

And that's it! At this point, if a supporting browser with a viewport width of 480px loads the page, the (max-width: 600px) media condition will be true, and so the browser chooses the 480px slot. The elva-fairy-480w.jpg will be loaded, as its inherent width (480w) is closest to the slot size. The 800px picture is 128KB on disk, whereas the 480px version is only 63KB — a saving of 65KB. Now, imagine if this was a page that had many pictures on it. Using this technique could save mobile users a lot of bandwidth.

+ +
+

Note: When testing this with a desktop browser, if the browser fails to load the narrower images when you've got its window set to the narowest width, have a look at what the viewport is (you can approximate it by going into the browser's JavaScript console and typing in document.querySelector('html').clientWidth). Different browsers have minimum sizes that they'll let you reduce the window width to, and they might be wider than you'd think. When testing it with a mobile browser, you can use tools like Firefox's about:debugging page to inspect the page loaded on the mobile using the desktop developer tools.
+
+ To see which images were loaded, you can use Firefox DevTools's Network Monitor tab.

+
+ +

Older browsers that don't support these features will just ignore them. Instead, those browsers will go ahead and load the image referenced in the {{htmlattrxref("src", "img")}} attribute as normal.

+ +
+

Note: In the {{htmlelement("head")}} of the example linked above, you'll find the line <meta name="viewport" content="width=device-width">: this forces mobile browsers to adopt their real viewport width for loading web pages (some mobile browsers lie about their viewport width, and instead load pages at a larger viewport width then shrink the loaded page down, which is not very helpful for responsive images or design).

+
+ +

Resolution switching: Same size, different resolutions

+ +

If you're supporting multiple display resolutions, but everyone sees your image at the same real-world size on the screen, you can allow the browser to choose an appropriate resolution image by using srcset with x-descriptors and without sizes — a somewhat easier syntax! You can find an example of what this looks like in srcset-resolutions.html (see also the source code):

+ +
<img srcset="elva-fairy-320w.jpg,
+             elva-fairy-480w.jpg 1.5x,
+             elva-fairy-640w.jpg 2x"
+     src="elva-fairy-640w.jpg"
+     alt="Elva dressed as a fairy">
+
+ +

A picture of a little girl dressed up as a fairy, with an old camera film effect applied to the imageIn this example, the following CSS is applied to the image so that it will have a width of 320 pixels on the screen (also called CSS pixels):

+ +
img {
+  width: 320px;
+}
+ +

In this case, sizes is not needed — the browser simply works out what resolution the display is that it is being shown on, and serves the most appropriate image referenced in the srcset. So if the device accessing the page has a standard/low resolution display, with one device pixel representing each CSS pixel, the elva-fairy-320w.jpg image will be loaded (the 1x is implied, so you don't need to include it.) If the device has a high resolution of two device pixels per CSS pixel or more, the elva-fairy-640w.jpg image will be loaded. The 640px image is 93KB, whereas the 320px image is only 39KB.

+ +

Art direction

+ +

To recap, the art direction problem involves wanting to change the image displayed to suit different image display sizes. For example, a web page includes a large landscape shot with a person in the middle when viewed on a desktop browser. When viewed on a mobile browser, that same image is shrunk down, making the person in the image very small and hard to see. It would probably be better to show a smaller, portrait image on mobile, which zooms in on the person. The {{htmlelement("picture")}} element allows us to implement just this kind of solution.

+ +

Returning to our original not-responsive.html example, we have an image that badly needs art direction:

+ +
<img src="elva-800w.jpg" alt="Chris standing up holding his daughter Elva">
+ +

Let's fix this, with {{htmlelement("picture")}}! Like <video> and <audio>, the <picture> element is a wrapper containing several {{htmlelement("source")}} elements that provide different sources for the browser to choose from, followed by the all-important {{htmlelement("img")}} element. The code in responsive.html looks like so:

+ +
<picture>
+  <source media="(max-width: 799px)" srcset="elva-480w-close-portrait.jpg">
+  <source media="(min-width: 800px)" srcset="elva-800w.jpg">
+  <img src="elva-800w.jpg" alt="Chris standing up holding his daughter Elva">
+</picture>
+
+ + + +

This code allows us to display a suitable image on both wide screen and narrow screen displays, as shown below:

+ +

Our example site as viewed on a wide screen - here the first image works ok, as it is big enough to see the detail in the center.Our example site as viewed on a narrow screen with the picture element used to switch the first image to a portrait close up of the detail, making it a lot more useful on a narrow screen

+ +
+

Note: You should use the media attribute only in art direction scenarios; when you do use media, don't also offer media conditions within the sizes attribute.

+
+ +

Why can't we just do this using CSS or JavaScript?

+ +

When the browser starts to load a page, it starts to download (preload) any images before the main parser has started to load and interpret the page's CSS and JavaScript. This is a useful technique, which has shaved an average of 20% off page load times. However, it is not helpful for responsive images, hence the need to implement solutions like srcset. For example, you couldn't load the {{htmlelement("img")}} element, then detect the viewport width with JavaScript, and then dynamically change the source image to a smaller one if desired. By then, the original image would already have been loaded, and you would load the small image as well, which is even worse in responsive image terms.

+ + + +

Use modern image formats boldly

+ +

There are several exciting new image formats (such as WebP and JPEG-2000) that can maintain a low file size and high quality at the same time. However, browser support is spotty.

+ +

<picture> lets us continue catering to older browsers. You can supply MIME types inside type attributes so the browser can immediately reject unsupported file types:

+ +
<picture>
+  <source type="image/svg+xml" srcset="pyramid.svg">
+  <source type="image/webp" srcset="pyramid.webp">
+  <img src="pyramid.png" alt="regular pyramid built from four equilateral triangles">
+</picture>
+
+ + + +

Active learning: Implementing your own responsive images

+ +

For this active learning, we're expecting you to be brave and go it alone ... mostly. We want you to implement your own suitable art directed narrow screen/wide screen shot using <picture>, and a resolution switching example that uses srcset.

+ +
    +
  1. Write some simple HTML to contain your code (use not-responsive.html as a starting point, if you like).
  2. +
  3. Find a nice wide screen landscape image with some kind of detail contained in it somewhere. Create a web-sized version of it using a graphics editor, then crop it to show a smaller part that zooms in on the detail, and create a second image (about 480px wide is good for this).
  4. +
  5. Use the <picture> element to implement an art direction picture switcher!
  6. +
  7. Create multiple image files of different sizes, each showing the same picture.
  8. +
  9. Use srcset/size to create a resolution switcher example, either to serve the same size image at different resolutions, or different image sizes at different viewport widths.
  10. +
+ +

Test your skills!

+ +

You've reached the end of this article, but can you remember the most important information? You can find a detailed assessment that tests these skills at the end of the module; see Mozilla splash page.

+ +

Summary

+ +

That's a wrap for responsive images — we hope you enjoyed playing with these new techniques. As a recap, there are two distinct problems we've been discussing here:

+ + + +

This also draws to a close the entire Multimedia and embedding module! The only thing to do now before moving on is to try our multimedia assessment, and see how you get on. Have fun!

+ +

See also

+ + + +
{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web", "Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page", "Learn/HTML/Multimedia_and_embedding")}}
+ +
+

In this module

+ + +
diff --git a/files/id/learn/html/pengenalan_html/document_and_website_structure/index.html b/files/id/learn/html/pengenalan_html/document_and_website_structure/index.html new file mode 100644 index 0000000000..5563c68fd3 --- /dev/null +++ b/files/id/learn/html/pengenalan_html/document_and_website_structure/index.html @@ -0,0 +1,293 @@ +--- +title: Document and website structure +slug: Learn/HTML/Pengenalan_HTML/Document_and_website_structure +tags: + - HTML + - Halaman + - Panduan + - Pemula + - Script Coding + - Situs + - Tata letak + - blocks + - semantic +translation_of: Learn/HTML/Introduction_to_HTML/Document_and_website_structure +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}
+ +

Selain mendefinisikan setiap bagian halaman Anda (seperti "paragraf" atau "gambar"), {{glossary("HTML")}} juga menawarkan sejumlah elemen tingkat blok yang digunakan untuk menentukan area situs web Anda (seperti "header", "menu navigasi", "kolom konten utama"). Artikel ini membahas cara merencanakan struktur situs web dasar, dan menulis HTML untuk mewakili struktur ini.

+ + + + + + + + + + + + +
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals. How hyperlinks work, as covered in Creating hyperlinks.
Objective:Learn how to structure your document using semantic tags, and how to work out the structure of a simple website.
+ +

Bagian dasar dari suatu dokumen

+ +

Halaman web dapat dan akan terlihat sangat berbeda satu sama lain, tetapi mereka semua cenderung berbagi komponen standar yang sama, kecuali halaman menampilkan video layar penuh atau permainan, adalah bagian dari semacam proyek seni, atau hanya terstruktur dengan buruk:

+ +
+
header (tajuk):
+
Biasanya strip besar di bagian atas dengan tajuk besar, logo, dan mungkin tagline. Ini biasanya tetap sama dari satu halaman web ke yang lain.
+
navigation bar (bilah navigasi):
+
Tautan ke bagian utama situs; biasanya diwakili oleh tombol menu, tautan, atau tab. Seperti tajuk, konten ini biasanya tetap konsisten dari satu halaman web ke halaman web lainnya - memiliki navigasi yang tidak konsisten pada situs web Anda hanya akan menyebabkan pengguna yang bingung dan frustrasi. Banyak perancang web menganggap bilah navigasi sebagai bagian dari tajuk daripada komponen individual, tetapi itu bukan keharusan; pada kenyataannya, beberapa juga berpendapat bahwa memiliki dua terpisah lebih baik untuk aksesibilitas, karena pembaca layar dapat membaca dua fitur lebih baik jika mereka terpisah.
+
main content (konten utama):
+
Area besar di tengah yang berisi sebagian besar konten unik dari halaman web yang diberikan, misalnya, video yang ingin Anda tonton, atau cerita utama yang Anda baca, atau peta yang ingin Anda lihat, atau berita utama, dll. Ini adalah satu bagian dari situs web yang pasti akan bervariasi dari halaman ke halaman!
+
sidebar (bilah samping):
+
Beberapa info tambahan, tautan, kutipan, iklan, dll. Biasanya, ini kontekstual dengan apa yang terkandung dalam konten utama (misalnya pada halaman artikel berita, bilah sisi mungkin berisi bio penulis, atau tautan ke artikel terkait) tetapi ada juga merupakan kasus di mana Anda akan menemukan beberapa elemen berulang seperti sistem navigasi sekunder.
+
footer:
+
Strip di bagian bawah halaman yang umumnya berisi cetakan, pemberitahuan hak cipta, atau info kontak. Ini adalah tempat untuk menaruh informasi umum (seperti header) tetapi biasanya, informasi itu tidak penting atau sekunder untuk situs web itu sendiri. Footer juga terkadang digunakan untuk {{Glossary("SEO")}} tujuan, dengan menyediakan tautan untuk akses cepat ke konten populer.
+
+ +

A "typical website" could be structured something like this:

+ +

a simple website structure example featuring a main heading, navigation menu, main content, side bar, and footer.

+ +

HTML for structuring content

+ +

The simple example shown above isn't pretty, but it is perfectly fine for illustrating a typical website layout example. Some websites have more columns, some are a lot more complex, but you get the idea. With the right CSS, you could use pretty much any elements to wrap around the different sections and get it looking how you wanted, but as discussed before, we need to respect semantics and use the right element for the right job.

+ +

This is because visuals don't tell the whole story. We use color and font size to draw sighted users' attention to the most useful parts of the content, like the navigation menu and related links, but what about visually impaired people for example, who might not find concepts like "pink" and "large font" very useful?

+ +
+

Note: Colorblind people represent around 4% of the world population or, to put it another way, approximately 1 in every 12 men and 1 in every 200 women are colorblind. Blind and visually impaired people represent roughly 4-5% of the world population (in 2012 there were 285 million such people in the world, while the total population was around 7 billion).

+
+ +

In your HTML code, you can mark up sections of content based on their functionality — you can use elements that represent the sections of content described above unambiguously, and assistive technologies like screenreaders can recognise those elements and help with tasks like "find the main navigation", or "find the main content." As we mentioned earlier in the course, there are a number of consequences of not using the right element structure and semantics for the right job.

+ +

Untuk menerapkan mark up semantik tersebut, HTML menyediakan tag khusus yang dapat Anda gunakan untuk mewakili bagian tersebut, misalnya:

+ + + +

Active learning: exploring the code for our example

+ +

Our example seen above is represented by the following code (you can also find the example in our GitHub repository). Kami ingin Anda melihat contoh di atas, dan kemudian melihat daftar di bawah untuk melihat bagian apa yang membentuk bagian visual apa.

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+
+    <title>My page title</title>
+    <link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Sonsie+One" rel="stylesheet" type="text/css">
+    <link rel="stylesheet" href="style.css">
+
+    <!-- the below three lines are a fix to get HTML5 semantic elements working in old versions of Internet Explorer-->
+    <!--[if lt IE 9]>
+      <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
+    <![endif]-->
+  </head>
+
+  <body>
+    <!-- Here is our main header that is used across all the pages of our website -->
+
+    <header>
+      <h1>Header</h1>
+    </header>
+
+    <nav>
+      <ul>
+        <li><a href="#">Home</a></li>
+        <li><a href="#">Our team</a></li>
+        <li><a href="#">Projects</a></li>
+        <li><a href="#">Contact</a></li>
+      </ul>
+
+       <!-- A Search form is another commmon non-linear way to navigate through a website. -->
+
+       <form>
+         <input type="search" name="q" placeholder="Search query">
+         <input type="submit" value="Go!">
+       </form>
+     </nav>
+
+    <!-- Here is our page's main content -->
+    <main>
+
+      <!-- It contains an article -->
+      <article>
+        <h2>Article heading</h2>
+
+        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Donec a diam lectus. Set sit amet ipsum mauris. Maecenas congue ligula as quam viverra nec consectetur ant hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur.</p>
+
+        <h3>Subsection</h3>
+
+        <p>Donec ut librero sed accu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor.</p>
+
+        <p>Pelientesque auctor nisi id magna consequat sagittis. Curabitur dapibus, enim sit amet elit pharetra tincidunt feugiat nist imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros.</p>
+
+        <h3>Another subsection</h3>
+
+        <p>Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum soclis natoque penatibus et manis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p>
+
+        <p>Vivamus fermentum semper porta. Nunc diam velit, adipscing ut tristique vitae sagittis vel odio. Maecenas convallis ullamcorper ultricied. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, is fringille sem nunc vet mi.</p>
+      </article>
+
+      <!-- the aside content can also be nested within the main content -->
+      <aside>
+        <h2>Related</h2>
+
+        <ul>
+          <li><a href="#">Oh I do like to be beside the seaside</a></li>
+          <li><a href="#">Oh I do like to be beside the sea</a></li>
+          <li><a href="#">Although in the North of England</a></li>
+          <li><a href="#">It never stops raining</a></li>
+          <li><a href="#">Oh well...</a></li>
+        </ul>
+      </aside>
+
+    </main>
+
+    <!-- And here is our main footer that is used across all the pages of our website -->
+
+    <footer>
+      <p>©Copyright 2050 by nobody. All rights reversed.</p>
+    </footer>
+
+  </body>
+</html>
+ +

Luangkan waktu untuk melihat kode dan memahaminya - komentar di dalam kode juga akan membantu Anda untuk memahaminya. Kami tidak meminta Anda untuk melakukan banyak hal lain dalam artikel ini, karena kunci untuk memahami tata letak dokumen adalah menulis struktur HTML yang baik, dan kemudian meletakkannya dengan CSS. Kami akan menunggu ini sampai Anda mulai mempelajari tata letak CSS sebagai bagian dari topik CSS.

+ +

HTML layout elements in more detail

+ +

It's good to understand the overall meaning of all the HTML sectioning elements in detail — this is something you'll work on gradually as you start to get more experience with web development. You can find a lot of detail by reading our HTML element reference. For now, these are the main definitions that you should try to understand:

+ + + +

Non-semantic wrappers

+ +

Sometimes you'll come across a situation where you can't find an ideal semantic element to group some items together or wrap some content. Sometimes you might want to just group a set of elements together to affect them all as a single entity with some {{glossary("CSS")}} or {{glossary("JavaScript")}}. For cases like these, HTML provides the {{HTMLElement("div")}} and {{HTMLElement("span")}} elements. You should use these preferably with a suitable {{htmlattrxref('class')}} attribute, to provide some kind of label for them so they can be easily targeted.

+ +

{{HTMLElement("span")}} is an inline non-semantic element, which you should only use if you can't think of a better semantic text element to wrap your content, or don't want to add any specific meaning. For example:

+ +
<p>The King walked drunkenly back to his room at 01:00, the beer doing nothing to aid
+him as he staggered through the door <span class="editor-note">[Editor's note: At this point in the
+play, the lights should be down low]</span>.</p>
+ +

Dalam hal ini, catatan editor seharusnya hanya memberikan arahan ekstra untuk sutradara drama; tidak seharusnya memiliki makna semantik tambahan. Untuk pengguna yang terlihat, CSS mungkin akan digunakan untuk menjauhkan catatan sedikit dari teks utama.

+ +

{{HTMLElement("div")}} is a block level non-semantic element, which you should only use if you can't think of a better semantic block element to use, or don't want to add any specific meaning. For example, imagine a shopping cart widget that you could choose to pull up at any point during your time on an e-commerce site:

+ +
<div class="shopping-cart">
+  <h2>Shopping cart</h2>
+  <ul>
+    <li>
+      <p><a href=""><strong>Silver earrings</strong></a>: $99.95.</p>
+      <img src="../products/3333-0985/thumb.png" alt="Silver earrings">
+    </li>
+    <li>
+      ...
+    </li>
+  </ul>
+  <p>Total cost: $237.89</p>
+</div>
+ +

This isn't really an <aside>, as it doesn't necessarily relate to the main content of the page (you want it viewable from anywhere). It doesn't even particularly warrant using a  <section>, as it isn't part of the main content of the page. So a <div> is fine in this case. We've included a heading as a signpost to aid screenreader users in finding it.

+ +
+

Warning: Div sangat nyaman digunakan sehingga mudah digunakan terlalu banyak. Karena mereka tidak memiliki nilai semantik, mereka hanya mengacaukan kode HTML Anda. Berhati-hatilah untuk menggunakannya hanya ketika tidak ada solusi semantik yang lebih baik dan cobalah untuk mengurangi penggunaannya seminimal mungkin jika tidak, Anda akan kesulitan memperbarui dan memelihara dokumen Anda.

+
+ +

Line breaks and horizontal rules

+ +

Two elements that you'll use occasionally and will want to know about are {{htmlelement("br")}} and {{htmlelement("hr")}}:

+ +

<br> creates a line break in a paragraph; it is the only way to force a rigid structure in a situation where you want a series of fixed short lines, such as in a postal address or a poem. For example:

+ +
+
<p>There once was a man named O'Dell<br>
+Who loved to write HTML<br>
+But his structure was bad, his semantics were sad<br>
+and his markup didn't read very well.</p>
+
+ +

Without the <br> elements, the paragraph would just be rendered in one long line (as we said earlier in the course, HTML ignores most whitespace); with <br> elements in the code, the markup renders like this:

+ +

{{EmbedLiveSample('line-break-live-sample', '100%', '125px', '', '', 'hide-codepen-jsfiddle')}}

+ +

<hr> elements create a horizontal rule in the document that denotes a thematic change in the text (such as a change in topic or scene). Visually it just looks like a horizontal line. As an example:

+ +
+
<p>Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.</p>
+<hr>
+<p>Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.</p>
+
+ +

Would render like this:

+ +

{{EmbedLiveSample('horizantal-rule-live-sample', '100%', '185px', '', '', 'hide-codepen-jsfiddle')}}

+ +

Planning a simple website

+ +

Setelah Anda merencanakan struktur laman web sederhana, langkah logis berikutnya adalah mencoba mencari tahu konten apa yang ingin Anda tempatkan di seluruh situs web, halaman apa yang Anda butuhkan, dan bagaimana mereka harus diatur dan terhubung satu sama lain untuk pengalaman pengguna terbaik. This is called {{glossary("Information architecture")}}. Dalam situs web besar dan kompleks, banyak perencanaan yang dapat dilakukan dalam proses ini, tetapi untuk situs web sederhana dari beberapa halaman, ini bisa sangat sederhana, dan menyenangkan!

+ +
    +
  1. Ingatlah bahwa Anda akan memiliki beberapa elemen yang umum untuk sebagian besar (jika tidak semua) halaman - seperti menu navigasi, dan konten footer. Jika situs Anda untuk bisnis, misalnya, sebaiknya informasi kontak Anda tersedia di catatan kaki di setiap halaman. Catat kesamaan yang ingin Anda miliki untuk setiap halaman.the common features of the travel site to go on every page: title and logo, contact, copyright, terms and conditions, language chooser, accessibility policy
  2. +
  3. Selanjutnya, buatlah sketsa kasar tentang bagaimana Anda ingin struktur setiap halaman terlihat (mungkin terlihat seperti situs web sederhana kami di atas). Catat apa yang akan menjadi setiap blok.A simple diagram of a sample site structure, with a header, main content area, two optional sidebars, and footer
  4. +
  5. Sekarang, tukar pikiran semua konten lain (tidak umum untuk setiap halaman) yang ingin Anda miliki di situs web Anda - tulis daftar besar.A long list of all the features that we could put on our travel site, from searching, to special offers and country-specific info
  6. +
  7. Selanjutnya, cobalah untuk mengurutkan semua item konten ini menjadi grup, untuk memberi Anda gambaran tentang bagian apa yang bisa hidup bersama di halaman yang berbeda. Ini sangat mirip dengan teknik yang disebut {{glossary("Card sorting")}}.The items that should appear on a holiday site sorted into 5 categories: Search, Specials, Country-specific info, Search results, and Buy things
  8. +
  9. Sekarang cobalah untuk membuat sketsa peta situs kasar - miliki gelembung untuk setiap halaman di situs Anda, dan gambarlah garis untuk menunjukkan alur kerja khas antar halaman. Beranda mungkin ada di tengah, dan tautan ke sebagian besar jika tidak semua yang lain; sebagian besar halaman di situs kecil harus tersedia dari navigasi utama, meskipun ada pengecualian. Anda mungkin juga ingin memasukkan catatan tentang bagaimana hal-hal disajikan.A map of the site showing the homepage, country page, search results, specials page, checkout, and buy page
  10. +
+ +

Active learning: create your own sitemap

+ +

Coba lakukan latihan di atas untuk situs web ciptaan Anda sendiri. Anda ingin membuat situs tentang apa?

+ +
+

Note: Simpan pekerjaan Anda di suatu tempat; Anda mungkin membutuhkannya nanti.

+
+ +

Test your skills!

+ +

Anda telah mencapai akhir artikel ini, tetapi dapatkah Anda mengingat informasi yang paling penting? Anda dapat menemukan penilaian terperinci yang menguji keterampilan ini di akhir modul; see Structuring a page of content. Kami menyarankan untuk membaca artikel berikutnya dalam seri ini terlebih dahulu dan tidak hanya melewatkannya saja!

+ +

Ringkasan

+ +

Pada titik ini, Anda harus memiliki ide yang lebih baik tentang bagaimana membuat struktur halaman web / situs. Pada artikel terakhir modul ini, kita akan mempelajari cara men-debug HTML.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}

+ +

In this module

+ + diff --git a/files/id/learn/html/pengenalan_html/html_text_fundamentals/index.html b/files/id/learn/html/pengenalan_html/html_text_fundamentals/index.html new file mode 100644 index 0000000000..bbee58cc80 --- /dev/null +++ b/files/id/learn/html/pengenalan_html/html_text_fundamentals/index.html @@ -0,0 +1,1047 @@ +--- +title: Teks mendasar HTML +slug: Learn/HTML/Pengenalan_HTML/HTML_text_fundamentals +translation_of: Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML")}}
+ +

Salah satu tugas utama HTML adalah memberikan struktur dan makna teks (dikenal juga sebagai {{glossary("semantics")}}) dengan begitu peramban dapat menampilkannya dengan benar. Artikel ini menjelaskan cara {{glossary("HTML")}} digunakan untuk membuat struktur halaman teks dengan menambahkan judul dan paragraf, menekankan kata-kata, membuat daftar, dan lainnya.

+ + + + + + + + + + + + +
Prasyarat:Familiar dengan dasar-dasar HTML, dicakup dalam Getting started with HTML.
Hal yang dipelajari:Mempelajari cara menandai halaman dasar teks untuk memberikan struktur dan tujuan — termasuk paragraf, judul, daftar, penekanan, dan kutipan.
+ +

Dasar-dasarnya: Judul dan paragaf

+ +

Sebaguan besar struktur teks terdiri dari judul dan paragraf, st structured text consists of headings and paragraphs, ntah Anda membaca sebuah kisah, koran, buku pelajaran, majalah, dsb.

+ +

An example of a newspaper front cover, showing use of a top level heading, subheadings and paragraphs.

+ +

Konten yang terstruktur membuat pengalaman membaca lebih mudah dan lebih menyenangkan.

+ +

Dalam HTML, setiap paragraf dirangkap element {{htmlelement("p")}}, seperti berikut.

+ +
<p>I am a paragraph, oh yes I am.</p>
+ +

Setiap judul juga dirangkap dalam sebuah element "heading":

+ +
<h1>I am the title of the story.</h1>
+ +

Terdaoat beberapa element heading (judul) — {{htmlelement("h1")}}, {{htmlelement("h2")}}, {{htmlelement("h3")}}, {{htmlelement("h4")}}, {{htmlelement("h5")}}, dan {{htmlelement("h6")}}. Setiap element mewakili level konten yang berbeda dalam dokumennnya; <h1> mewakili judul utama, <h2> mewakili sub judul, <h3> mewakili sub-sub judul, dan seterusnya.

+ +

Menerapkan susunan struktural

+ +

Untuk contohnya, dalam sebuah kisah, <h1> mewakili judul kisahnya, <h2> mewakili judul setiap babnya dan <h3> mewakili sub-bagian setiap babnya, dan seterusnya.

+ +
<h1>The Crushing Bore</h1>
+
+<p>By Chris Mills</p>
+
+<h2>Chapter 1: The dark night</h2>
+
+<p>It was a dark night. Somewhere, an owl hooted. The rain lashed down on the ...</p>
+
+<h2>Chapter 2: The eternal silence</h2>
+
+<p>Our protagonist could not so much as a whisper out of the shadowy figure ...</p>
+
+<h3>The specter speaks</h3>
+
+<p>Several more hours had passed, when all of a sudden the specter sat bolt upright and exclaimed, "Please have mercy on my soul!"</p>
+ +

Sebenarnya terserah Anda element yang digunakan, selama susunannya masuk akal. Anda perlu mengingat beberapa prakter terbaik saat Anda membuat struktur seperti:

+ + + +

Why do we need structure?

+ +

To answer this question, let's take a look at text-start.html — the starting point of our running example for this article (a nice hummus recipe). You should save a copy of this file on your local machine, as you'll need it for the exercises later on. This document's body currently contains multiple pieces of content — they aren't marked up in any way, but they are separated with linebreaks (Enter/Return pressed to go onto the next line).

+ +

However, when you open the document in your browser, you'll see that the text appears as a big chunk!

+ +

A webpage that shows a wall of unformatted text, because there are no elements on the page to structure it.

+ +

This is because there are no elements to give the content structure, so the browser does not know what is a heading and what is a paragraph. Furthermore:

+ + + +

We therefore need to give our content structural markup.

+ +

Active learning: Giving our content structure

+ +

Let's jump straight in with a live example. In the example below, add elements to the raw text in the Input field so that it appears as a heading and two paragraphs in the Output field.

+ +

If you make a mistake, you can always reset it using the Reset button. If you get stuck, press the Show solution button to see the answer.

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 400, "", "", "hide-codepen-jsfiddle") }}

+ +

Why do we need semantics?

+ +

Semantics are relied on everywhere around us — we rely on previous experience to tell us what the function of an everyday object is; when we see something, we know what its function will be. So, for example, we expect a red traffic light to mean "stop", and a green traffic light to mean "go". Things can get tricky very quickly if the wrong semantics are applied (Do any countries use red to mean "go"? I hope not.)

+ +

In a similar vein, we need to make sure we are using the correct elements, giving our content the correct meaning, function, or appearance. In this context the {{htmlelement("h1")}} element is also a semantic element, which gives the text it wraps around the role (or meaning) of "a top level heading on your page."

+ +
<h1>This is a top level heading</h1>
+ +

By default, the browser will give it a large font size to make it look like a heading (although you could style it to look like anything you wanted using CSS). More importantly, its semantic value will be used in multiple ways, for example by search engines and screen readers (as mentioned above).

+ +

On the other hand, you could make any element look like a top level heading. Consider the following:

+ +
<span style="font-size: 32px; margin: 21px 0; display: block;">Is this a top level heading?</span>
+ +

This is a {{htmlelement("span")}} element. It has no semantics. You use it to wrap content when you want to apply CSS to it (or do something to it with JavaScript) without giving it any extra meaning (you'll find out more about these later on in the course). We've applied some CSS to it to make it look like a top level heading, but since it has no semantic value, it will not get any of the extra benefits described above. It is a good idea to use the relevant HTML element for the job.

+ +

Lists

+ +

Now let's turn our attention to lists. Lists are everywhere in life — from your shopping list to the list of directions you subconsciously follow to get to your house every day, to the lists of instructions you are following in these tutorials! Lists are everywhere on the Web too, and we've got three different types to worry about.

+ +

Unordered

+ +

Unordered lists are used to mark up lists of items for which the order of the items doesn't matter — let's take a shopping list as an example.

+ +
milk
+eggs
+bread
+hummus
+ +

Every unordered list starts off with a {{htmlelement("ul")}} element — this wraps around all the list items:

+ +
<ul>
+milk
+eggs
+bread
+hummus
+</ul>
+ +

The last step is to wrap each list item in a {{htmlelement("li")}} (list item) element:

+ +
<ul>
+  <li>milk</li>
+  <li>eggs</li>
+  <li>bread</li>
+  <li>hummus</li>
+</ul>
+ +

Active learning: Marking up an unordered list

+ +

Try editing the live sample below to create your very own HTML unordered list.

+ + + +

{{ EmbedLiveSample('Playable_code_2', 700, 400, "", "", "hide-codepen-jsfiddle") }}

+ +

Ordered

+ +

Ordered lists are lists in which the order of the items does matter — let's take a set of directions as an example:

+ +
Drive to the end of the road
+Turn right
+Go straight across the first two roundabouts
+Turn left at the third roundabout
+The school is on your right, 300 meters up the road
+ +

The markup structure is the same as for unordered lists, except that you have to wrap the list items in an {{htmlelement("ol")}} element, rather than <ul>:

+ +
<ol>
+  <li>Drive to the end of the road</li>
+  <li>Turn right</li>
+  <li>Go straight across the first two roundabouts</li>
+  <li>Turn left at the third roundabout</li>
+  <li>The school is on your right, 300 meters up the road</li>
+</ol>
+ +

Active learning: Marking up an ordered list

+ +

Try editing the live sample below to create your very own HTML ordered list.

+ + + +

{{ EmbedLiveSample('Playable_code_3', 700, 500, "", "", "hide-codepen-jsfiddle") }}

+ +

Active learning: Marking up our recipe page

+ +

So at this point in the article, you have all the information you need to mark up our recipe page example. You can choose to either save a local copy of our text-start.html starting file and do the work there, or do it in the editable example below. Doing it locally will probably be better, as then you'll get to save the work you are doing, whereas if you fill it in to the editable example, it will be lost the next time you open the page. Both have pros and cons.

+ + + +

{{ EmbedLiveSample('Playable_code_4', 900, 500, "", "", "hide-codepen-jsfiddle") }}

+ +

If you get stuck, you can always press the Show solution button, or check out our text-complete.html example on our github repo.

+ +

Nesting lists

+ +

It is perfectly ok to nest one list inside another one. You might want to have some sub-bullets sitting below a top level bullet. Let's take the second list from our recipe example:

+ +
<ol>
+  <li>Remove the skin from the garlic, and chop coarsely.</li>
+  <li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li>
+  <li>Add all the ingredients into a food processor.</li>
+  <li>Process all the ingredients into a paste.</li>
+  <li>If you want a coarse "chunky" hummus, process it for a short time.</li>
+  <li>If you want a smooth hummus, process it for a longer time.</li>
+</ol>
+ +

Since the last two bullets are very closely related to the one before them (they read like sub-instructions or choices that fit below that bullet), it might make sense to nest them inside their own unordered list, and put that list inside the current fourth bullet. This would look like so:

+ +
<ol>
+  <li>Remove the skin from the garlic, and chop coarsely.</li>
+  <li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li>
+  <li>Add all the ingredients into a food processor.</li>
+  <li>Process all the ingredients into a paste.
+    <ul>
+      <li>If you want a coarse "chunky" hummus, process it for a short time.</li>
+      <li>If you want a smooth hummus, process it for a longer time.</li>
+    </ul>
+  </li>
+</ol>
+ +

Try going back to the previous active learning example and updating the second list like this.

+ +

Emphasis and importance

+ +

In human language, we often emphasise certain words to alter the meaning of a sentence, and we often want to mark certain words as important or different in some way. HTML provides various semantic elements to allow us to mark up textual content with such effects, and in this section, we'll look at a few of the most common ones.

+ +

Emphasis

+ +

When we want to add emphasis in spoken language, we stress certain words, subtly altering the meaning of what we are saying. Similarly, in written language we tend to stress words by putting them in italics. For example, the following two sentences have different meanings.

+ +

I am glad you weren't late.

+ +

I am glad you weren't late.

+ +

The first sentence sounds genuinely relieved that the person wasn't late. In contrast, the second one sounds sarcastic or passive-aggressive, expressing annoyance that the person arrived a bit late.

+ +

In HTML we use the {{htmlelement("em")}} (emphasis) element to mark up such instances. As well as making the document more interesting to read, these are recognised by screen readers and spoken out in a different tone of voice. Browsers style this as italic by default, but you shouldn't use this tag purely to get italic styling. To do that, you'd use a {{htmlelement("span")}} element and some CSS, or perhaps an {{htmlelement("i")}} element (see below).

+ +
<p>I am <em>glad</em> you weren't <em>late</em>.</p>
+ +

Strong importance

+ +

To emphasize important words, we tend to stress them in spoken language and bold them in written language. For example:

+ +

This liquid is highly toxic.

+ +

I am counting on you. Do not be late!

+ +

In HTML we use the {{htmlelement("strong")}} (strong importance) element to mark up such instances. As well as making the document more useful, again these are recognized by screen readers and spoken in a different tone of voice. Browsers style this as bold text by default, but you shouldn't use this tag purely to get bold styling. To do that, you'd use a {{htmlelement("span")}} element and some CSS, or perhaps a {{htmlelement("b")}} element (see below).

+ +
<p>This liquid is <strong>highly toxic</strong>.</p>
+
+<p>I am counting on you. <strong>Do not</strong> be late!</p>
+ +

You can nest strong and emphasis inside one another if desired:

+ +
<p>This liquid is <strong>highly toxic</strong> —
+if you drink it, <strong>you may <em>die</em></strong>.</p>
+ +

Active learning: Let's be important!

+ +

In this active learning section, we have provided an editable example. Inside it, we'd like you to try adding emphasis and strong importance to the words you think need them, just to have some practice.

+ + + +

{{ EmbedLiveSample('Playable_code_5', 700, 500, "", "", "hide-codepen-jsfiddle") }}

+ +

Italic, bold, underline...

+ +

The elements we've discussed so far have clearcut associated semantics. The situation with {{htmlelement("b")}}, {{htmlelement("i")}}, and {{htmlelement("u")}} is somewhat more complicated. They came about so people could write bold, italics, or underlined text in an era when CSS was still supported poorly or not at all. Elements like this, which only affect presentation and not semantics, are known as presentational elements and should no longer be used, because as we've seen before, semantics is so important to accessibility, SEO, etc.

+ +

HTML5 redefined <b>, <i> and <u> with new, somewhat confusing, semantic roles.

+ +

Here's the best rule of thumb: it's likely appropriate to use <b>, <i>, or <u> to convey a meaning traditionally conveyed with bold, italics, or underline, provided there is no more suitable element. However, it always remains critical to keep an accessibility mindset. The concept of italics isn't very helpful to people using screen readers, or to people using a writing system other than the Latin alphabet.

+ + + +
+

A kind warning about underline: People strongly associate underlining with hyperlinks. Therefore, on the Web, it's best to underline only links. Use the <u> element when it's semantically appropriate, but consider using CSS to change the default underline to something more appropriate on the Web. The example below illustrates how it can be done.

+
+ +
<!-- scientific names -->
+<p>
+  The Ruby-throated Hummingbird (<i>Archilochus colubris</i>)
+  is the most common hummingbird in Eastern North America.
+</p>
+
+<!-- foreign words -->
+<p>
+  The menu was a sea of exotic words like <i lang="uk-latn">vatrushka</i>,
+  <i lang="id">nasi goreng</i> and <i lang="fr">soupe à l'oignon</i>.
+</p>
+
+<!-- a known misspelling -->
+<p>
+  Someday I'll learn how to <u style="text-decoration-line: underline; text-decoration-style: wavy;">spel</u> better.
+</p>
+
+<!-- Highlight keywords in a set of instructions -->
+<ol>
+  <li>
+    <b>Slice</b> two pieces of bread off the loaf.
+  </li>
+  <li>
+    <b>Insert</b> a tomato slice and a leaf of
+    lettuce between the slices of bread.
+  </li>
+</ol>
+ +

Summary

+ +

That's it for now! This article should have given you a good idea of how to start marking up text in HTML, and introduced you to some of the most important elements in this area. There are a lot more semantic elements to cover in this area, and we'll look at a lot more in our 'More Semantic Elements' article, later on in the course. In the next article, we'll be looking in detail at how to create hyperlinks, possibly the most important element on the Web.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML")}}

+ + + +

In this module

+ + diff --git a/files/id/learn/html/pengenalan_html/index.html b/files/id/learn/html/pengenalan_html/index.html new file mode 100644 index 0000000000..367ef45712 --- /dev/null +++ b/files/id/learn/html/pengenalan_html/index.html @@ -0,0 +1,64 @@ +--- +title: Pengenalan HTML +slug: Learn/HTML/Pengenalan_HTML +tags: + - CodingScripting + - HTML + - Link + - Pengenalan HTML + - Struktur + - Teks + - head + - semantic +translation_of: Learn/HTML/Introduction_to_HTML +--- +
{{LearnSidebar}}
+ +

Pada intinya, {{glossary("HTML")}} adalah bahasa yang cukup sederhana yang tersusun dari elemen, yang bisa diaplikasikan pada teks untuk menambah perbedaan maksud dalam dokumen (Apakah paragraf? Apakah daftar dengan butir? Apakah bagian dari sebuah tabel?), membentuk struktur dokumen menjadi satu bagian logikal (Apakah memiliki header? Apakah berbentuk tiga kolom? Apakah sebuah menu navigasi?), dan menempatkan konten seperti gambar dan video pada satu halaman. Modul ini akan memperkenalkan dua hal dulu, dan memperkenalkan konsep fundamental dan sintaks yang harus kamu ketahui untuk memahami HTML.

+ +

Prasyarat

+ +

Sebelum memulai modul ini, kamu tidak harus memiliki pengetahuan mengenai HTML, tapi kamu setidaknya harus sudah terbiasa menggunakan komputer dan menggunakan web secara pasif (misalnya, hanya membuka-buka dan menikmati kontennya). Kamu harus memiliki perlengkapan dasar (seperti dijelaskan dalam Menginstal perangkat lunak dasar), dan memahami cara membuat dan mengelola file (seperti dijelaskan dalam Berurusan dengan file). Keduanya adalah bagian dari modul untuk pemula yang berjudul Mengenal apa itu web.

+ +
+

Catatan: Jika kamu menggunakan komputer/tablet/alat lain yang tidak bisa membuat file sendiri, kamu bisa mencoba (banyak) contoh kode di aplikasi pemrograman daring seperti JSBin atau Thimble.

+
+ +

Panduan

+ +

Modul ini berisi artikel-artikel berikut, yang akan mengajarkan kamu mengenai semua teori dasar HTML dan memberimu kesempatan untuk menguji beberapa keterampilan.

+ +
+
Mulai bekerja dengan HTML
+
Mengkover dasar-dasar HTML, untuk memulai — kita mendefinisikan elemen, atribut, dan istilah penting lainnya, dan menunjukkan di mana posisi mereka dalam HTML. Kita juga tunjukkan bagaimana tipikal halaman HTML terstruktur dan bagaimana elemen HTML tersetruktur, dan menjelaskan fitur dasar penting lainnya. Selain itu, kita akan bermain dengan beberapa HTML supaya kamu tertarik!
+
Apa yang ada di head? Metadata dalam HTML
+
Head dokumen HTML merupakan bagian yang tidak tampil dalam peramban web ketika halaman dimuat. Dia mengandung informasi seperti halaman {{htmlelement("title")}}, link ke {{glossary("CSS")}} (jika kamu ingin memberi gaya konten HTML mu dengan CSS), link ke kustom favicons, dan metadata (data tentang HTML, misalnya siapa yang menulis, dan kata kunci penting yang menjelaskan dokumen tersebut).
+
Fundamental teks HTML
+
Salah satu dari tugas utama HTML ialah memberi teks arti (juga disebut semantic), sehingga peramban tahu cara yang benar untuk menampilkannya. Artikel ini melihat bagaimana menggunakan HTML untuk memecah blok teks menjadi satu struktur headings dan paragraf, tambah penekanan/kepentingan ke dalam kata-kata, membuat list, dan banyak lagi.
+
Membuat hyperlinks
+
Hyperlinks sangat penting — merekalah yang membuat web menjadi web. Artikel ini menunjukkan syntaks yang dibutuhkan untuk membuat link, dan mendiskusikan praktek terbaik untuk link.
+
Pemformatan teks maju
+
Banyak elemen lain dalam HTML untuk pemformatan teks yang tidak kita dapatkan dalam artikel fundamental teks HTML. Elemen ini kurang dikenal, tapi masih berfaedah untuk diketahui. Dalam artikel ini kamu akan belajar tentang menandai quotasi, deskripsi list, kode komputer dan text terkait lain, subscript dan superscript, informasi kontak, dan banyak lagi.
+
Struktur dokumen dan website
+
Selain mendefinisi bagian individu halaman kamu (seperti sebuah "paragraf" atau "gambar"), HTML juga digunakan untuk mendefinisi area website kamu (seperti header," "menu navigasi," atau "kolom konten utama.") Artikel ini melihat ke dalam bagaimana merencanakan struktur web dasar dan bagaimana menulis HTML untuk mewakili struktur ini.
+
Mendebug HTML
+
Menulis HTML itu bagus, tapi kalau sesuatu buruk terjadi, dan kamu tidak bisa mengatasinya? Artikel ini akan memperkenalkan kamu pada beberapa tools yang berfaedah untuk itu.
+
+ +

Latihan

+ +

Latihan-latihan berikut akan menguji pemahaman kamu mengenai HTML dasar yang ada pada panduan-panduan di atas.

+ +
+
Menandai huruf
+
Kita semua belajar menulis huruf cepat atau lambat; itu juga contoh berfaedah untuk menguji keahlian memformat. Dalam asesmen ini, kamu akan diberi huruf untuk ditandai.
+
Menandai halaman konten
+
Asesmen ini menguji kemampuanmu menggunakan HTML untuk menstrukturisasi halaman konten sederhana, yang berisi header, footer, menu navigasi, konten utama, dan sidebar.
+
+ +

Lihat juga

+ +
+
Dasar literasi web 1
+
Kursus Mozilla foundation terbaik yang menjelajahi dan menguji banyak kemampuan dalam modul Pengenalan HTML. Pelajar akan akrab dengan bacaan, tulisan, dan berpartisipasi dalam web di modul 6-bagian ini. Cari tahu fondasi web melalui produksi dan kolaborasi.
+
diff --git a/files/id/learn/html/pengenalan_html/structuring_a_page_of_content/index.html b/files/id/learn/html/pengenalan_html/structuring_a_page_of_content/index.html new file mode 100644 index 0000000000..2535589f38 --- /dev/null +++ b/files/id/learn/html/pengenalan_html/structuring_a_page_of_content/index.html @@ -0,0 +1,116 @@ +--- +title: Structuring a page of content +slug: Learn/HTML/Pengenalan_HTML/Structuring_a_page_of_content +translation_of: Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
+ +

Structuring a page of content ready for laying it out using CSS is a very important skill to master, so in this assessment you'll be tested on your ability to think about how a page might end up looking, and choose appropriate structural semantics to build a layout on top of.

+ + + + + + + + + + + + +
Prerequisites:Before attempting this assessment you should have already worked through the rest of the course, with a particular emphasis on Document and website structure.
Objective:To test knowledge of web page structures, and how to represent a prospective layout design in markup.
+ +

Starting point

+ +

To get this assessment started, you should go and grab the zip file containing all the starting assets.

+ +


+ The zip file contains:

+ + + +

Create the example on your local computer, or alternatively use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks.

+ +
+

Note: If you get stuck, then ask us for help — see the {{anch("Assessment or further help")}} section at the bottom of this page.

+
+ +

Project brief

+ +

Untuk proyek ini, tugas Anda adalah mengambil konten untuk beranda situs web pengamatan burung dan menambahkan elemen struktural ke dalamnya sehingga dapat memiliki tata letak halaman yang diterapkan padanya. Perlu memiliki:

+ + + +

You need to add a suitable wrapper for (Anda perlu menambahkan pembungkus yang cocok untuk:):

+ + + +

You should also:

+ + + +

Hints and tips

+ + + +

Example

+ +

The following screenshot shows an example of what the homepage might look like after being marked up.

+ +

The finished example for the assessment; a simple webpage about birdwatching, including a heading of "Birdwatching", bird photos, and a welcome message

+ +

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 Structuring a page of content".
    • +
    • 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/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

+ +

In this module

+ + diff --git a/files/id/learn/html/tabel/index.html b/files/id/learn/html/tabel/index.html new file mode 100644 index 0000000000..b8fe3a2d8a --- /dev/null +++ b/files/id/learn/html/tabel/index.html @@ -0,0 +1,36 @@ +--- +title: HTML Tables +slug: Learn/HTML/Tabel +translation_of: Learn/HTML/Tables +--- +
{{LearnSidebar}}
+ +

Salah satu tugas umum di HTML adalah menyusun data secara tabular dan untuk tujuan tersebut maka disediakan sejumlah elemen dan atribut. HTML yang ditambah sedikit CSS untuk styling akan memudahkan untuk menampilkan tabel informasi pada website seperti jadwal pelajaran, jadwal kolam renang atau statistik tentang dinosaurus atau tim sepakbola favoritmu. Modul ini akan memberi apa yang anda ingin ketahui tentang menyusun data tabular dengan HTML.

+ +

+ +

Prasayarat

+ +

Sebelum memulai modul ini, anda harus sudah menguasai dasar HTML — Lihat Introduction to HTML.

+ +
+

Catatan: Jika anda berkerja di komputer/tablet/atau perangkat lain yang tidak memiliki kemampuan untuk membuat file sendiri, anda dapat mencoba (sebagian besar) contoh kode pada program coding online seperti JSBin atau Glitch.

+
+ +

Panduan

+ +

Modul ini berisi artikel berikut :

+ +
+
HTML table basics
+
Artikel ini membawa anda mengawali pembahasan tabel HTML, mencakup dasar mengenai baris dan sel, heading, membuat sel span untuk kolom dan baris berganda, dan bagaimana untuk mengelompokan semua sel di dalam sebuah kolom untuk tujuan styling.
+
HTML table advanced features and accessibility
+
Modul ini mengulas beberapa fitur lanjutan tabel HTML — seperti caption/rangkuman dan mengelompokan baris dalam bagian judul tabel, bodi atau footer — dan juga melihat aksesibilitas tabel untuk melihat kesalahan pengguna
+
+ +

Penilaian

+ +
+
Structuring planet data
+
pada penilaian tabel, kami menyediakan anda data planet dalam tata surya kita, dan membantu menyusunnya dalam tabel HTML.
+
diff --git a/files/id/learn/index.html b/files/id/learn/index.html new file mode 100644 index 0000000000..3e9329375a --- /dev/null +++ b/files/id/learn/index.html @@ -0,0 +1,97 @@ +--- +title: Belajar Pengembangan Web +slug: Learn +tags: + - Index + - Landing + - Pemula + - Web +translation_of: Learn +--- +
+

V-neckline necklines are ideal for the following body types:

+ +

Because it gives a vertical impression to the outfit worn, the V-neckline can give the illusion of a slimmer, more elongated, and taller silhouette. Adapted to all body types, the V-neck can, depending on the depth chosen, create a balanced look.

+ +

A V-neckline is particularly recommended for silhouettes with broad shoulders and for people who have a large bust or a very short neck. While, overall, depending on the shape of the neckline, moreover, you're petite, skinny or voluptuous, the V-neck flatters and suits all body types.

+ +

If you want to buy some stylish and fashionable dresses you can visit bonanza satrangi online store and find the latest gorgeous and stylish dresses with good quality.

+ +

What is a square neckline?

+ +

The square collar is a neckline whose shape, on the front, evokes that of a square or a rectangle. This neckline falls straight and visually cuts the bust. This is a perfect style for women with large breasts as well as those with small breasts. However, it is not recommended for women with a square face as it will make it look too masculine.

+ +

Square necklines are ideal for the following body types:

+ +

Pyramid morphology

+ +

If you are a woman with a small neck and narrow shoulders, this type of neckline will help you lengthen your neck. In addition, if you have a round face or a pyramid-shaped body, a square neckline will help you rebalance the lines of your face as well as those of your figure. Finally, the square neckline is ideal for women with large breasts because it offers a sophisticated structure to the neckline without revealing too much.

+ +

Latest bonanza satrangi sale 2020 offers new designs and best quality dresses for men and women.

+ + + +

What is a dancer's neckline?

+ +

The dancer neckline is a very indented rounded neckline which owes its name to the leotard worn by the dancers. 

+ +

Black dress with dancer collar, fitted and sleeveless

+ +

Dancing necklines are ideal for the following body types:

+ +

Hourglass morphology

+ +

Pyramid morphology

+ +

This simple cut neckline is very flattering and fits almost any figure. Very high cut, this wide and deep neckline lengthens the neck and highlights the collarbones. Whether you are petite or tall, this neckline will suit you. The dancer collar works particularly well on people with narrow shoulders. Indeed, this neckline balances the defects as well as the proportions.

+ +

Nishatlinen provides the latest summer lawn and cotton dresses with unique designs. If you want to buy these stylish and stunning dresses you can visit nishat linen online store.

+ +

Accompany your tops with a dancer collar or your dresses with this neckline of a collar that follows its flared shape. Lightweight, layered necklaces or earrings will not compete with your cleavage and may even create a perfect lengthening effect if you are petite.

+ +

What is a halter or halter neckline?

+ +

The halter neckline or halter neckline consists of two triangular points of fabric, of variable width according to the desired effect. These cutouts run down the chest to the back of the neck. Sometimes the halter neckline is made from a single piece of fabric that is tied or tied with a drawstring or tie at the nape of the neck. 

+ + + +

Avoid this neckline if:

+ +

You have a downward shoulder line

+ +

Broad or square shoulders

+ +

If you have beefy arms, broad shoulders, or a voluminous chest, avoid wearing a dress or halter top. Indeed, this neckline will tend to make you appear wider than you are.

+ +

How to wear the halter neckline or the halter neck?

+ +

No collar is needed with this particular neckline. Opt for a pair of trendy earrings or, more simply, let this spectacular neckline speak for itself.

+ +

What is a sweetheart neckline or sweetheart neckline?

+ +

This neckline has a neckline whose shape, on the front, evokes the graphics of the upper part of a heart. This very feminine neckline is mainly associated with strapless dresses, with off the shoulders. However, a few clothes with long sleeves and thin straps may also feature a heart-shaped neckline. This neckline shape is mostly found on wedding dresses and evening gowns but is increasingly found on casual clothes like tank tops or feminine tops.

+ +

The sweetheart neckline adapts very easily to all body types and to all sizes. It is suitable for small breasts as well as medium or larger breasts. Small women, with small breasts and narrow shoulders will opt for this sweetheart neckline to appear more voluptuous. Finally, the vertical hollow of this neckline visually lengthens the face and balances the proportions of the silhouette of the wearer.

+ +

Which keyhole neckline is best?

+ +

The “keyhole” neckline is very close to the halter neckline (or halter) except that the converging diagonal lines meet at the beginning of the neck to form a small slit similar to the shape of a keyhole. This very versatile neckline can have several shapes: it can be in the form of a discreet slot on a top or a dress or adopt a more or less important oval or round shape, closed by a seam, a tie to tie or a fastening system (button, clip, etc.).

+ +

Correctly positioned, this opening can give the impression of wearing a jewel and, depending on the height or it is located, this opening can reveal more or less the neckline.

+ +

Short black dress, with a keyhole neckline.

+ +

Keyhole necklines are ideal for the following body types:

+ +

Keyhole necklines can be tailored to fit most figures and women of all ages. The effect depends on the height at which the opening is located. If you have a petite bust, this neckline can magnify your cleavage and provide an illusion of volume.

+ +

Avoid this neckline if:

+ +

You have a round body shape and a voluminous chest. Indeed, located on a voluminous chest, this low-cut keyhole neckline could harm your elegance by revealing your chest a little too much.

+ +

In conclusion:

+ +

There are many other forms of necklines and necklines and this list cannot be exhaustive, however, we have no doubt that this guide will guide you on the forms adapted to your face and your body type. Now you should be able to find the perfect top or the perfect dress to flatter your figure as well as your facial features. 

+ + +
diff --git a/files/id/learn/javascript/building_blocks/index.html b/files/id/learn/javascript/building_blocks/index.html new file mode 100644 index 0000000000..14142a20ba --- /dev/null +++ b/files/id/learn/javascript/building_blocks/index.html @@ -0,0 +1,42 @@ +--- +title: JavaScript building blocks +slug: Learn/JavaScript/Building_blocks +translation_of: Learn/JavaScript/Building_blocks +--- +
{{LearnSidebar}}
+ +

Pada modul ini, kita lanjutkan cakupan semua fitur dasar JavaScript, arahkan perhatian kita pada jenis blok kode yang biasa ditemukan seperti pernyataan kondisional, perulangan, fungsi, dan events. Anda pernah melihat dasar ini sudah ada di kursus, tapi hanya sebentar - di sini kami akan membahas semuanya secara jelas.

+ +

Persyaratan

+ +

Sebelum memulai modul ini, Anda harus memiliki beberapa pemahaman mengenai dasar-dasar dari HTML dan CSS, dan Anda juga harus sudah mengerjakan modul kami sebelumnya , Memulai JavaScript.

+ +
+

Catatan: Jika Anda bekerja di komputer / tablet / perangkat lain dimana Anda tidak memiliki kemampuan untuk membuat file sendiri, Anda bisa mencoba (sebagian besar) contoh kode dalam program pengkodean online seperti JSBin atau Thimble.

+
+ +

Panduan

+ +
+
Membuat keputusan di kode Anda — kondisional
+
Dalam bahasa pemrograman apapun, kode perlu untuk membuat keputusan dan melakukan tindakan yang sesuai pada masukan yang berbeda. Misalnya dalam permainan, jika jumlah nyawa pemain adalah 0, maka permainannya berakhir. Dalam aplikasi cuaca, jika yang dilihat adalah pagi hari maka akan tampil grafik matahari terbit dan jika sudah malam hari maka akan menunjukkan bintang dan bulan. Pada artikel ini kita akan membahas bagaimana struktur kondisional bekerja dalam JavaScript.
+
Kode perulangan (looping)
+
Terkadang Anda membutuhkan tugas yang dilakukan lebih dari sekali dan berulang-ulang. Misalnya melihat daftar banyak nama. Dalam pemrograman, loop melakukan pekerjaan ini dengan sangat baik. Di sini kita akan melihat struktur perulangan di JavaScript.
+
Fungsi — blok kode yang bisa digunakan kembali
+
Konsep penting lainnya dalam berkode adalah fungsi. Fungsi memungkinkan Anda untuk menyimpan bagian kode yang melakukan satu tugas di dalam blok yang ditetapkan, dan kemudian memanggil kode itu kapan pun Anda memerlukannya kemudian menggunakan satu perintah pendek untuk memanggilnya daripada harus mengetikkan kode yang sama beberapa kali. Pada artikel ini kita akan mengeksplorasi konsep dasar di balik fungsi seperti sintaks dasar, bagaimana cara memanggil dan mendefinisikan fungsi, ruang lingkup, dan parameternya.
+
Membangun fungsi sendiri
+
Dengan sebagian besar teori esensial yang telah dibahas dalam artikel sebelumnya, artikel ini akan memberikan pengalaman praktik. Di sini Anda akan mendapatkan beberapa latihan dengan membangun fungsi Anda sendiri. Ikutilah jalannya, kami juga akan menjelaskan beberapa rincian lebih lanjut mengenai fungsi.
+
Fungsi mengembalikan suatu nilai
+
Ada satu konsep penting yang bisa kita diskusikan dalam kursus ini, untuk menutup fungsi kita bisa mengembalikan suatu nilai. Beberapa fungsi tidak mengembalikan nilai yang signifikan setelah selesai, tapi ada juga yang melakukannya. Penting untuk memahami apa nilai mereka, bagaimana memanfaatkannya dalam kode Anda, dan bagaimana membuat fungsi Anda sendiri mengembalikan nilai yang berguna.
+
Perkenalan events
+
Events adalah tindakan atau kejadian yang terjadi di sistem yang Anda gunakan dalam pemrograman, dimana sistem memberi tahu Anda sehingga Anda dapat meresponsnya dengan cara apa pun jika diinginkan. Misalnya jika pengguna mengeklik tombol pada laman web, Anda mungkin ingin menanggapi tindakan tersebut dengan menampilkan kotak informasi. Pada artikel akhir ini kita akan membahas beberapa konsep penting seputar events, dan melihat bagaimana mereka bekerja di browser.
+
+ +

Penilaian

+ +

Penilaian berikut akan menguji pemahaman Anda tentang dasar-dasar JavaScript yang tercakup dalam panduan di atas.

+ +
+
Galeri Gambar
+
Sekarang setelah melihat fundamental dari bangunan blok di JavaScript, kami akan menguji pengetahuan Anda tentang loop, fungsi, kondisional dan events dengan membangun barang yang cukup umum yang akan Anda lihat di banyak situs web yaitu galeri gambar yang dibuat dengan JavaScript.
+
diff --git a/files/id/learn/javascript/client-side_web_apis/index.html b/files/id/learn/javascript/client-side_web_apis/index.html new file mode 100644 index 0000000000..171c0647b7 --- /dev/null +++ b/files/id/learn/javascript/client-side_web_apis/index.html @@ -0,0 +1,50 @@ +--- +title: Client-side web APIs +slug: Learn/JavaScript/Client-side_web_APIs +tags: + - API + - Artikel + - CodingScripting + - DOM + - JavaScript + - Landing + - Latihan + - Media + - Module + - Pemula + - WebAPI + - data +translation_of: Learn/JavaScript/Client-side_web_APIs +--- +
{{LearnSidebar}}
+ +

Ketika menulis JavaScript client-side untuk website atau aplikasi, anda tidak akan berkembang jauh sebelum memulai cara menggunakan API — yaitu sekumpulan interface untuk memanifulasi berbagai aspect pada browser dan operating sistem dimana situs dijalankan, atau cara mengolah data dari website atau service yang lain. Didalam modul kali ini, kita akan menjelajahi apa itu API dan bagaimana cara menggunakan beberapa API yang sangat umum yang mungkin anda akan temukan dalam pekerjaan Development anda.

+ +

Prasyarat

+ +

Untuk mendapatkan hasil maksimal dalam modul ini, diharuskan bagi anda menyelesaikan tahapan modul JavaScript pada seri-seri (First steps, Building blocks, dan JavaScript objects). Keseluruhan modul tersebut cukup banyak melibatkan cara-cara penggunaan API yang sederhana, dikarenakan akan sulit untuk menulis contoh-contoh JavaScript client-side yang sangat berguna tanpa mereka! Disini kita meningkat pada satu level, dengan mengharapkan pengetahunan lebih mendalam tentang core pemrograman JavaScript dan mengeksplorasi banyak contoh Web API yang umum.

+ +

Pengetahuan dasar mengenai HTML dan CSS juga akan sangat berguna.

+ +
+

Catatan: Jika anda sedang bekerja dengan  perangkat dimana anda tidak mendapatkan kemampuan untuk membuat file -file anda sendiri, anda dapat mencoba (hampir semua) contoh code pada sebuah program pemrograman online semisal JSBin atau Thimble.

+
+ +

Panduan

+ +
+
Pengenalan tentang Web API
+
Sebagai permulaan, kita akan memulai melihat mengenai API dari sebuah level yang tinggi — tentang apa itu API, bagaimana cara API bekerja, bagaimana cara menggunakannya pada program kita, dan bagaimana mereka dibentuk secara terstruktur? Kita juga akan melihat apa perbedaan utama antara Class-class API dan jenis penggunaan sepert apa yang mereka miliki.
+
Cara memanipulasi dokumen
+
Ketika sedang menulis website dan aplikasi, satu hal yang sangat penting yang anda ingin lakukan adalah menemukan berbagai cara untuk memanipulasi dokumen-dokumen web. Hal ini biasanya dilakukan menggunakan Document Object Model (DOM), sekumpulan API untuk mengontrol HTML dan memperindah tampilan informasi yang menekankan penggunaan objek {{domxref("Document")}}.  Pada artikel ini, kita akan melihat bagaimana cara menggunakan DOM secara detail, we'll look at how to use the DOM in detail, bersamaan dengan berbagai API menarik lainnya yang dapat mengubah ruang lingkup anda dengan cara-cara yang menarik.
+
Cara mengambil data dari server
+
Another very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entirely new page. This seemingly small detail has had a huge impact on the performance and behavior of sites, so in this article, we'll explain the concept, and look at technologies that make it possible, such as {{domxref("XMLHttpRequest")}} and the Fetch API.
+
Third party APIs
+
The APIs we've covered so far are built into the browser, but not all APIs are. Many large websites and services such as Google Maps, Twitter, Facebook, PayPal, etc. provide APIs allowing developers to make use of their data (e.g. displaying your twitter stream on your blog) or services (e.g. displaying custom Google Maps on your site, or using Facebook login to log in your users). This article looks at the difference between browser APIs and 3rd party APIs and shows some typical uses of the latter.
+
Drawing graphics
+
The browser contains some very powerful graphics programming tools, from the Scalable Vector Graphics (SVG) language, to APIs for drawing on HTML {{htmlelement("canvas")}} elements, (see The Canvas API and WebGL). Ths article provides an introduction to the Canvas API, and further resources to allow you to learn more.
+
Video and audio APIs
+
HTML5 comes with elements for embedding rich media in documents — {{htmlelement("video")}} and {{htmlelement("audio")}} — which in turn come with their own APIs for controlling playback, seeking, etc. This article shows you how to do common tasks such as creating custom playback controls.
+
Client-side storage
+
Modern web browsers feature a number of different technologies that allow you to store data related to web sites and retrieve it when necessary allowing you to persist data long term, save sites offline, and more. This article explains the very basics of how these work.
+
diff --git a/files/id/learn/javascript/client-side_web_apis/introduction/index.html b/files/id/learn/javascript/client-side_web_apis/introduction/index.html new file mode 100644 index 0000000000..20cd0d7214 --- /dev/null +++ b/files/id/learn/javascript/client-side_web_apis/introduction/index.html @@ -0,0 +1,278 @@ +--- +title: Introduction to web APIs +slug: Learn/JavaScript/Client-side_web_APIs/Introduction +translation_of: Learn/JavaScript/Client-side_web_APIs/Introduction +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/Client-side_web_APIs/Manipulating_documents", "Learn/JavaScript/Client-side_web_APIs")}}
+ +

First up, we'll start by looking at APIs from a high level — what are they, how do they work, how do you use them in your code, and how are they structured? We'll also take a look at what the different main classes of APIs are, and what kind of uses they have.

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, a basic understanding of HTML and CSS, JavaScript basics (see first steps, building blocks, JavaScript objects).
Objective:To gain familiarity with APIs, what they can do, and how you can use them in your code.
+ +

What are APIs?

+ +

Application Programming Interfaces (APIs) are constructs made available in programming languages to allow developers to create complex functionality more easily. They abstract more complex code away from you, providing some easier syntax to use in its place.

+ +

As a real-world example, think about the electricity supply in your house, apartment, or other dwellings. If you want to use an appliance in your house, you simply plug it into a plug socket and it works. You don't try to wire it directly into the power supply — to do so would be really inefficient and, if you are not an electrician, difficult and dangerous to attempt.

+ +

+ +

Image source: Overloaded plug socket by The Clear Communication People, on Flickr.

+ +

In the same way, if you want to say, program some 3D graphics, it is a lot easier to do it using an API written in a higher level language such as JavaScript or Python, rather than try to directly write low level code (say C or C++) that directly controls the computer's GPU or other graphics functions.

+ +
+

Note: See also the API glossary entry for further description.

+
+ +

APIs in client-side JavaScript

+ +

Client-side JavaScript, in particular, has many APIs available to it — these are not part of the JavaScript language itself, rather they are built on top of the core JavaScript language, providing you with extra superpowers to use in your JavaScript code. They generally fall into two categories:

+ + + +

 

+ +

 

+ +

+ +

 

+ +

Relationship between JavaScript, APIs, and other JavaScript tools

+ +

So above, we talked about what client-side JavaScript APIs are, and how they relate to the JavaScript language. Let's recap this to make it clearer, and also mention where other JavaScript tools fit in:

+ + + +

What can APIs do?

+ +

There are a huge number of APIs available in modern browsers that allow you to do a wide variety of things in your code. You can see this by taking a look at the MDN APIs index page.

+ +

Common browser APIs

+ +

In particular, the most common categories of browser APIs you'll use (and which we'll cover in this module in greater detail) are:

+ + + +

Common third-party APIs

+ +

Third party APIs come in a large variety; some of the more popular ones that you are likely to make use of sooner or later are:

+ + + +
+

Note: You can find information on a lot more 3rd party APIs at the Programmable Web API directory.

+
+ +

How do APIs work?

+ +

Different JavaScript APIs work in slightly different ways, but generally, they have common features and similar themes to how they work.

+ +

They are based on objects

+ +

APIs are interacted with in your code using one or more JavaScript objects, which serve as containers for the data the API uses (contained in object properties), and the functionality the API makes available (contained in object methods).

+ +
+

Note: If you are not already familiar with how objects work, you should go back and work through our JavaScript objects module before continuing.

+
+ +

Let's return to the example of the Geolocation API — this is a very simple API that consists of a few simple objects:

+ + + +

So how do these objects interact? If you look at our maps-example.html example (see it live also), you'll see the following code:

+ +
navigator.geolocation.getCurrentPosition(function(position) {
+  var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
+  var myOptions = {
+    zoom: 8,
+    center: latlng,
+    mapTypeId: google.maps.MapTypeId.TERRAIN,
+    disableDefaultUI: true
+  }
+  var map = new google.maps.Map(document.querySelector("#map_canvas"), myOptions);
+});
+ +
+

Note: When you first load up the above example, you should be given a dialog box asking if you are happy to share your location with this application (see the {{anch("They have additional security mechanisms where appropriate")}} section later in the article). You need to agree to this to be able to plot your location on the map. If you still can't see the map, you may need to set your permissions manually; you can do this in various ways depending on what browser you are using; for example in Firefox go to > Tools > Page Info > Permissions, then change the setting for Share Location; in Chrome go to Settings > Privacy > Show advanced settings > Content settings then change the settings for Location.

+
+ +

We first want to use the {{domxref("Geolocation.getCurrentPosition()")}} method to return the current location of our device. The browser's {{domxref("Geolocation")}} object is accessed by calling the {{domxref("Navigator.geolocation")}} property, so we start off by using

+ +
navigator.geolocation.getCurrentPosition(function(position) { ... });
+ +

This is equivalent to doing something like

+ +
var myGeo = navigator.geolocation;
+myGeo.getCurrentPosition(function(position) { ... });
+ +

But we can use the dot syntax to chain our property/method access together, reducing the number of lines we have to write.

+ +

The {{domxref("Geolocation.getCurrentPosition()")}} method only has a single mandatory parameter, which is an anonymous function that will run when the device's current position has been successfully retrieved. This function itself has a parameter, which contains a {{domxref("Position")}} object representing the current position data.

+ +
+

Note: A function that is taken by another function as an argument is called a callback function.

+
+ +

This pattern of invoking a function only when an operation has been completed is very common in JavaScript APIs — making sure one operation has completed before trying to use the data the operation returns in another operation. These are called asynchronous operations. Because getting the device's current position relies on an external component (the device's GPS or other geolocation hardware), we can't guarantee that it will be done in time to just immediately use the data it returns. Therefore, something like this wouldn't work:

+ +
var position = navigator.geolocation.getCurrentPosition();
+var myLatitude = position.coords.latitude;
+ +

If the first line had not yet returned its result, the second line would throw an error, because the position data would not yet be available. For this reason, APIs involving asynchronous operations are designed to use {{glossary("callback function")}}s, or the more modern system of Promises, which were made available in ECMAScript 6 and are widely used in newer APIs.

+ +

We are combining the Geolocation API with a third party API — the Google Maps API — which we are using to plot the location returned by getCurrentPosition() on a Google Map. We make this API available on our page by linking to it — you'll find this line in the HTML:

+ +
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyDDuGt0E5IEGkcE6ZfrKfUtE9Ko_de66pA"></script>
+ +

To use the API, we first create a LatLng object instance using the google.maps.LatLng() constructor, which takes our geolocated {{domxref("Coordinates.latitude")}} and {{domxref("Coordinates.longitude")}} values as parameters:

+ +
var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
+ +

This object is itself set as the value of the center property of an options object that we've called myOptions. We then create an object instance to represent our map by calling the google.maps.Map() constructor, passing it two parameters — a reference to the {{htmlelement("div")}} element we want to render the map on (with an ID of map_canvas), and the options object we defined just above it.

+ +
var myOptions = {
+  zoom: 8,
+  center: latlng,
+  mapTypeId: google.maps.MapTypeId.TERRAIN,
+  disableDefaultUI: true
+}
+
+var map = new google.maps.Map(document.querySelector("#map_canvas"), myOptions);
+ +

With this done, our map now renders.

+ +

This last block of code highlights two common patterns you'll see across many APIs. First of all, API objects commonly contain constructors, which are invoked to create instances of those objects that you'll use to write your program. Second, API objects often have several options available that can be tweaked to get the exact environment you want for your program. API constructors commonly accept options objects as parameters, which is where you'd set such options.

+ +
+

Note: Don't worry if you don't understand all the details of this example immediately. We'll cover using third party APIs in a lot more detail in a future article.

+
+ +

They have recognizable entry points

+ +

When using an API, you should make sure you know where the entry point is for the API. In The Geolocation API, this is pretty simple — it is the {{domxref("Navigator.geolocation")}} property, which returns the browser's {{domxref("Geolocation")}} object that all the useful geolocation methods are available inside.

+ +

The Document Object Model (DOM) API has an even simpler entry point — its features tend to be found hanging off the {{domxref("Document")}} object, or an instance of an HTML element that you want to affect in some way, for example:

+ +
var em = document.createElement('em'); // create a new em element
+var para = document.querySelector('p'); // reference an existing p element
+em.textContent = 'Hello there!'; // give em some text content
+para.appendChild(em); // embed em inside para
+ +

Other APIs have slightly more complex entry points, often involving creating a specific context for the API code to be written in. For example, the Canvas API's context object is created by getting a reference to the {{htmlelement("canvas")}} element you want to draw on, and then calling its {{domxref("HTMLCanvasElement.getContext()")}} method:

+ +
var canvas = document.querySelector('canvas');
+var ctx = canvas.getContext('2d');
+ +

Anything that we want to do to the canvas is then achieved by calling properties and methods of the content object (which is an instance of {{domxref("CanvasRenderingContext2D")}}), for example:

+ +
Ball.prototype.draw = function() {
+  ctx.beginPath();
+  ctx.fillStyle = this.color;
+  ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
+  ctx.fill();
+};
+ +
+

Note: You can see this code in action in our bouncing balls demo (see it running live also).

+
+ +

They use events to handle changes in state

+ +

We already discussed events earlier on in the course, in our Introduction to events article — this article looks in detail at what client-side web events are and how they are used in your code. If you are not already familiar with how client-side web API events work, you should go and read this article first before continuing.

+ +

Some web APIs contain no events, but some contain a number of events. The handler properties that allow us to run functions when events fire are generally listed in our reference material in separate "Event handlers" sections. As a simple example, instances of the XMLHttpRequest object (each one represents an HTTP request to the server to retrieve a new resource of some kind) have a number of events available on them, for example the load event is fired when a response has been successfully returned containing the requested resource, and it is now available.

+ +

The following code provides a simple example of how this would be used:

+ +
var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
+var request = new XMLHttpRequest();
+request.open('GET', requestURL);
+request.responseType = 'json';
+request.send();
+
+request.onload = function() {
+  var superHeroes = request.response;
+  populateHeader(superHeroes);
+  showHeroes(superHeroes);
+}
+ +
+

Note: You can see this code in action in our ajax.html example (see it live also).

+
+ +

The first five lines specify the location of resource we want to fetch, create a new instance of a request object using the XMLHttpRequest() constructor, open an HTTP GET request to retrieve the specified resource, specify that the response should be sent in JSON format, then send the request.

+ +

The onload handler function then specifies what we do with the response. We know the response will be successfully returned and available after the load event has required (unless an error occurred), so we save the response containing the returned JSON in the superHeroes variable, then pass it to two different functions for further processing.

+ +

They have additional security mechanisms where appropriate

+ +

WebAPI features are subject to the same security considerations as JavaScript and other web technologies (for example same-origin policy), but they sometimes have additional security mechanisms in place. For example, some of the more modern WebAPIs will only work on pages served over HTTPS due to them transmitting potentially sensitive data (examples include Service Workers and Push).

+ +

In addition, some WebAPIs request permission to be enabled from the user once calls to them are made in your code. As an example, you may have noticed a dialog like the following when loading up our earlier Geolocation example:

+ +

+ +

The Notifications API asks for permission in a similar fashion:

+ +

+ +

These permission prompts are given to users for security — if they weren't in place, then sites could start secretly tracking your location without you knowing it, or spamming you with a lot of annoying notifications.

+ +

Summary

+ +

At this point, you should have a good idea of what APIs are, how they work, and what you can do with them in your JavaScript code. You are probably excited to start actually doing some fun things with specific APIs, so let's go! Next up, we'll look at manipulating documents with the Document Object Model (DOM).

+ +

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

+ +

In this module

+ + diff --git a/files/id/learn/javascript/first_steps/index.html b/files/id/learn/javascript/first_steps/index.html new file mode 100644 index 0000000000..6f7e166951 --- /dev/null +++ b/files/id/learn/javascript/first_steps/index.html @@ -0,0 +1,63 @@ +--- +title: Memulai Javascript +slug: Learn/JavaScript/First_steps +tags: + - Arrays + - Article + - Assessment + - Beginner + - Guide + - JavaScript + - Landing + - Operator + - String + - Variables +translation_of: Learn/JavaScript/First_steps +--- +
{{LearnSidebar}}
+ +

Pada modul Javascript pertama kita, kita akan mengawali dengan menjawab beberapa pertanyaan fundamental seperti "Apa itu JavaScript?", "seperti apa?", dan "untuk apa?", sebelum anda melanjutkan belajar menulis javascript pertama kali. Setelah itu, kita akan mendiskusikan beberapa kunci block pembangun secara detail, Seperti variable, string, number dan array.

+ +

Persyaratan

+ +

Sebelum memulai modul ini, anda tidak perlu memiliki pemahaman javascript sebelumnya, namun anda perlu setidaknya pernah menggunakan HTML and CSS. Anda disarankan belajar dari modul berikut sebelum memulai di javascript:

+ + + +
+

Catatan: jika anda bekerja dengan menggunakan computer/tablet/perangkat lainnya dimana anda tidak memiliki kemampuan untuk membuat file anda sendiri, anda bisa mencoba (sangat disarankan) contoh kode di online coding program seperti JSBin atau Thimble.

+
+ +

Panduan

+ +
+
Apa itu JavaScript?
+
Selamat datang di Kursus Javascript MDN untuk pemula! pada artikel pertama kita akan melihat javascript dari level tertinggi, menjawab pertanyaan seperti "Apa itu javascript?", dan "untuk apa?", dan memastikan anda nyaman dengan tujuan dari JavaScript.
+
Percikan pertama Javascript
+
Sekarang anda akan belajar teori tentang JavaScript, dan apa yang bisa anda lakukan dengan itu, kita akan memberikan anda kursus kilat pada dasar JavaScript melalui tutorial yang praktis. Disini anda akan membuat permainan sederhana "Guess the number" langkah demi langkah.
+
Apa yang salah? Memecahkan Masalah JavaScript
+
Ketika anda membangun permainan "Guess the number" pada artikel sebelumnya, anda mungkin telah  menemukan bahwa itu tidak berjalan dengan baik. Jangan takut — artikel ini akan membantu anda memecahkan masalah tersebut dengan memberikan anda beberapa tips sederhana untuk mencari dan memperbaiki error di program javascript.
+
Menyimpan informasi yang anda butuhkan — Variable
+
Setelah membaca beberapa artikel, anda perlu mengetahui apa itu javascript, apa yang bisa dimanfaatkan bagi anda, bagaimana menggunakannya dengan teknologi web lain, dan seperti apa fitur utama dari level tertinggi. Pada artikel ini kita akan kembali ke hal yang lebihdasar, melihat bagaimana bekerja dengan hal paling dasar pada block pembangun JavaScript — Variable.
+
Matematika dasar di JavaScript — number dan operator
+
Pada poin ini anda akan mendiskusikan matematika di JavaScript — bagaimana kita mengabungkan operator dan fitur lain untuk berhasil memanipulasi angka melakukan perintah kita.
+
Penanganan text — strings di JavaScript
+
Selanjunya kita akan mengalihkan perhatian kita pada string — ini adalah potongan teks di programming. Pada artikel ini kita akan melihat pada semua hal umum yang sangat perlu anda tahu tentang string ketika belajar JavaScript, seperti membuat string, memunculkan tanda kutip pada string, dan menggabungkanya.
+
Metod string yang berguna
+
Sekarang kita telah melihat pada dasar string, mari kita beralih dan mulai memikirkan tentang operasi apa yang berguna yang bisa kita gunakan dengan method built-in pada string, seperti mencari panjang teks string, menggabung dan memisahkan string, mensubtitusi sebuah karakter pada string ke lainnya, dan banyak lagi.
+
Arrays
+
Pada artikel terakhir pada modul ini, kita akan melihat pada array — cara rapi untuk menyimpan daftar item pada sebuah nama variabel. Disini kita akan melihat kenapa ini berguna, kemudian mencari tahu bagaimana membuat array, mengambil, menambah, dan menghapus item yang tersimpan pada array, dan banyak lagi.
+
+ +

Penilaian

+ +

Penilaian berikut akan menguji pemahaman anda tentang dasar javascrip berdasarkan paduan yang telah diberikan.

+ +
+
Silly story generator
+
Pada penilaian ini anda ditugaskan mengambil beberapa pengetahuan yang anda dapatkan dari modul artikel ini dan menerapkannya dengan membuat sebuah aplikasi seru yang menghasilkan cerita konyol secara acak. Selamat Bersenang — senang!
+
diff --git a/files/id/learn/javascript/first_steps/what_is_javascript/index.html b/files/id/learn/javascript/first_steps/what_is_javascript/index.html new file mode 100644 index 0000000000..f85ec8b2e1 --- /dev/null +++ b/files/id/learn/javascript/first_steps/what_is_javascript/index.html @@ -0,0 +1,433 @@ +--- +title: What is JavaScript? +slug: Learn/JavaScript/First_steps/What_is_JavaScript +tags: + - 3rd party + - API + - Artikel + - Bahasa Indonesia + - Browser + - Coding + - JavaScript + - Learn + - Pemula + - programming +translation_of: Learn/JavaScript/First_steps/What_is_JavaScript +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}
+ +

Selamat datang di kursus Javascript MDN tingkat pemula ini! Di artikel ini kita akan melihat JavaScript dari level tinggi, menjawab pertanyaan seperti "Apa itu?" dan "Bagaimana kamu dapat melakukannya", dan memastikan kamu nyaman dengan kegunaan JavaScript 

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, a basic understanding of HTML and CSS.
Objective:To gain familiarity with what JavaScript is, what it can do, and how it fits into a web site.
+ +

Definisi Tingkat Tinggi

+ +

JavaScript merupakan bahasa pemrograman yang memungkinkan anda untuk melakukan sesuatu yang kompleks di halaman web — ketika halaman web dibuka, pasti ada sesuatu selain menampilkan halaman statis dan informasi — halaman web akan menampilkan konten terbaru, map interaktif, animasi 2D/3D, scrolling video, dan lain-lain. — Apabila semua itu ada di sebuah halaman web, sudah pasti halaman itu menggunakan bahasa JavaScript.  JavaScript merupakan lapisan/layer ketiga dari standard web technologies, yang pertama HTML dan kedua CSS. Anda dapat melihat dokumentasinya di link yang di sediakan.

+ +

+ + + +

Mari kita buat label teks sederhana sebagai contoh. kita bisa gunakan HTML untuk strukturnya.

+ +
<p>Player 1: Chris</p>
+ +

+ +

Lalu kita tambahkan CSS agar terlihat menarik.

+ +
p {
+  font-family: 'helvetica neue', helvetica, sans-serif;
+  letter-spacing: 1px;j
+  text-transform: uppercase;
+  text-align: center;
+  border: 2px solid rgba(0,0,200,0.6);
+  background: rgba(0,0,200,0.3);
+  color: rgba(0,0,200,0.6);
+  box-shadow: 1px 1px 2px rgba(0,0,200,0.4);
+  border-radius: 10px;
+  padding: 3px 10px;
+  display: inline-block;
+  cursor: pointer;
+}
+ +

+ +

Dan yang terakhir, kita akan menambahkan JavaScript sehingga kita bisa menambahkan Player:

+ +
var para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  var name = prompt('Enter a new name');
+  para.textContent = 'Player 1: ' + name;
+}
+
+ +

{{ EmbedLiveSample('Definisi_Tingkat_Tinggi', '', '', '', 'Learn/JavaScript/First_steps/What_is_JavaScript') }}

+ +

Coba kalian klik label teks yang sudah kita buat dan lihat apa yang terjadi!. Kalian akan diminta menuliskan nama untuk Player 1. (Note: Kalian bisa melihat demo ini di GitHub  — source code, atau live preview)

+ +

JavaScript bisa melakukan sesuatu lebih dari yang diatas! — mari kita jelajahi lebih tentang JavaScript.

+ +

Lalu apa yang bisa dilakukannya?

+ +

Inti dari bahasa JavaScript terdiri dari beberapa fitur umum pada bahasa program lainnya yang memungkinkan kita:

+ + + +

What is even more exciting however is the functionality built on top of the core JavaScript language. So-called Application Programming Interfaces (APIs) provide you with extra superpowers to use in your JavaScript code.

+ +

APIs are ready-made sets of code building blocks that allow a developer to implement programs that would otherwise be hard or impossible to implement. They do the same thing for programming that ready-made furniture kits do for home building — it is much easier to take ready-cut panels and screw them together to make a bookshelf than it is to work out the design yourself, go and find the correct wood, cut all the panels to the right size and shape, find the correct-sized screws, and then put them together to make a bookshelf.

+ +

They generally fall into two categories.

+ +

+ +

Browser APIs are built into your web browser, and are able to expose data from the surrounding computer environment, or do useful complex things. For example:

+ + + +
+

Note: Many of the above demos won't work in an older browser — when experimenting, it's a good idea to use a modern browser like Firefox, Chrome, Edge or Opera to run your code in. You will need to consider cross browser testing in more detail when you get closer to delivering production code (i.e. real code that real customers will use).

+
+ +

Third party APIs are not built into the browser by default, and you generally have to grab their code and information from somewhere on the Web. For example:

+ + + +
+

Note: These APIs are advanced, and we'll not be covering any of these in this module. You can find out much more about these in our Client-side web APIs module.

+
+ +

There's a lot more available, too! However, don't get over excited just yet. You won't be able to build the next Facebook, Google Maps or Instagram after studying JavaScript for 24 hours — there are a lot of basics to cover first. And that's why you're here — let's move on!

+ +

What is JavaScript doing on your page?

+ +

Here we'll start actually looking at some code, and while doing so explore what actually happens when you run some JavaScript in your page.

+ +

Let's briefly recap the story of what happens when you load a web page in a browser (first talked about in our How CSS works article). When you load a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an execution environment (the browser tab). This is like a factory that takes in raw materials (the code) and outputs a product (the web page).

+ + + + + +

+ + + +

The JavaScript is executed by the browser's JavaScript engine, after the HTML and CSS have been assembled and put together into a web page. This ensures that the structure and style of the page are already in place by the time the JavaScript starts to run.

+ +

This is a good thing, as a very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above). If the JavaScript loaded and tried to run before the HTML and CSS were there to affect, then errors would occur.

+ +

Browser security

+ +

Each browser tab is its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website. This is a good security measure — if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things.

+ +
+

Note: There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course.

+
+ +

JavaScript running order

+ +

When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom. This means that you need to be careful what order you put things in. For example, let's return to the block of JavaScript we saw in our first example:

+ +
var para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  var name = prompt('Enter a new name');
+  para.textContent = 'Player 1: ' + name;
+}
+ +

Here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the updateName() code block (lines 5–8) is run. The updateName() code block (these types of reusable code blocks are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display.

+ +

If you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an error returned in the browser developer console — TypeError: para is undefined. This means that the para object does not exist yet, so we can't add an event listener to it.

+ +
+

Note: This is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them.

+
+ +

Interpreted versus compiled code

+ +

You might hear the terms interpreted and compiled in the context of programming. In interpreted languages, the code is run from top to bottom and the result of running the code is immediately returned. You don't have to transform the code into a different form before the browser runs it.

+ +

Compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer. For example C/C++ are compiled into assembly language that is then run by the computer.

+ +

JavaScript is a lightweight interpreted programming language. Both approaches have different advantages, which we won't discuss at this point.

+ +

Server-side versus client-side code

+ +

You might also hear the terms server-side and client-side code, especially in the context of web development. Client-side code is code that is run on the user's computer — when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser. In this JavaScript module we are explicitly talking about client-side JavaScript.

+ +

Server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser. Examples of popular server-side web languages include PHP, Python, Ruby, and ASP.NET. And JavaScript! JavaScript can also be used as a server-side language, for example in the popular Node.js environment — you can find out more about server-side JavaScript in our Dynamic Websites – Server-side programming topic.

+ +

Dynamic versus static code

+ +

The word dynamic is used to describe both client-side JavaScript, and server-side languages — it refers to the ability to update the display of a web page/app to show different things in different circumstances, generating new content as required. Server-side code dynamically generates new content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically generates new content inside the browser on the client, e.g. creating a new HTML table, filling it with data requested from the server, then displaying the table in a web page shown to the user. The meaning is slightly different in the two contexts, but related, and both approaches (server-side and client-side) usually work together.

+ +

A web page with no dynamically updating content is referred to as static — it just shows the same content all the time.

+ +

How do you add JavaScript to your page?

+ +

JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses {{htmlelement("link")}} elements to apply external stylesheets and {{htmlelement("style")}} elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the {{htmlelement("script")}} element. Let's learn how this works.

+ +

Internal JavaScript

+ +
    +
  1. First of all, make a local copy of our example file apply-javascript.html. Save it in a directory somewhere sensible.
  2. +
  3. Open the file in your web browser and in your text editor. You'll see that the HTML creates a simple web page containing a clickable button.
  4. +
  5. Next, go to your text editor and add the following in your head — just before your closing </head> tag: +
    <script>
    +
    +  // JavaScript goes here
    +
    +</script>
    +
  6. +
  7. Now we'll add some JavaScript inside our {{htmlelement("script")}} element to make the page do something more interesting — add the following code just below the "// JavaScript goes here" line: +
    document.addEventListener("DOMContentLoaded", function() {
    +  function createParagraph() {
    +    var para = document.createElement('p');
    +    para.textContent = 'You clicked the button!';
    +    document.body.appendChild(para);
    +  }
    +
    +  var buttons = document.querySelectorAll('button');
    +
    +  for(var i = 0; i < buttons.length ; i++) {
    +    buttons[i].addEventListener('click', createParagraph);
    +  }
    +});
    +
  8. +
  9. Save your file and refresh the browser — now you should see that when you click the button, a new paragraph is generated and placed below.
  10. +
+ +
+

Note: If your example doesn't seem to work, go through the steps again and check that you did everything right. Did you save your local copy of the starting code as a .html file? Did you add your {{htmlelement("script")}} element just before the </head> tag? Did you enter the JavaScript exactly as shown? JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown, otherwise it may not work.

+
+ +
+

Note: You can see this version on GitHub as apply-javascript-internal.html (see it live too).

+
+ +

External JavaScript

+ +

This works great, but what if we wanted to put our JavaScript in an external file? Let's explore this now.

+ +
    +
  1. First, create a new file in the same directory as your sample HTML file. Call it script.js — make sure it has that .js filename extension, as that's how it is recognized as JavaScript.
  2. +
  3. Replace your current {{htmlelement("script")}} element with the following: +
    <script src="script.js" defer></script>
    +
  4. +
  5. Inside script.js, add the following script: +
    function createParagraph() {
    +  var para = document.createElement('p');
    +  para.textContent = 'You clicked the button!';
    +  document.body.appendChild(para);
    +}
    +
    +var buttons = document.querySelectorAll('button');
    +
    +for(var i = 0; i < buttons.length ; i++) {
    +  buttons[i].addEventListener('click', createParagraph);
    +}
    +
  6. +
  7. Save and refresh your browser, and you should see the same thing! It works just the same, but now we've got our JavaScript in an external file. This is generally a good thing in terms of organizing your code, and making it reusable across multiple HTML files. Plus the HTML is easier to read without huge chunks of script dumped in it.
  8. +
+ +
+

Note: You can see this version on GitHub as apply-javascript-external.html and script.js (see it live too).

+
+ +

Inline JavaScript handlers

+ +

Note that sometimes you'll come across bits of actual JavaScript code living inside HTML. It might look something like this:

+ +
function createParagraph() {
+  var para = document.createElement('p');
+  para.textContent = 'You clicked the button!';
+  document.body.appendChild(para);
+}
+ +
<button onclick="createParagraph()">Click me!</button>
+ +

You can try this version of our demo below.

+ +

{{ EmbedLiveSample('Inline_JavaScript_handlers', '100%', 150, "", "", "hide-codepen-jsfiddle") }}

+ +

This demo has exactly the same functionality as in the previous two sections, except that the {{htmlelement("button")}} element includes an inline onclick handler to make the function run when the button is pressed.

+ +

Please don't do this, however. It is bad practice to pollute your HTML with JavaScript, and it is inefficient — you'd have to include the onclick="createParagraph()" attribute on every button you wanted the JavaScript to apply to.

+ +

Using a pure JavaScript construct allows you to select all the buttons using one instruction. The code we used above to serve this purpose looks like this:

+ +
var buttons = document.querySelectorAll('button');
+
+for (var i = 0; i < buttons.length ; i++) {
+  buttons[i].addEventListener('click', createParagraph);
+}
+ +

This might be a bit longer than the onclick attribute, but it will work for all buttons — no matter how many are on the page, nor how many are added or removed. The JavaScript does not need to be changed.

+ +
+

Note: Try editing your version of apply-javascript.html and add a few more buttons into the file. When you reload, you should find that all of the buttons when clicked will create a paragraph. Neat, huh?

+
+ +

Script loading strategies

+ +

There are a number of issues involved with getting scripts to load at the right time. Nothing is as simple as it seems! A common problem is that all the HTML on a page is loaded in the order in which it appears. If you are using JavaScript to manipulate elements on the page (or more accurately, the Document Object Model), your code won't work if the JavaScript is loaded and parsed before the HTML you are trying to do something to.

+ +

In the above code examples, in the internal and external examples the JavaScript is loaded and run in the head of the document, before the HTML body is parsed. This could cause an error, so we've used some constructs to get around it.

+ +

In the internal example, you can see this structure around the code:

+ +
document.addEventListener("DOMContentLoaded", function() {
+  ...
+});
+ +

This is an event listener, which listens for the browser's "DOMContentLoaded" event, which signifies that the HTML body is completely loaded and parsed. The JavaScript inside this block will not run until after that event is fired, therefore the error is avoided (you'll learn about events later in the course).

+ +

In the external example, we use a more modern JavaScript feature to solve the problem, the async attribute, which tells the browser to continue downloading the HTML content once the <script> tag element has been reached.

+ +
<script src="script.js" async></script>
+ +

In this case both the script and the HTML will load simultaneously and the code will work.

+ +
+

Note: In the external case, we did not need to use the DOMContentLoaded event because the async attribute solved the problem for us. We didn't use the async solution for the internal JavaScript example because async only works for external scripts.

+
+ +

And old-fashioned solution to this problem used to be to put your script element right at the bottom of the body (e.g. just before the </body> tag), so that it would load after all the HTML has been parsed. The problem with this solution (and the DOMContentLoaded solution seen above) is that loading/parsing of the script is completely blocked until the HTML DOM has been loaded. On larger sites with lots of JavaScript, this can cause a major performance issue, slowing down your site. This is why async was added to browsers!

+ +

async and defer

+ +

There are actually two ways we can bypass the problem of the blocking script — async and defer. Let's look at the difference between these two.

+ +

Async scripts will download the script without blocking rendering the page and will execute it as soon as the script finishes downloading. You get no guarantee that scripts will run in any specific order, only that they will not stop the rest of the page from displaying. It is best to use async when the scripts in the page run independently from each other and depend on no other script on the page.

+ +

For example, if you have the following script elements:

+ +
<script async src="js/vendor/jquery.js"></script>
+
+<script async src="js/script2.js"></script>
+
+<script async src="js/script3.js"></script>
+ +

You can't rely on the order the scripts will load in. jquery.js may load before or after script2.js and script3.js and if this is the case, any functions in those scripts depending on jquery will produce an error because jquery will not be defined at the time the script runs.

+ +

Defer will run the scripts in the order they appear in the page and execute them as soon as the script and content are downloaded:

+ +
<script defer src="js/vendor/jquery.js"></script>
+
+<script defer src="js/script2.js"></script>
+
+<script defer src="js/script3.js"></script>
+ +

All the scripts with the defer attribute will load in the order they appear on the page. So in the second example, we can be sure that jquery.js will load before script2.js and script3.js and that script2.js will load before script3.js.

+ +

To summarize:

+ + + +

Comments

+ +

As with HTML and CSS, it is possible to write comments into your JavaScript code that will be ignored by the browser, and exist simply to provide instructions to your fellow developers on how the code works (and you, if you come back to your code after six months and can't remember what you did). Comments are very useful, and you should use them often, particularly for larger applications. There are two types:

+ + + +

So for example, we could annotate our last demo's JavaScript with comments like so:

+ +
// Function: creates a new paragraph and append it to the bottom of the HTML body.
+
+function createParagraph() {
+  var para = document.createElement('p');
+  para.textContent = 'You clicked the button!';
+  document.body.appendChild(para);
+}
+
+/*
+  1. Get references to all the buttons on the page and sort them in an array.
+  2. Loop through all the buttons and add a click event listener to each one.
+
+  When any button is pressed, the createParagraph() function will be run.
+*/
+
+var buttons = document.querySelectorAll('button');
+
+for (var i = 0; i < buttons.length ; i++) {
+  buttons[i].addEventListener('click', createParagraph);
+}
+ +

Summary

+ +

So there you go, your first step into the world of JavaScript. We've begun with just theory, to start getting you used to why you'd use JavaScript and what kind of things you can do with it. Along the way, you saw a few code examples and learned how JavaScript fits in with the rest of the code on your website, amongst other things.

+ +

JavaScript may seem a bit daunting right now, but don't worry — in this course, we will take you through it in simple steps that will make sense going forward. In the next article, we will plunge straight into the practical, getting you to jump straight in and build your own JavaScript examples.

+ + + +

{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}

+ +

In this module

+ + diff --git a/files/id/learn/javascript/index.html b/files/id/learn/javascript/index.html new file mode 100644 index 0000000000..bdcf5aeedb --- /dev/null +++ b/files/id/learn/javascript/index.html @@ -0,0 +1,57 @@ +--- +title: JavaScript +slug: Learn/JavaScript +tags: + - JavaScript + - JavaScript Pemula + - Landing + - Module + - Pemula +translation_of: Learn/JavaScript +--- +
{{LearnSidebar}}
+ +

{{Glossary("JavaScript")}} adalah bahasa pemrograman yang memungkinkan anda mengimplementasikan hal kompleks di halaman web — setiap halaman web tidak hanya berdiam disana dengan menampilkan informasi statis untuk anda lihat — menampilkan update setiap waktu, peta interaktif, animasi grafis 2D/3D, scrolling video jukeboxes, dll. — anda bisa memastikan bahwa disanalah JavaScript terlibat.

+ +

Jalur Belajar

+ +

JavaScript dapat dikatakan sulit untuk dipelajari dibandingkan teknologi terkait seperti HTML dan CSS. Sebelum mencoba belajar JavaScript, disarankan anda telah mengetahui setidaknya kedua teknologi tersebut, dan mungkin yang lain juga. Mulailah dengan modul belajar berikut:

+ + + +

Memiliki pengalaman bahasa pemrograman lain juga bisa sangat membantu anda memahami Javascript.

+ +

Setelah mengetahui dasar javascript , anda bisa belajar topik yang lebih lanjut, seperti:

+ + + +

Modul Belajar

+ +

Pada topik ini berisi modul berikut, dengan urutan yang disarankan untuk belajar.

+ +
+
Dasar JavaScript
+
Pada modul pertama ini, kita akan menjawab beberapa pertanyaan fundamental seperti  "apa itu JavaScript?", "seperti apa itu javascript?", dan "untuk apa?", sebelum melanjukan untuk menuntun anda berlatih menulis javascript untuk pertama kali. Setelah itu, kita akan mendiskusikan beberapa kunci fitur Javascript secara detail, seperti variabel, strings, number dan array.
+
Block Pembangun JavaScript
+
Pada modul ini, kita melanjutkan memperluas cakupan pada semua kunci fitur fundamental Javascript, beralih pada tipe kode block yang umum digunakan seperti pernyataan kondisional, perulangan, fungsi, dan event. Anda tentu telah melihatnya di pembelajaran, tapi hanya sepintas — disini kita akan mendiskusikannya dengan lebih eksplisit.
+
Mengenal Objek JavaScript
+
Di JavaScript, kebanyakan diantaranya adalah objek, dari fitur inti javascript seperti string dan array sampai pada API browser dibangun diatas JavaScript. Anda juga bisa membuat objek anda sendiri untuk merangkum fungsi dan variabel terkait menjadi paket yang lebih efisien. Sifat orientasi objek dari javascript sangat penting untuk dipahami jika anda ingin meningkatkan pengetahuan pada bahasa dan menulis kode yang lebih efisien, karena itu disini kami telah menyediakan modul ini untuk membantu anda. Disini kita belajar teori objek dan sintak secara detail, melihat bagaimana anda bisa membuat objek anda sendiri, dan menjelaskan apa itu data JSON dan bagaimana menggunakannya.
+
Client-side web API
+
Ketika menulis client-side JavaScript untuk Website atau aplikasi, anda tidak akan lebih jauh sebelum memulai menggunakan API — antarmuka untuk memanipulasi aspek berbeda dari browser dan sistem operasi dimana situs berjalan, atau bahkan data dari website lain atau services. Pada modul ini kita akan membahas apa itu API, dan bagaimana menggunakan API yang umum digunakan pada pembangunan kode anda. 
+
+ +

Lihat Juga

+ +
+
JavaScript di MDN
+
Poin utama untuk inti dokumentasi Javascript di MDN — dimana anda mencari referensi yang luas pada semua aspek dari dan beberapa tutorial lanjutan untuk mendalami pengalaman menggunakan Javascript.
+
Coding math
+
Seri terbaik dari tutorial video untuk anda belajar matematika yang perlu dipahami untuk menjadi programer yang lebih efektif, oleh Keith Peters.
+
diff --git a/files/id/learn/javascript/objects/dasar-dasar/index.html b/files/id/learn/javascript/objects/dasar-dasar/index.html new file mode 100644 index 0000000000..6c273b51a3 --- /dev/null +++ b/files/id/learn/javascript/objects/dasar-dasar/index.html @@ -0,0 +1,261 @@ +--- +title: Dasar-dasar Objek JavaScript object +slug: Learn/JavaScript/Objects/Dasar-dasar +translation_of: Learn/JavaScript/Objects/Basics +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}
+ +

Pada artikel ini, kita akan melihat beberapa hal mendasar dalam sintaks Javascript Objek dan meninjau kembali beberapa fitur JavaScript yang telah kita bahas pada bab sebelumnya .

+ + + + + + + + + + + + +
Prasyarat:Mengetahui dasar komputer literasi, memahami tentang dasar HTML dan CSS, memahami dasar javascript (lihat First steps dan Building blocks).
Tujuan:Untuk memahami teori dasar tentang pemrograman berbasis objek, dan bagaimana hubungannya dengan Javascript dan bagaimana memulai bekerja menggunakan JavaScript objects.
+ +

Dasar Objek

+ +

Objek adalah kumpulan data yang saling berkaitan secara data maupun fungsionalitas (yang terdiri dari beberapa variabel dan fungsi yang disebut properti (properties) dan metode (method) ketika digunakan dalam objek). 

+ +

Untuk memulainya, silakan salin file oojs.html, yang berisi tentang contoh kecil dari apa yang kita bahas. Kita akan menggunakan file ini sebagai dasar untuk mempelajari sintaks objek dasar. Saat  mempelajarinya anda harus memiliki developer tools JavaScript console.

+ +

Seperti banyak hal dalam JavaScript, membuat objek dimulai dengan mendefinisikan dan menginisialisasi beberapa variabel. Coba anda gunakan baris kode berikut pada kode JavaScript yang sudah ada dalam file, simpan lalu refresh:

+ +
const person = {};
+ +

Now open your browser's JavaScript console, enter person into it, and press Enter/Return. You should get a result similar to one of the below lines:

+ +
[object Object]
+Object { }
+{ }
+
+ +

Congratulations, you've just created your first object. Job done! But this is an empty object, so we can't really do much with it. Let's update the JavaScript object in our file to look like this:

+ +
const person = {
+  name: ['Bob', 'Smith'],
+  age: 32,
+  gender: 'male',
+  interests: ['music', 'skiing'],
+  bio: function() {
+    alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
+  },
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name[0] + '.');
+  }
+};
+
+ +

After saving and refreshing, try entering some of the following into the JavaScript console on your browser devtools:

+ +
person.name
+person.name[0]
+person.age
+person.interests[1]
+person.bio()
+person.greeting()
+ +

You have now got some data and functionality inside your object, and are now able to access them with some nice simple syntax!

+ +
+

Note: If you are having trouble getting this to work, try comparing your code against our version — see oojs-finished.html (also see it running live). The live version will give you a blank screen, but that's OK — again, open your devtools and try typing in the above commands to see the object structure.

+
+ +

So what is going on here? Well, an object is made up of multiple members, each of which has a name (e.g. name and age above), and a value (e.g. ['Bob', 'Smith'] and 32). Each name/value pair must be separated by a comma, and the name and value in each case are separated by a colon. The syntax always follows this pattern:

+ +
const objectName = {
+  member1Name: member1Value,
+  member2Name: member2Value,
+  member3Name: member3Value
+};
+ +

The value of an object member can be pretty much anything — in our person object we've got a string, a number, two arrays, and two functions. The first four items are data items, and are referred to as the object's properties. The last two items are functions that allow the object to do something with that data, and are referred to as the object's methods.

+ +

An object like this is referred to as an object literal — we've literally written out the object contents as we've come to create it. This is in contrast to objects instantiated from classes, which we'll look at later on.

+ +

It is very common to create an object using an object literal when you want to transfer a series of structured, related data items in some manner, for example sending a request to the server to be put into a database. Sending a single object is much more efficient than sending several items individually, and it is easier to work with than an array, when you want to identify individual items by name.

+ +

Dot notation

+ +

Above, you accessed the object's properties and methods using dot notation. The object name (person) acts as the namespace — it must be entered first to access anything encapsulated inside the object. Next you write a dot, then the item you want to access — this can be the name of a simple property, an item of an array property, or a call to one of the object's methods, for example:

+ +
person.age
+person.interests[1]
+person.bio()
+ +

Sub-namespaces

+ +

It is even possible to make the value of an object member another object. For example, try changing the name member from

+ +
name: ['Bob', 'Smith'],
+ +

to

+ +
name : {
+  first: 'Bob',
+  last: 'Smith'
+},
+ +

Here we are effectively creating a sub-namespace. This sounds complex, but really it's not — to access these items you just need to chain the extra step onto the end with another dot. Try these in the JS console:

+ +
person.name.first
+person.name.last
+ +

Important: At this point you'll also need to go through your method code and change any instances of

+ +
name[0]
+name[1]
+ +

to

+ +
name.first
+name.last
+ +

Otherwise your methods will no longer work.

+ +

Bracket notation

+ +

There is another way to access object properties — using bracket notation. Instead of using these:

+ +
person.age
+person.name.first
+ +

You can use

+ +
person['age']
+person['name']['first']
+ +

This looks very similar to how you access the items in an array, and it is basically the same thing — instead of using an index number to select an item, you are using the name associated with each member's value. It is no wonder that objects are sometimes called associative arrays — they map strings to values in the same way that arrays map numbers to values.

+ +

Setting object members

+ +

So far we've only looked at retrieving (or getting) object members — you can also set (update) the value of object members by simply declaring the member you want to set (using dot or bracket notation), like this:

+ +
person.age = 45;
+person['name']['last'] = 'Cratchit';
+ +

Try entering the above lines, and then getting the members again to see how they've changed, like so:

+ +
person.age
+person['name']['last']
+ +

Setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely new members. Try these in the JS console:

+ +
person['eyes'] = 'hazel';
+person.farewell = function() { alert("Bye everybody!"); }
+ +

You can now test out your new members:

+ +
person['eyes']
+person.farewell()
+ +

One useful aspect of bracket notation is that it can be used to set not only member values dynamically, but member names too. Let's say we wanted users to be able to store custom value types in their people data, by typing the member name and value into two text inputs. We could get those values like this:

+ +
let myDataName = nameInput.value;
+let myDataValue = nameValue.value;
+ +

We could then add this new member name and value to the person object like this:

+ +
person[myDataName] = myDataValue;
+ +

To test this, try adding the following lines into your code, just below the closing curly brace of the person object:

+ +
let myDataName = 'height';
+let myDataValue = '1.75m';
+person[myDataName] = myDataValue;
+ +

Now try saving and refreshing, and entering the following into your text input:

+ +
person.height
+ +

Adding a property to an object using the method above isn't possible with dot notation, which can only accept a literal member name, not a variable value pointing to a name.

+ +

What is "this"?

+ +

You may have noticed something slightly strange in our methods. Look at this one for example:

+ +
greeting: function() {
+  alert('Hi! I\'m ' + this.name.first + '.');
+}
+ +

You are probably wondering what "this" is. The this keyword refers to the current object the code is being written inside — so in this case this is equivalent to person. So why not just write person instead? As you'll see in the Object-oriented JavaScript for beginners article, when we start creating constructors and so on, this is very useful — it always ensures that the correct values are used when a member's context changes (for example, two different person object instances may have different names, but we want to use their own name when saying their greeting).

+ +

Let's illustrate what we mean with a simplified pair of person objects:

+ +
const person1 = {
+  name: 'Chris',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+
+const person2 = {
+  name: 'Deepti',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+ +

In this case, person1.greeting() outputs "Hi! I'm Chris."; person2.greeting() on the other hand outputs "Hi! I'm Deepti.", even though the method's code is exactly the same in each case. As we said earlier, this is equal to the object the code is inside — this isn't hugely useful when you are writing out object literals by hand, but it really comes into its own when you are dynamically generating objects (for example using constructors). It will all become clearer later on.

+ +

You've been using objects all along

+ +

As you've been going through these examples, you have probably been thinking that the dot notation you've been using is very familiar. That's because you've been using it throughout the course! Every time we've been working through an example that uses a built-in browser API or JavaScript object, we've been using objects, because such features are built using exactly the same kind of object structures that we've been looking at here, albeit more complex ones than in our own basic custom examples.

+ +

So when you used string methods like:

+ +
myString.split(',');
+ +

You were using a method available on an instance of the String class. Every time you create a string in your code, that string is automatically created as an instance of String, and therefore has several common methods and properties available on it.

+ +

When you accessed the document object model using lines like this:

+ +
const myDiv = document.createElement('div');
+const myVideo = document.querySelector('video');
+ +

You were using methods available on an instance of the Document class. For each webpage loaded, an instance of Document is created, called document, which represents the entire page's structure, content, and other features such as its URL. Again, this means that it has several common methods and properties available on it.

+ +

The same is true of pretty much any other built-in object or API you've been using — Array, Math, and so on.

+ +

Note that built in objects and APIs don't always create object instances automatically. As an example, the Notifications API — which allows modern browsers to fire system notifications — requires you to instantiate a new object instance using the constructor for each notification you want to fire. Try entering the following into your JavaScript console:

+ +
const myNotification = new Notification('Hello!');
+ +

Again, we'll look at constructors in a later article.

+ +
+

Note: It is useful to think about the way objects communicate as message passing — when an object needs another object to perform some kind of action often it sends a message to another object via one of its methods, and waits for a response, which we know as a return value.

+
+ +

Test your skills!

+ +

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Object basics.

+ +

Summary

+ +

Congratulations, you've reached the end of our first JS objects article — you should now have a good idea of how to work with objects in JavaScript — including creating your own simple objects. You should also appreciate that objects are very useful as structures for storing related data and functionality — if you tried to keep track of all the properties and methods in our person object as separate variables and functions, it would be inefficient and frustrating, and we'd run the risk of clashing with other variables and functions that have the same names. Objects let us keep the information safely locked away in their own package, out of harm's way.

+ +

In the next article we'll start to look at object-oriented programming (OOP) theory, and how such techniques can be used in JavaScript.

+ +

{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}

+ +

In this module

+ + diff --git a/files/id/learn/javascript/objects/index.html b/files/id/learn/javascript/objects/index.html new file mode 100644 index 0000000000..a1ddfe032a --- /dev/null +++ b/files/id/learn/javascript/objects/index.html @@ -0,0 +1,54 @@ +--- +title: Memperkenalkan objek JavaScript +slug: Learn/JavaScript/Objects +tags: + - Artikel + - Asesmen + - CodingScripting + - JavaScript + - Objek + - Panduan + - Pemula + - Tutorial + - belajar +translation_of: Learn/JavaScript/Objects +--- +
{{LearnSidebar}}
+ +

Dalam JavaScript, banyak hal adalah objek, dari fitur inti JavaScript seperti string dan array sampai API browser dibangun atas JavaScript. Kamu bahkan bisa membuat objek sendiri untuk membungkus function dan variabel yang berhubungan menjadi package yang efisien, dan bertindak sebagai wadah data praktis. Sifat JavaScript yang berorientasi object penting untuk dipahami jika kamu ingin melangkah lebih jauh dengan pengetahuanmu tentang bahasanya, oleh karena itu kami menyediakan modul ini untuk membantumu. Di sini kita mengajarkan teori objek dan syntax secara detil, lalu melihat bagaimana cara membuat objekmu sendiri.

+ +

Persyaratan

+ +

Sebelum mulai modul ini, kamu harus punya beberapa pemahaman dengan dasar-dasar dari modul Pengenalan HTML dan Pengenalan CSS sebelum mulai JavaScript.

+ +

Kamu juga harus punya pemahaman tentang JavaScript dasar sebelum melihat objek JavaScript secara detil. Sebelum mencoba modul ini, pahami dulu Langkah pertama JavaScript dan Blok bangunan JavaScript.

+ +
+

Catatan: Jika kamu bekerja di komputer /tablet /perangkat lain di mana kamu tiak punya kemampuan membuat file sendiri, kamu bisa mencoba (sebagian besar) contoh kode dalam program pengkodean online seperti JSBin atau Thimble.

+
+ +

Panduan

+ +
+
Dasar Objek
+
+

Dalam artikel pertama tentang objek JavaScript, kita akan melihat syntax dasar objek JavaScript dan meninjau kembali beberapa fitur JavaScript yang telah kita lihat sebelumnya, mengulangi fakta bahwa banyak fitur yang telah kamu hadapi sebelumnya, yang mana itu sebenarnya objek.

+
+
JavaScript berorientasi object untuk pemula
+
Dengan dasar-dasar yang sudah dilalui, kita sekarang akan fokus pada JavaScript berorientasi objek (OOJS) - artikel ini menyajikan pandangan dasar teori pemrograman berorientasi objek (OOP), kemudian membahas bagaimana JavaScript mengemulasikan kelas objek melalui fungsi konstruktor, dan cara membuat objek secara instan.
+
Prototipe objek
+
Prototipe adalah mekanisme di mana objek JavaScript mewarisi fitur satu sama lain, dan mereka bekerja secara berbeda dengan mekanisme pewarisan dalam bahasa pemrograman berorientasi objek klasik. Pada artikel ini kita mengeksplorasi perbedaan itu, menjelaskan bagaimana rantai prototipe bekerja, dan melihat bagaimana properti prototipe dapat digunakan untuk menambahkan metode pada konstruktor yang ada.
+
Pewarisan/Inheritance pada JavaScript
+
Dengan sebagian besar rincian OOJS sudah dijelaskan, artikel ini menunjukkan bagaimana membuat kelas objek "child" (konstructor) yang mewarisi fitur dari kelas "parent" mereka. Selain itu, kami menyajikan beberapa saran, kapan dan di mana kamu bisa menggunakan OOJS..
+
Bekerja dengan data JSON
+
JavaScript Object Notation (JSON) adalah format standar untuk mewakili data terstruktur sebagai objek JavaScript, yang biasanya digunakan untuk mewakili dan mentransmisi data di situs web (misalnya mengirimkan beberapa data dari server ke klien, sehingga dapat ditampilkan di laman web). Kamu akan sering menjumpainya, jadi dalam artikel ini, kami memberikan semua yang kamu butuhkan untuk bekerja dengan JSON menggunakan JavaScript, termasuk mengakses item data dalam objek JSON dan menulis JSONmu sendiri.
+
Latihan membangun objek
+
Pada artikel sebelumnya, kita melihat semua teori esensial dari objek JavaScript dan sintak secara detil, sehingga memberi dasar kokoh untuk mulai membangun. Di artikel ini, kita melakukan latihan praktik, memberimu beberapa latihan lagi dalam membangun objek JavaScript sendiri untuk menghasilkan sesuatu yang menyenangkan dan berwarna — beberapa bola pantul berwarna.
+
+ +

Asesmen

+ +
+
Menambahkan fitur pada demo bola pantul kita
+
Dalam asesmen ini, kamu diharapkan menggunakan demo bola pantul dari artikel sebelumnya sebagai titik awal, dan menambahkan beberapa fitur baru dan menarik.
+
diff --git a/files/id/learn/server-side/django/development_environment/index.html b/files/id/learn/server-side/django/development_environment/index.html new file mode 100644 index 0000000000..79cb6b884a --- /dev/null +++ b/files/id/learn/server-side/django/development_environment/index.html @@ -0,0 +1,423 @@ +--- +title: Setting up a Django development environment +slug: Learn/Server-side/Django/development_environment +translation_of: Learn/Server-side/Django/development_environment +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/Introduction", "Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django")}}
+ +

Sekarang setelah Anda tahu apa gunanya Django, kami akan menunjukkan kepada Anda cara mengatur dan menguji lingkungan pengembangan Django di Windows, Linux (Ubuntu), dan macOS - sistem operasi apa pun yang Anda gunakan, artikel ini akan memberi Anda apa yang Anda butuhkan untuk dapat mulai mengembangkan aplikasi Django.

+ + + + + + + + + + + + +
Prerequisites:Pengetahuan dasar tentang penggunaan terminal / baris perintah dan cara menginstal paket perangkat lunak pada sistem operasi komputer pengembangan Anda.
Objective:Untuk memiliki lingkungan pengembangan untuk Django (2.0) yang berjalan di komputer Anda.
+ +

Gambaran lingkungan pengembangan Django

+ +

Django membuatnya sangat mudah untuk mengatur komputer Anda sendiri sehingga Anda dapat mulai mengembangkan aplikasi web. Bagian ini menjelaskan apa yang Anda dapatkan dengan lingkungan pengembangan, dan memberikan gambaran umum dari beberapa opsi pengaturan dan konfigurasi Anda. Sisa dari artikel ini menjelaskan metode yang disarankan untuk menginstal lingkungan pengembangan Django di Ubuntu, macOS, dan Windows, dan bagaimana Anda dapat mengujinya.

+ +

Apa itu Django development environment?

+ +

The development environment  adalah instalasi Django di komputer lokal Anda yang dapat Anda gunakan untuk mengembangkan dan menguji aplikasi Django sebelum menyebarkannya ke lingkungan produksi.

+ +

Alat utama yang disediakan Django sendiri adalah seperangkat skrip Python untuk membuat dan bekerja dengan proyek Django, bersama dengan server web pengembangan sederhana yang dapat Anda gunakan untuk menguji lokal (yaitu pada komputer Anda, bukan pada server web eksternal) Aplikasi web Django di browser web komputer Anda.

+ +

Ada alat periferal lain, yang merupakan bagian dari lingkungan pengembangan, yang tidak akan kita bahas di sini. Ini termasuk hal-hal seperti editor teks atau IDE untuk mengedit kode, dan alat manajemen kontrol sumber seperti Git untuk mengelola berbagai versi kode Anda dengan aman. Kami berasumsi bahwa Anda telah menginstal editor teks.

+ +

Apa saja opsi pengaturan Django?

+ +

Django sangat fleksibel dalam hal bagaimana dan di mana ia dapat diinstal dan dikonfigurasi. Django dapat:

+ + + +

Masing-masing opsi ini memerlukan konfigurasi dan pengaturan yang sedikit berbeda. Subbagian berikut menjelaskan beberapa pilihan Anda. Untuk sisa artikel ini, kami akan menunjukkan kepada Anda cara mengatur Django pada sejumlah kecil sistem operasi, dan pengaturan itu akan diasumsikan sepanjang sisa modul ini.

+ +
+

Catatan: Opsi instalasi lain yang mungkin dicakup dalam dokumentasi resmi Django. Kami menautkan ke appropriate documents below.

+
+ +

Sistem operasi apa yang didukung?

+ +

Aplikasi web Django dapat dijalankan di hampir semua mesin yang dapat menjalankan bahasa pemrograman Python 3: Windows, macOS, Linux / Unix, Solaris, dan lain-lain. Hampir semua komputer harus memiliki kinerja yang diperlukan untuk menjalankan Django selama pengembangan.

+ +

In this article, we'll provide instructions for Windows, macOS, and Linux/Unix.

+ +

Versi Python apa yang harus digunakan?

+ +

Kami menyarankan Anda menggunakan versi terbaru yang tersedia - pada saat penulisan ini adalah Python 3.8.2.

+ +

Python 3.5 or later can be used if needed (Python 3.5 support will be dropped in future releases).

+ +
+

Catatan: Python 2.7 tidak dapat digunakan dengan rilis Django saat ini (The Django 1.11.x series adalah yang terakhir untuk mendukung Python 2.7).

+
+ +

Di mana kita bisa mengunduh Django?

+ +

Ada tiga tempat untuk mengunduh Django:

+ + + +

Artikel ini menunjukkan cara menginstal Django dari PyPi, untuk mendapatkan versi stabil terbaru.

+ +

Database yang mana?

+ +

Django mendukung empat database utama (PostgreSQL, MySQL, Oracle, dan SQLite), dan ada perpustakaan komunitas yang menyediakan berbagai tingkat dukungan untuk database SQL dan NoSQL populer lainnya. Kami menyarankan Anda memilih database yang sama untuk produksi dan pengembangan (meskipun Django mengabstraksikan banyak perbedaan database menggunakan Object-Relational Mapper (ORM), there are still potential issues that are better to avoid).

+ +

Untuk artikel ini (dan sebagian besar modul ini) kita akan menggunakan database SQLite, yang menyimpan datanya dalam file. SQLite dimaksudkan untuk digunakan sebagai basis data yang ringan dan tidak dapat mendukung konkurensi tingkat tinggi. Namun, ini adalah pilihan yang sangat baik untuk aplikasi yang hanya bersifat baca-saja.

+ +
+

Catatan: Django dikonfigurasi untuk menggunakan SQLite secara default ketika Anda memulai proyek situs web Anda menggunakan alat standar (django-admin). Ini adalah pilihan yang bagus ketika Anda memulai karena tidak memerlukan konfigurasi atau pengaturan tambahan.

+
+ +

Menginstal seluruh sistem atau dalam lingkungan virtual Python?

+ +

Ketika Anda menginstal Python3 Anda mendapatkan lingkungan global tunggal yang dibagikan oleh semua kode Python3. Meskipun Anda dapat menginstal paket Python apa pun yang Anda suka di lingkungan, Anda hanya dapat menginstal satu versi tertentu dari setiap paket pada suatu waktu.

+ +
+

Catatan: Aplikasi python yang diinstal ke dalam lingkungan global berpotensi dapat saling bertentangan (mis. Jika mereka bergantung pada versi berbeda dari paket yang sama).

+
+ +

Jika Anda menginstal Django ke lingkungan default / global maka Anda hanya akan dapat menargetkan satu versi Django di komputer. Ini bisa menjadi masalah jika Anda ingin membuat situs web baru (menggunakan Django versi terbaru) sambil tetap mempertahankan situs web yang bergantung pada versi yang lebih lama.

+ +

Akibatnya, pengembang Python / Django berpengalaman biasanya menjalankan aplikasi Python dalam lingkungan virtual Python independen. Ini memungkinkan beberapa lingkungan Django berbeda di satu komputer. Tim pengembang Django sendiri merekomendasikan agar Anda menggunakan lingkungan virtual Python!

+ +

Modul ini mengasumsikan bahwa Anda telah menginstal Django ke lingkungan virtual, dan kami akan menunjukkan caranya di bawah ini.

+ +

Memasang Python 3

+ +

Untuk menggunakan Django Anda harus menginstal Python di sistem operasi Anda. Jika anda menggunakan Python 3 maka anda juga akan memerlukan Python Package Index tool — pip3 — yang digunakan untuk mengelola (menginstal, memperbarui, dan menghapus) paket / pustaka Python yang digunakan oleh Django dan aplikasi Python Anda yang lain.

+ +

Bagian ini menjelaskan secara singkat bagaimana Anda dapat memeriksa versi Python apa yang ada, dan menginstal versi baru sesuai kebutuhan, untuk Ubuntu Linux 18.04, macOS, dan Windows 10.

+ +
+

Note: Bergantung pada platform Anda, Anda mungkin juga dapat menginstal Python / pip dari manajer paket sistem operasi sendiri atau melalui mekanisme lain. Untuk sebagian besar platform, Anda dapat mengunduh file instalasi yang diperlukan dari https://www.python.org/downloads/ dan menginstalnya menggunakan metode spesifik platform yang sesuai.

+
+ +

Ubuntu 18.04

+ +

Ubuntu Linux 18.04 LTS sudah terdapat Python 3.6.6 secara default. Anda dapat melihatnya dengan menjalankan perintah berikut di bash terminal:

+ +
python3 -V
+ Python 3.6.6
+
+ +

Namun, alat Python Package Index yang akan dibutuhkan untuk dapat  memasang packages Python 3 (termasuk Django) tidak tersedia secara default. Jadi, Anda dapat memasang pip3 di bash terminal menggunakan:

+ +
sudo apt install python3-pip
+
+ +

macOS

+ +

macOS "El Capitan" dan versi terbaru yang lainnya tidak tersedia Python 3 didalamnya. Anda dapat melihatnya dengan menjalankan perintah di bash terminal:

+ +
python3 -V
+ -bash: python3: command not found
+ +

Anda dapat dengan mudah memasang Python 3 (bersamaan dengan pip3) di python.org:

+ +
    +
  1. Download installer yang dibutuhkan: +
      +
    1. Pergi ke https://www.python.org/downloads/
    2. +
    3. Pilih tombol Download Python 3.8.2 (versi minor yang tepat mungkin berbeda)
    4. +
    +
  2. +
  3. Cari file tersebut dengan menggunakan Finder, double-click file tersebut. Ikuti perintah pada proses instalasi.
  4. +
+ +

Sekarang Anda dapat mengonfirmasi keberhasilan instalasi dengan melihat versi Python 3 seperti yang ditunjukkan dibawah:

+ +
python3 -V
+ Python 3.8.2
+
+ +

Anda dapat pula mengecek bahwa pip3 sudah terpasang dengan melihat list packages yang tersedia:

+ +
pip3 list
+ +

Windows 10

+ +

Windows doesn't include Python by default, but you can easily install it (along with the pip3 tool) from python.org:

+ +
    +
  1. Download the required installer: +
      +
    1. Go to https://www.python.org/downloads/
    2. +
    3. Select the Download Python 3.8.2 button (the exact minor version number may differ).
    4. +
    +
  2. +
  3. Instal Python dengan mengklik dua kali pada file yang diunduh dan mengikuti petunjuk instalasi
  4. +
  5. Pastikan untuk menandai kotak yang berlabel "Add Python to PATH"Pastikan untuk menandai kotak yang berlabel
  6. +
+ +

You can then verify that Python 3 was installed by entering the following text into the command prompt:

+ +
py -3 -V
+ Python 3.8.2
+
+ +

The Windows installer incorporates pip3 (the Python package manager) by default. You can list installed packages as shown:

+ +
pip3 list
+
+ +
+

Note: Pemasang harus mengatur semua yang Anda butuhkan agar perintah di atas berfungsi. Namun jika Anda mendapatkan pesan bahwa Python tidak dapat ditemukan, Anda mungkin lupa menambahkannya ke jalur sistem Anda. Anda dapat melakukan ini dengan menjalankan penginstal lagi, memilih "Modify", dan centang kotak berlabel  "Add Python to environment variables" di halaman kedua.

+
+ +

Using Django inside a Python virtual environment

+ +

Perpustakaan yang akan kami gunakan untuk membuat lingkungan virtual kami adalah virtualenvwrapper (Linux and macOS) dan virtualenvwrapper-win (Windows), yang pada gilirannya keduanya menggunakan alat virtualenv. The wrapper tools menciptakan antarmuka yang konsisten untuk mengelola antarmuka di semua platform.

+ +

Menginstal perangkat lunak lingkungan virtual

+ +

Ubuntu virtual environment setup

+ +

Setelah menginstal Python dan pip Anda dapat menginstal virtualenvwrapper (which includes virtualenv). Panduan instalasi resmi dapat ditemukan here, atau ikuti instruksi di bawah ini.

+ +

Install the tool using pip3:

+ +
sudo pip3 install virtualenvwrapper
+ +

Kemudian tambahkan baris berikut di akhir file startup shell Anda (ini adalah nama file tersembunyi .bashrc di direktori home Anda). Ini mengatur lokasi di mana lingkungan virtual seharusnya hidup, lokasi direktori proyek pengembangan Anda, dan lokasi skrip yang diinstal dengan paket ini:

+ +
export WORKON_HOME=$HOME/.virtualenvs
+export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
+export VIRTUALENVWRAPPER_VIRTUALENV_ARGS=' -p /usr/bin/python3 '
+export PROJECT_HOME=$HOME/Devel
+source /usr/local/bin/virtualenvwrapper.sh
+
+ +
+

Note: The VIRTUALENVWRAPPER_PYTHON and VIRTUALENVWRAPPER_VIRTUALENV_ARGS variables point to the normal installation location for Python3, and source /usr/local/bin/virtualenvwrapper.sh points to the normal location of the virtualenvwrapper.sh script. If the virtualenv doesn't work when you test it, one thing to check is that Python and the script are in the expected location (and then change the startup file appropriately).
+
+ You can find the correct locations for your system using the commands which virtualenvwrapper.sh and which python3.

+
+ +

Kemudian muat ulang file startup dengan menjalankan perintah berikut di terminal:

+ +
source ~/.bashrc
+ +

Pada titik ini Anda akan melihat banyak skrip dijalankan seperti yang ditunjukkan di bawah ini:

+ +
virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/premkproject
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postmkproject
+...
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/preactivate
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postactivate
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/get_env_details
+
+ +

Sekarang Anda dapat membuat lingkungan virtual baru dengan perintah mkvirtualenv .

+ +

macOS virtual environment setup

+ +

Pengaturan virtualenvwrapper pada macOS hampir persis sama dengan di Ubuntu (sekali lagi, Anda dapat mengikuti instruksi dari official installation guide atau di bawah). 

+ +

Install virtualenvwrapper (and bundling virtualenv) using pip as shown.

+ +
sudo pip3 install virtualenvwrapper
+ +

Then add the following lines to the end of your shell startup file.

+ +
export WORKON_HOME=$HOME/.virtualenvs
+export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
+export PROJECT_HOME=$HOME/Devel
+source /usr/local/bin/virtualenvwrapper.sh
+ +
+

Note: The VIRTUALENVWRAPPER_PYTHON variable points to the normal installation location for Python3, and source /usr/local/bin/virtualenvwrapper.sh points to the normal location of the virtualenvwrapper.sh script. If the virtualenv doesn't work when you test it, one thing to check is that Python and the script are in the expected location (and then change the startup file appropriately).

+ +

For example, one installation test on macOS ended up with the following lines being necessary in the startup file:

+ +
export WORKON_HOME=$HOME/.virtualenvs
+export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
+export PROJECT_HOME=$HOME/Devel
+source /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh
+ +

You can find the correct locations for your system using the commands which virtualenvwrapper.sh and which python3.

+
+ +

These are the same lines as for Ubuntu, but the startup file is the differently named hidden file .bash_profile in your home directory.

+ +
+

Note: If you can't find .bash_profile to edit in the finder, you can also open this in the terminal using nano.

+ +

The commands look something like this:

+ +
cd ~  # Navigate to my home directory
+ls -la #List the content of the directory. YOu should see .bash_profile
+nano .bash_profile # Open the file in the nano text editor, within the terminal
+# Scroll to the end of the file, and copy in the lines above
+# Use Ctrl+X to exit nano, Choose Y to save the file.
+
+
+ +

Then reload the startup file by making the following call in the terminal:

+ +
source ~/.bash_profile
+ +

At this point, you may see a bunch of scripts being run (the same scripts as for the Ubuntu installation). You should now be able to create a new virtual environment with the mkvirtualenv command.

+ +

Windows 10 virtual environment setup

+ +

Installing virtualenvwrapper-win is even simpler than setting up virtualenvwrapper because you don't need to configure where the tool stores virtual environment information (there is a default value). All you need to do is run the following command in the command prompt:

+ +
pip3 install virtualenvwrapper-win
+ +

Now you can create a new virtual environment with the mkvirtualenv command

+ +

Creating a virtual environment

+ +

Setelah Anda menginstal virtualenvwrapper or virtualenvwrapper-win then working with virtual environments is very similar on all platforms.

+ +

Sekarang anda dapat membuat lingkungan baru dengan perintah mkvirtualenv .Saat perintah ini berjalan, Anda akan melihat lingkungan sedang disiapkan (apa yang Anda lihat sedikit platform-specific). Ketika perintah selesai lingkungan virtual baru akan aktif - Anda dapat melihat ini karena awal prompt akan menjadi nama lingkungan dalam tanda kurung (di bawah ini kami menunjukkan ini untuk Ubuntu, tetapi baris terakhir mirip untuk Windows / macOS) .

+ +
$ mkvirtualenv my_django_environment
+
+Running virtualenv with interpreter /usr/bin/python3
+...
+virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/t_env7/bin/get_env_details
+(my_django_environment) ubuntu@ubuntu:~$
+
+ +

Sekarang Anda berada di dalam lingkungan virtual Anda dapat menginstal Django dan mulai mengembangkan.

+ +
+

Catatan: Mulai sekarang dalam artikel ini (dan memang modul) asumsikan bahwa setiap perintah dijalankan dalam lingkungan virtual Python seperti yang kita atur di atas.

+
+ +

Menggunakan lingkungan virtual

+ +

Hanya ada beberapa perintah berguna lainnya yang harus Anda ketahui (ada lebih banyak dalam dokumentasi alat, tetapi ini adalah yang akan Anda gunakan secara teratur):

+ + + +

Installing Django

+ +

Setelah Anda membuat lingkungan virtual, dan memanggil workon untuk memasukkannya, kamu dapat menggunakan pip3 untuk menginstal Django. 

+ +
pip3 install django~=2.2
+ +

Anda dapat menguji bahwa Django diinstal dengan menjalankan perintah berikut (ini hanya menguji apakah Python dapat menemukan modul Django):Anda dapat menguji bahwa Django diinstal dengan menjalankan perintah berikut (ini hanya menguji apakah Python dapat menemukan modul Django):

+ +
# Linux/macOS
+python3 -m django --version
+ 2.2.12
+
+# Windows
+py -3 -m django --version
+ 2.2.12
+
+ +
+

Catatan: Jika perintah Windows di atas tidak menampilkan modul django, cobalah:

+ +
py -m django --version
+ +

Pada Windows, skrip Python 3 diluncurkan dengan mengawali perintah dengan py -3, meskipun ini dapat bervariasi tergantung pada instalasi spesifikasi anda. Coba hilangkan -3  jika anda menemukan masalah dengan perintah, Di Linux / macOS, perintahnya adalah python3.

+
+ +
+

Penting: Sisa modul ini menggunakan perintah Linux untuk menjalankan Python 3 (python3) . Jika anda bekerja pada Windows cukup ganti awalan ini dengan: py -3

+
+ +

Menguji instalasi Anda

+ +

Tes di atas berfungsi, tetapi tidak terlalu menyenangkan. Tes yang lebih menarik adalah membuat proyek kerangka dan melihatnya bekerja. Untuk melakukan ini, pertama-tama navigasikan di command prompt / terminal Anda ke tempat Anda ingin menyimpan aplikasi Django Anda. Buat folder untuk situs pengujian Anda dan navigasikan ke dalamnya.

+ +
mkdir django_test
+cd django_test
+
+ +

Anda kemudian dapat membuat situs kerangka baru bernama "mytestsite" menggunakan alat django-admin seperti yang ditunjukkan. Setelah membuat situs, Anda dapat menavigasi ke folder tempat Anda akan menemukan skrip utama untuk mengelola proyek, bernama manage.py.

+ +
django-admin startproject mytestsite
+cd mytestsite
+ +

Kita dapat menjalankan development web server dari dalam folder ini menggunakan manage.py dan perintah runserver , seperti yang ditunjukkan.

+ +
$ python3 manage.py runserver
+Performing system checks...
+
+System check identified no issues (0 silenced).
+
+You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
+Run 'python manage.py migrate' to apply them.
+
+December 16, 2018 - 07:06:30
+Django version 2.2.12, using settings 'mytestsite.settings'
+Starting development server at http://127.0.0.1:8000/
+Quit the server with CONTROL-C.
+
+ +
+

Catatan: Perintah di atas menunjukkan perintah Linux / macOS. Anda dapat mengabaikan peringatan tentang "15 migrasi yang belum diterapkan" pada titik ini!

+
+ +

Setelah server berjalan, Anda dapat melihat situs dengan menavigasi ke URL berikut di browser web lokal Anda:http://127.0.0.1:8000/. Anda akan melihat situs yang terlihat seperti ini:
+ Django Skeleton App Homepage - Django 2.0

+ + + +

Ringkasan

+ +

Anda sekarang memiliki lingkungan pengembangan Django dan berjalan di komputer Anda.

+ +

Di bagian pengujian Anda juga melihat secara singkat bagaimana kami dapat membuat situs web Django baru menggunakan django-admin startproject, dan jalankan di browser Anda menggunakan server web pengembangan (python3 manage.py runserver). Pada artikel selanjutnya, kami memperluas proses ini, membangun aplikasi web yang sederhana namun lengkap.

+ +

Lihat juga

+ + + +

{{PreviousMenuNext("Learn/Server-side/Django/Introduction", "Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django")}}

+ +

Dalam modul ini

+ + diff --git a/files/id/learn/server-side/django/index.html b/files/id/learn/server-side/django/index.html new file mode 100644 index 0000000000..c95aa6f162 --- /dev/null +++ b/files/id/learn/server-side/django/index.html @@ -0,0 +1,67 @@ +--- +title: Django Web Framework (Python) +slug: Learn/Server-side/Django +tags: + - CodingScripting + - Pemula + - Python + - Server-side programming + - belajar + - django +translation_of: Learn/Server-side/Django +--- +
{{LearnSidebar}}
+ +

Django merupakan sebuah web framework server-side yang sangat populer dan unggul. Modul ini menunjukan mengapa Django adalah salah satu web server frameworks yang paling populer, bagaimana mempersiapkan sebuah lingkungan pengembangan, dan bagaimana memulai menggunakan Django untuk membuat aplikasi web milik Anda.

+ +

Persyaratan

+ +

Sebelum memulai modul ini, Anda tidak perlu memiliki pengetahuan tentang Django. Anda perlu mengetahui apa itu server-side web programming dan web frameworks, idealnya dengan membaca topik di modul Server-side website programming first steps.

+ +

Pengetahuan umum tentang konsep pemrograman dan Python sangat direkomendasikan, tetapi tidak penting untuk memahami konsep inti.

+ +
+

Catatan: Python adalah salah satu bahasa pemrograman termudah bagi pemula untuk dibaca dan dimengerti. Disarankan, jika Anda ingin memahami modul ini dengan lebih baik maka ada banyak buku dan tutorial gratis yang tersedia di internet (programmers baru barangkali ingin memeriksa halaman Python untuk Non Programmers di wiki python.org).

+
+ +

Panduan

+ +
+
Pengenalan Django
+
Dalam artikel pertama Django kita menjawab pertanyaan "Apa itu Django?" dan memberi Anda sebuah gambaran tentang apa yang membuat web framework ini spesial. Kita akan menjelaskan mengenai fitur utama-nya, termasuk beberapa fungsi lanjutan yang tidak dapat kami bahas secara rinci dalam modul ini. Kita juga akan menunjukan Anda beberapa bagian utama aplikasi Django, untuk memberi gambaran tentang apa yang dapat dilakukan sebelum Anda memasangnya dan mulai bermain.
+
Menyiapkan lingkungan pengembangan Django
+
Sekarang Anda sudah tahu apa itu Django, Kita akan menunjukan Anda bagaimana untuk mempersiapkan dan menguji sebuah lingkungan pengembangan Django pada Windows, Linux (Ubuntu), dan Mac OS X -- apapun sistem operasi yang Anda gunakan, artikel ini akan memberi apa yang Anda inginkan untuk dapat mulai mengembangkan aplikasi Django.
+
Django Tutorial: Situs Perpustakaan Lokal
+
Artikel pertama dalam rangkaian tutorial praktis kami menjelaskan apa yang akan Anda pelajari, dan memberikan gambaran umum tentang "perpustakaan lokal", contoh situs yang akan Kita kerjakan dan kembangkan di artikel berikutnya.
+
Django Tutorial Part 2: Membuat kerangka website
+
Artikel ini menjelaskan bagaimana Anda dapat membuat sebuah "skeleton (kerangka)" website sebagai dasar, yang kemudian dapat Anda gunakan untuk diisi dengan pengaturan situs, urls, models, views, dan templates.
+
Django Tutorial Part 3: Menggunakan Models
+
Artikel ini menunjukan bagaimana untuk mendefinisikan models untuk website LocalLibrary — models mewakili sebuah struktur data yang ingin disimpan dalam data aplikasi kita, dan juga memperbolehkan Django untuk menyimpan data didalam sebuah database untuk kita(dan memodifikasinya nanti). Hal ini menjelaskan apa itu model, bagaimana hal itu di deklarasikan, dan beberapa jenis field (attribute suatu data) utama.Hal ini juga secara singkat menunjukkan beberapa cara utama untuk mengakses data model.
+
Django Tutorial Part 4: Django admin situs
+
Sekarang setelah kita membuat models untuk website LocalLibrary. Kita akan mengunakan situs Django Admin untuk menambahkan beberapa  data buku "sebenarnya". Pertama Kita akan menunjukkan Anda bagaimana cara mendaftarkan models dengan situs admin (admin site), lalu kita akan menunjukkan cara masuk dan membuat beberapa data. Pada akhirnya Kita menunjukkan beberapa cara untuk lebih meningkatkan penyajian situs admin.
+
Django Tutorial Part 5: Membuat home page Kita
+
Kita telah mengetahui bahwa untuk menambahkan sebuah kode untuk menampilkan halaman penuh pertama kita -- sebuah homepage untuk Locallibrary yang menunjukkan berapa banyak record yang Kita miliki dari masing-masing tipe model dan menyediakan link navigasi sidebar ke halaman Kita yang lain. Sepanjang jalan kita akan mendapatkan pengalaman praktek dalam menulis URL maps dan views, mendapatkan records dari sebuah database, dan menggunakan templates.
+
Django Tutorial Part 6: List umum dan detail views
+
Tutorial ini mengembangkan website Locallibrary Kita, menambahkan list dan detail untuk books dan authors. Di sini kita akan belajar tentang generic class-based views (sebuah tampilan berbasis class), dan menampilkan bagaimana mereka dapat mengurangi jumlah kode yang harus Anda tulis untuk kasus penggunaan umum. Kita juga akan membahas URL secara lebih rinci, menunjukkan bagaimana melakukan pencocokan pola dasar.
+
Django Tutorial Part 7: Sessions framework
+
Tutorial ini mengembangkan website LocalLibrary kita, menambahkan session-based visit-counter ke sebuah home page. Ini adalah contoh yang relatif sederhana, namun ini menunjukkan bagaimana Anda dapat menggunakan sesi framework untuk menyediakan perilaku konsisten bagi pengguna anonymous(anonim) di situs Anda sendiri.
+
Django Tutorial Part 8: User authentication and perizinan
+
Pada tutorial ini Kami akan menunjukan Anda bagaimana untuk memperbolehkan pengguna untuk masuk ke situs Anda dengan akun mereka, dan bagaimana mengatur apa yang dapat mereka lakukan dan melihat berdasarkan pada apakah mereka login dan perizinan mereka. Sebagai bagian dari demonstrasi ini, kita akan memperluas website LocalLibrary, menambahkan halaman masuk dan logout, dan halaman pengguna dan staf untuk melihat buku-buku yang telah dipinjam.
+
Django Tutorial Part 9: Bekerja dengan forms
+
Dalam tutorial ini Kami akan menunjukkan cara bekerja dengan HTML Forms di Django, dan khusunya cara termudah untuk menulis Forms untuk membuat, memperbaru, dan menghapus model Instances. Sebagai bagian dari demonstrasi ini, Kita akan memperluas website LocalLibrary sehingga pustakawan dapat memperbarui buku, dan membuat, memperbarui, dan menghapus penulis menggunakan formulir kita sendir(bukan menggunakan aplikasi admin).
+
Django Tutorial Part 10: Menguji aplikasi web Django
+
Seiring berkembangnya website mereka menjadi lebih sulit untuk dilakukan pengujian secara manual -- bukan hanya karena adanya lebih banyak tes, namun, karena interaksi antar komponen menjadi lebih kompleks, perubahan kecil di satu area dapat memerlukan banyak tes tambahan untuk memverifikasi pengaruhnya terhadap area lain. Salah satu cara untuk mengurangi masalah ini adalah dengan menulis tes secara otomatis, yang dapat dengan mudah dan handal dijalankan setiap kali Anda melakukan perubahan. Tutorial ini menunjukkan bagaimana mengotomatisasi pengujian unit dari situs Anda menggunakan Django's test framework.
+
Django Tutorial Part 11: Meluncurkan Django untuk produksi
+
Sekarang Anda telah membuat (dan menguji) website LocalLibrary yang hebat, Anda akan menginstallnya pada public web server sehingga bisa diakses oleh staf perpustakaan dan anggota melalui internet. Artikel ini memberikan gambaran umum tentang bagaimana Anda bisa menemukan host untuk menyebarkan situs web Anda, dan apa yang perlu Anda lakukan agar situs Anda siap masuk produksi.
+
Keamanan aplikasi web Django
+
Melindungi data pengguna merupakan bagian penting dari setiap desain situs web. Kita sebelumnya menjelaskan beberapa ancaman keamanan yang lebih umum dalam artikel Web security — artikel ini memberikan demonstrasi praktis tentang bagaimana perlindungan built-in (yang secara default terinstall) Django menangani ancaman tersebut.
+
+ +

Penilaian

+ +

Penilaian berikut akan menguji pemahaman Anda tentang bagaimana membuat situs web menggunakan Django, seperti yang dijelaskan dalam panduan yang tercantum di atas.

+ +
+
DIY Django mini blog
+
Dalam penilaian ini Anda akan menggunakan beberapa pengetahuan yang telah Anda pelajari dari modul ini untuk membuat blog Anda sendiri.
+
diff --git a/files/id/learn/server-side/django/tutorial_local_library_website/index.html b/files/id/learn/server-side/django/tutorial_local_library_website/index.html new file mode 100644 index 0000000000..21ed6a040e --- /dev/null +++ b/files/id/learn/server-side/django/tutorial_local_library_website/index.html @@ -0,0 +1,90 @@ +--- +title: 'Django Tutorial: The Local Library website' +slug: Learn/Server-side/Django/Tutorial_local_library_website +translation_of: Learn/Server-side/Django/Tutorial_local_library_website +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django")}}
+ +
Pada artikel pertama ini dalam seri latihan praktek menjelaskan apa yang akan Anda pelajari, dan menyediakan sebuah gambaran mengenai percobaan website "local library" Kita akan bekerja dan terus berkembang pada artikel-artikel selanjuntya.
+ + + + + + + + + + + + +
Prerequisites:Read the Django Introduction. For the following articles you'll also need to have set up a Django development environment
Objective:To introduce the example application used in this tutorial, and allow readers to understand what topics will be covered. 
+ +

Gambaran

+ +

Selamat datang di tutorial django MDN "Local Library", dimana kita akan mengembangakn sebuah website yang memungkinkan untuk mengatur sebuah katalog untuk perpustakaan lokal. 

+ +

Pada seri ini Anda akan:

+ + + +

Anda sudah belajar mengenai beberapa topik-topik yang akan dibahas. Pada akhir seri tutorial Anda seharusnya cukup tahu untuk mengembangkan aplikasi simple Django secara pribadi.

+ +

The LocalLibrary website

+ +

LocalLibrary is the name of the website that we'll create and evolve over the course of this series of tutorials. As you'd expect, the purpose of the website is to provide an online catalog for a small local library, where users can browse available books and manage their accounts.

+ +

This example has been carefully chosen because it can scale to show as much or as little detail as we need, and can be used to show off almost any Django feature. More importantly, it allows us to provide a guided path through the most important functionality in the Django web framework:

+ + + +

Even though this is a very extensible example, it's called LocalLibrary for a reason — we're hoping to show the minimum information that will help you get up and running with Django quickly. As a result we'll store information about books, copies of books, authors and other key information. We won't however be storing information about other items a library might store, or provide the infrastructure needed to support multiple library sites or other "big library" features. 

+ +

I'm stuck, where can I get the source?

+ +

As you work through the tutorial we'll provide the appropriate code snippets for you to copy and paste at each point, and there will be other code that we hope you'll extend yourself (with some guidance).

+ +

If you get stuck, you can find the fully developed version of the website on Github here.

+ +

Summary

+ +

Now that you know a bit more about the LocalLibrary website and what you're going to learn, it's time to start creating a skeleton project to contain our example.

+ +

{{PreviousMenuNext("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django")}}

+ +

In this module

+ + diff --git a/files/id/learn/server-side/first_steps/index.html b/files/id/learn/server-side/first_steps/index.html new file mode 100644 index 0000000000..b085099081 --- /dev/null +++ b/files/id/learn/server-side/first_steps/index.html @@ -0,0 +1,39 @@ +--- +title: Server-side website programming first steps +slug: Learn/Server-side/First_steps +translation_of: Learn/Server-side/First_steps +--- +
{{LearnSidebar}}
+ +

Pada module server-side ini, akan menjawab beberapa pertanyaan mendasar mengenai pemrograman server-side--, apa itu ?, apa bedanya dengan pemrograman client-side ?, kenapa pemmogrmaan ini sangat berguna. Kemudian akan diberikan penjelasan singkat dari beberapa framework pemrograman server-side populer, bersamaan dengan petunjuk bagaimana memilih framework yang paling cocok untuk website Anda. 

+ +

Prasyarat

+ +

Sebelum memulai modul ini, Anda tidak harus memiliki pengetahuan apapun mengenai pemgrograman server-side, atau jenis pemrograman lainnya.

+ +

Anda perlu untuk mengeti "bagaimana web bekerja". Kami sarankan Anda baca terlebih dahulu topik - topik berikut:

+ + + +

Dengan pemahaman dasar diatas, Anda akan siap untuk belajar dengan modul ini. 

+ +

Panduan

+ +
+
Pengenalan web server side
+
Welcome to the MDN beginner's server-side programming course! In this first article we look at Server-side programming  from a high level, answering questions such as "what is it?", "how does it differ from client-side programming?", and "why it is so useful?". After reading this article you'll understand the additional power available to websites through server-side coding.
+
Client-Server overview
+
Now that you know the purpose and potential benefits of server-side programming we're going to examine in detail what happens when a server receives a "dynamic request" from a browser. As most website server-side code handles requests and responses in similar ways, this will help you understand what you need to do when writing your own code.
+
Server-side web frameworks
+
The last article showed you what a server-side web application needs to do in order to respond to requests from a web browser. Now we show how web frameworks can simplify these tasks, and help you choose the right framework for your first server-side web application.
+
Website security
+
Website security requires vigilance in all aspects of website design and usage. This introductory article won't make you a website security guru, but it will help you understand the first important steps you can take to harden your web application against the most common threats.
+
+ +

Assessments

+ +

This "overview" module doesn't have any assessement because we haven't yet shown you any code.  We do hope at this point you have a good understanding of what sorts of functionality you can deliver using server-side programming and you have made a decision about what server-side web framework you will use to create your first website.

diff --git a/files/id/learn/server-side/index.html b/files/id/learn/server-side/index.html new file mode 100644 index 0000000000..b497257371 --- /dev/null +++ b/files/id/learn/server-side/index.html @@ -0,0 +1,59 @@ +--- +title: Server-side website programming +slug: Learn/Server-side +tags: + - Beginner + - CodingScripting + - Intro + - Landing + - Learn + - NeedsTranslation + - Server + - Server-side programming + - Topic + - TopicStub +translation_of: Learn/Server-side +--- +
{{LearnSidebar}}
+ +

The Dynamic Websites  Server-side programming topic is a series of modules that show how to create dynamic websites; websites that deliver customised information in response to HTTP requests. The modules provide a generic introduction to server-side programming, along with specific beginner-level guides on how to use the Django (Python) and Express (Node.js/JavaScript) web frameworks to create basic applications.

+ +

Most major websites use some kind of server-side technology to dynamically display different data as required. For example, imagine how many products are available on Amazon, and imagine how many posts have been written on Facebook? Displaying all of these using completely different static pages would be completely inefficient, so instead such sites display static templates (built using HTML, CSS, and JavaScript), and then dynamically update the data displayed inside those templates when needed, e.g. when you want to view a different product on Amazon.

+ +

In the modern world of web development, learning about server-side development is highly recommended.

+ +

Learning pathway

+ +

Getting started with server-side programming is usually easier than with client-side development, because dynamic websites tend to perform a lot of very similar operations (retrieving data from a database and displaying it in a page, validating user-entered data and saving it in a database, checking user permissions and logging users in, etc.), and are constructed using web frameworks that make these and other common web server operations easy.

+ +

A basic knowledge of programming concepts (or of a particular programming language) is useful, but not essential. Similarly, expertise in client-side coding is not required, but a basic knowledge will help you work better with the developers creating your client-side web "front end".

+ +

You will need to understand "how the web works". We recommend that you first read the following topics:

+ + + +

With that basic understanding you'll be ready to work your way through the modules in this section. 

+ +

Modules

+ +

This topic contains the following modules. You should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks . 

+ +
+
Server-side website programming first steps
+
This module provides server-technology-agnostic information about server-side website programming, including answers to fundamental questions about server-side programming — "what it is", "how it differs from client-side programming", and "why it is so useful" — and an overview of some of the more popular server-side web frameworks and guidance on how to select the most suitable for your site. Lastly we provide an introductory section on web server security.
+
Django Web Framework (Python)
+
Django is an extremely popular and fully featured server-side web framework, written in Python. The module explains why Django is such a good web server framework, how to set up a development environment and how to perform common tasks with it.
+
Express Web Framework (Node.js/JavaScript)
+
Express is a popular web framework, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.
+
+ +

See also

+ +
+
Node server without framework
+
This article provides a simple static file server built with pure Node.js, for those of you not wanting to use a framework.
+
diff --git a/files/id/learn/web_mechanics/index.html b/files/id/learn/web_mechanics/index.html new file mode 100644 index 0000000000..c1cb59bd12 --- /dev/null +++ b/files/id/learn/web_mechanics/index.html @@ -0,0 +1,29 @@ +--- +title: Mekanisme Web +slug: Learn/Web_Mechanics +tags: + - MekanismeWeb + - Pemula +translation_of: Learn/Common_questions +--- +

Kompetensi ini merepresentasikan pemahaman Anda mengenai ekosistem web. Kami pecah pengetahuan yang Anda butuhkan kedalam bentuk yang lebih kecil, yakni detil keahliannya.

+ +

{{NoteStart}}Mekanisme web berfokus pada sisi fungsional dari ekosistem web, bukan pada sisi teknis, dimana pembahasannya berada pada Infrastruktur.{{NoteEnd}}

+ +

Keahlian Dasar

+ +

Mulailah dari sini jika Anda belum akrab dengan web. Kami juga menyarankan Anda untuk mengunjungi ke halaman glosarium kami untuk bantuan dalam memahami berbagai jargon yang ada pada web.

+ +

{{ArticlesByTag({"tags":["WebMechanics","Beginner"]})}}

+ +

Keahlian Menengah

+ +

Jika Anda sudah pernah mengenal web, di sini ada beberapa detail yang dapat Anda pelajari lebih lanjut:

+ +

{{ArticlesByTag({"tags":["WebMechanics","Intermediate"]})}}

+ +

Keahlian Lanjutan

+ +

Jika Anda adalah seorang pembuat web yang berpengalaman, Anda mungkin tertarik untuk mempelajari keahlian yang luar biasa.

+ +

{{ArticlesByTag({"tags":["WebMechanics","Advanced"]})}}

diff --git a/files/id/mdn/about/index.html b/files/id/mdn/about/index.html new file mode 100644 index 0000000000..f220277d09 --- /dev/null +++ b/files/id/mdn/about/index.html @@ -0,0 +1,135 @@ +--- +title: About MDN Web Docs +slug: MDN/About +translation_of: MDN/About +--- +
{{MDNSidebar}}
+ +
{{IncludeSubNav("/en-US/docs/MDN")}}
+ +

MDN Web Docs (yang sebelumnya dikenal sebagai MDN — the Mozilla Developer Network) adalah sebuah platform pembelajaran untuk teknologi web dan perangkat lunak yang berbasis Web. termasuk: 

+ + + +

Misi Kami

+ +

Misi MDN sederhana: menyediakan pengembang informasi yang pengembang butuhkan untuk membangun proyek  open Web dengan mudah. Jika MDN adalah sebuah teknologi terbuka di Web, kita ingin mendokumentasikannya.

+ +

Kita juga menyediakan dokumentasi tentang Mozilla products dan cara build and contribute to Mozilla projects.

+ +

Jika kamu tidak yakin apakah sebuah artikel harus dibahas di MDN, baca Does this belong on MDN?

+ +

Cara kamu dapat membantu

+ +

Kamu tidak perlu menjadi seorang coder profesional atau penulis untuk membantu MDN! Kita mempunya banyak cara agar kamu dapat membantu, dari me-review artikel memastikan artikel tersebut masuk akal, kontribusi di tulisan, menambahkan contoh kode. Sebenarnya, ada banyak cara untuk membantu. Kami memiliki halaman Getting Started yang membantu kamu mengambil tugas untuk dikerjakan berdasarkan ketertarikanmu dan jumlah waktu yang kamu luangkan!.

+ +

Kamu juga dapat membantu dengan mempromosikan MDN pada blog atau website mu.

+ +

Komunitas MDN 

+ +

Komunitas kita bersifat global. Kami memiliki kontributor yang luar biasa di seluruh dunia yang bekerja dengan berbagai bahasa. Jika kamu suka untuk belajar lebih banyak tentang kita, atau kamu butuh bantuan MDN, cek discussion forum kami atau saluran IRC! Kamu juga dapat menetahui berita terbaru tentang kamu dengan me- follow akun Twitter,  @MozDevNet. Kamu juga dapat mengirimkan cuitan ke kami jika kau melihat sesuatu yang salah atau jika kamu suka memberikan masukkan (kami akan berterima kasih) pada penulis - penulis dan kontributor kami.

+ + + +

Menggunakan konten website dokumentasi MDN

+ +

Konten MDN tersedia gratis, dan berlisensi open source.

+ +

Hak cipta dan lisensi

+ +

Konten MDN semuanya tersedia dengan berbagai variasi lisensi open source. Pada bagian ini membahas tipe-tipe konten yang kami sediakan dan lisensi yang berefek di masing-masingnya.

+ +

Dokumentasi dan artikel

+ +

MDN wiki documents telah disiapkan oleh kontribusi-kontribusi penulis baik dari dalam maupun dari luar Mozilla Foundation. Kecuali diyatakan lain, konten tersedia dibawah syarat Creative Commons Attribution-ShareAlike license (CC-BY-SA), v2.5 atau versi selanjutnya. 

+ +

Ketika menggukan ulang konten MDN, kamu perlu memastikan 2 hal:

+ +
    +
  1. +

    Atribusi diberikan pada konten orisinil.

    + +

    Mohon atribut "Kontributor Mozilla" dan termasuk sebuah tautan (online) atau URL (cetak) ke halaman wiki khusus untuk sumber konten. Contoh, untuk menyediakan atribusi pada artikel ini, kamu dapat menulis:

    + +
    +

    About MDN oleh Mozilla Contributors dibawah lisensi CC-BY-SA 2.5.

    +
    + +

    Catat bahwa pada contoh, tautan "Mozilla Contributors" ke halaman official. liat Best practices for attribution untuk penjelasan lebih lanjut.

    +
  2. +
  3. +

    Penggunaan ulang di publikasikan dibawah lisensi yag sama dengan konten original—CC-BY-SA v2.5 atau versi selanjutnya.

    +
  4. +
+ +

Contoh kode dan bagian kecil

+ +

Contoh kode yang ditambahkan pada atau setelah 20 Agustus 2010 pada public domain (CC0). Tidak diperlukan pemberitahuan lisensi, tapi jika kamu butuh lisensi, kamu dapat menggunakan: "Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/".

+ +

Contoh kode yang ditambahkan pada wiki ini sebelum 20 Agustus 2010 tersedia dibawah lisensi MIT license; Kamu harus menambahkan informasi atribusi pada MIT template: "© <tanggal revisi halaman wiki> <nama orang yang memasukkan ke wiki>

+ +

Kamu dapat menentukan lisensi mana pada sebuah contoh kode yang tersedia dibawah history artikel. Untuk menampilkan history :

+ +
    +
  1. Klik tombol Edit in wiki pada header artikel.  Tombol ini membawa kamu pada artikel sama yang editable, wiki version of MDN Web Docs (tapi tidak benar-benar menempatkan artikel pada mode edit).  
  2. +
  3. Klik ikon berbentuk roda gigi pada header di artikel wiki, dan pilih History pada menu yang muncul.
  4. +
  5. Klik View All, dan lihat revisi terbaru yang ada sebelum 20 Agustus 2010 (jika ada) .
  6. +
  7. Klik stempel tanggal dari revisi untuk melihat revisi pada artikel dihari itu .
  8. +
+ +

Jika terdapat contoh revisi yang kamu pilih, kemudian revisi itu ditambahkan sebelum lisensi dirubah dan tersedia dibawah syarat lisensi MIT. Jika contoh kode tidak ada atau tidak ada revisi sebelum 20 Agustus 2010, kemudian revisi telah ditambahkan setelah berubah dan pada domain publik.

+ +

Kontribusi

+ +

Jika kamu berharap untuk berkontribusi pada wiki ini, kamu harus membuat dokumentasi tersedia dibawah lisensi Attribution-ShareAlike (atau ada kalanya sebuah lisensi alternatif yang secara khusus pada halaman yang kamu edit), dan contoh kode tersedia dibawah Creative Commons CC-0 (sebuah dedikasi Public Domain ). Menambahkan pada wiki ini berarti kamu setuju bahwa kontribusimu akan dibuat tersedia dibawah lisensi tersebut.

+ +

Beberapa konten lama yang telah dibuat dibawah sebuah lisensi lain dari pada lisensi yang telah dijelaskan diatas; Konten ini ditunjukkan pada bagian bawah disetiap halaman melalui sebuah Alternate License Block.

+ +
+

Tidak ada halaman baru yang mungkin dibuat menggunakan  alternate licenses.

+
+ +

Hak cipta untuk kontribusi materi tetap pada penulis kecuali penulis menetapkannya pada orang lain.

+ +

Jika kamu memiliki pertanyaan atau kepentingan tentang diskusi disini, mohon hubungi MDN administrators.

+ +

Logo, merek dagang, tanda layanan dan tanda kata.

+ +
+

Hak pada merek datang, logo, dan tanda layanan pada Mozilla Foundation, serta tampilan dan nuansa pada website, tidak berada dibawah lisensi Creative Commons, dan luasnya merupakan karya penulis (seperti logo dan desain grafis), mereka tidak termasuk pada karya yang dibawah lisensi pada persyaratan tersebut. Jika kamu menggunakan tulisan pada dokumen, dan berharap menggunakan hak ini, atau kamu punya pertanyaan-pertanyaan lain tentang mematuhi persyaratan lisensi pada koleksi ini. kamu harus menghubungi Mozilla Foundation disini: licensing@mozilla.org.

+ +

Menautkan MDN

+ +

Lihat artikel ini untuk pedoman linking to MDN untuk praktek terbaik ketika menautkan.

+ +

Mengunduh konten

+ +

Halaman tunggal

+ +

Kamu dapat menyalin konten dari halaman tunggal pada MDN dengan menambahkan URL parameters untuk menetapkan format yang kamu inginkan.

+ +

Alat Third-party

+ +

Kamu dapat meliat konten MDN melalui alat third-party seperti Dash (untuk macOS) dan Zeal (untuk Linux dan Windows).

+ +

Kapeli juga mempublikasikan offline MDN docs covering HTML, CSS, JavaScript, SVG, dan XSLT.

+ +

Melaporkan masalah pada Documen Web MDN

+ +

lihat How to report a problem on MDN.

+ +

Sejarah Dokumen Web MDN

+ +

MDN Web Docs (sebelumnya Mozilla Developer Network (MDN), sebelumnya Mozilla Developer Center (MDC), a.k.a. Devmo) proyek dimulai pada awal 2005, ketika Mozilla Foundation memperoleh sebuah lisensi dari AOL untuk menggunakan konten original Netscape DevEdge. Konten DevEdge merupakan konten yang masih sangat berguna yang kemudian di migrasi sukarelawan pada wiki ini sehingga konten ini menjadi mudah diperbarui dan dipelihara.

+ +

Nama telah dirubah menjadi MDN Web Docs pada Juni 2017. Lihat The Future of MDN: A Focus on Web Docs untuk alasan dibalik keputusan ini.

+ +

Kamu dapat mencari lebih banyak sejarah MDN pada halaman 10th anniversary celebration kami, termasuk sejarah lain oleh beberapa orang yang terlibat.

+ +

Tentang Mozilla

+ +

Kalau kamu ingin mempelajari lebih banyak tentang siapa kita, bagaimana menjadi bagian dari Mozilla atau sekedar tempat menemukan kita, kamu berada di tempat yang tepat. Untuk menemukan hal yang mendorong kami dan yang membuat kami berbeda, mohon kunjungi halaman mission kita.

diff --git a/files/id/mdn/contribute/feedback/index.html b/files/id/mdn/contribute/feedback/index.html new file mode 100644 index 0000000000..fc2958dc4f --- /dev/null +++ b/files/id/mdn/contribute/feedback/index.html @@ -0,0 +1,56 @@ +--- +title: 'Project:Tanggapan' +slug: MDN/Contribute/Feedback +tags: + - Dokumentasi + - MDN + - MDN Meta + - Panduan +translation_of: MDN/Contribute/Feedback +--- +
{{MDNSidebar}}
+ +

Selamat datang di Mozilla Developer Network! Jika kamu mempunyai masalah, atau ingin meminta saran, ini tempat yang tepat. Kenyataannya kamu tertarik mengirimkan tanggapan membuat anda semakin menjadi bagian dari komunitas Mozilla, dan kami berterima kasih atas ketertarikan kamu.

+ +

Kamu memiliki beberapa pilihan untuk menawarkan wawasan, artikel ini akan membantumu melakukannya.

+ +

Memperbarui dokumentasi

+ +

Pertama-tama, jika kamu melihat masalah dalam dokumentasi, kamu boleh mengkoreksinya sendiri. Masuk dengan Persona, tekan tombol biru Edit sehingga membuka editor dan masukan kata untuk berkontribusi pada dokumentasi MDN. Dokumentasi di sini adalah pengetahuan, dan dikumpulkan oleh team relawan dan staff yang dibayar, jadi jangan malu -- tata bahasa kamu tidak harus sempurna. Kami akan membersihkan jika kamu membuat kesalahan; tak ada salahnya untuk dilakukan!

+ +

Untuk informasi lebih lanjut tentang kontribusi untuk dokumentasi MDN, lihat:

+ + + +

Gabung dalam percakapan

+ +

Bicara pada kami! Ada beberapa cara untuk terhubung dengan orang lain yang bekerja dalam konten MDN.

+ +

Obrolan

+ +

Kami menggunakan Internet Relay Chat (IRC) untuk mendiskusikan MDN dan kontennya. Kamu dapat bergabung dalam percakapan! Kami mempunyai beberapa saluran, tergantung pada minat kamu:

+ +
+
Situs MDN (#mdn)
+
Saluran ini untuk diskusi umum MDN. Bila kamu tidak yakin dimana mendapatkan bantuan, atau masalah yang melibatakan kamu, kamu dapat bertanya di sini!
+
Situs dokumentasi pengembang (#mdndev)
+
Di saluran #mdndev ini kita membahas tentang pekerjaan pengembang platform yang berjalan pada situs MDN. Bila kamu memiliki masalah tentang fungsionalitas website, atau ide tentang fitur, kamu dapat bergabung dalam pembahasan ini.
+
+ +

(Asinkron) Diskusi

+ +

Diskusi jangka panjang terjadi di forum diskusi MDN kita. Kamu bisa posting ke forum via email ke mdn@mozilla-community.org. Jika kamu bergabung dengan forum, kamu dapat memilih untuk memiliki pemberitahuan tentang diskusi yang dikirimkan kepada kamu melalui email juga.

+ +

Laporkan masalah

+ +

Masalah dokumentasi

+ +

Bila kamu melihat masalah dalam dokumentasi dan tidak bisa memperbaikinya sendiri karena berbagai alasan, kamu dapat melaporkan masalah! Kamu dapat menggunakan formulir ini untuk semua masalah dokumentasi, apakah itu koreksi sederhana atau permintaan untuk sepotong konten yang sama sekali baru. Seperti disebutkan sebelumnya, kami mengundang anda untuk berkontribusi dengan melakukan perubahan sendiri, tetapi opsi pelaporan ini tersedia untuk kamu juga.

+ +

Masalah situs

+ +

Bila kamu mengalami masalah dengan situs web MDN, atau memiliki ide untuk fitur baru dalam situs ini, anda dapat mengajukan permintaan dalam sistem Bugzilla juga.

diff --git a/files/id/mdn/contribute/getting_started/index.html b/files/id/mdn/contribute/getting_started/index.html new file mode 100644 index 0000000000..04dd189549 --- /dev/null +++ b/files/id/mdn/contribute/getting_started/index.html @@ -0,0 +1,126 @@ +--- +title: Langkah Awal Di MDN +slug: MDN/Contribute/Getting_started +tags: + - Dokumentasi + - Langkah Awal + - MDN + - Panduan + - Proyek MDN +translation_of: MDN/Contribute/Getting_started +--- +
{{MDNSidebar}}
{{IncludeSubnav("/id/docs/MDN")}}
+ +

Kami adalah komunitas terbuka yang terdiri dari pengembang dan penulis sumber daya untuk Web yang lebih baik, terlepas dari merek, browser, atau perangkat. Siapa saja dapat memberikan kontribusinya dan mereka yang membuat kami semakin kuat. Bersama kita bisa melanjutkan untuk menggerakkan inovasi di Web untuk memberikan pelayanan yang lebih baik. Dimulai disini, dengan Anda.

+ +

Setiap bagian dari MDN (dokumen, demonstrasi, dan situs itu sendiri) dibuat oleh komunitas terbuka para pengembang sumber daya. Bergabunglah bersama kami!

+ +

3 langkah mudah untuk MDN

+ +

MDN adalah sebuah ensiklopedia, dimana semua orang bisa menambah dan mengedit konten. Anda tidak perlu menjadi seorang pemrogram atau mengetahui banyak hal mengenai teknologi. Ada beberapa tugas yang harus diselesaikan, mulai dari yang termudah (Mengoreksi bacaan and mengoreksi kesalahan penulisan) hingga yang kompleks (menulis dokumentasi Program aplikasi antarmuka, API).

+ +

Ikut berkontribusi sangatlah mudah dan aman. Bahkan jika Anda melakukan kesalahan, itu mudah diperbaiki. Bahkan jika Anda tidak mengetahui dengan tepat bagaimana suatu hal yang seharusnya benar, atau tata bahasa Anda tidak sepenuhnya bagus, jangan khawatir akan hal tersebut! Kami memiliki tim yang terdiri dari orang-orang yang bekerja untuk memastikan bahwa konten di MDN bisa lebih baik sebisa mungkin. Seseorang akan ikut serta untuk memastikan bahwa pekerjaan Anda rapih dan ditulis dengan benar.

+ +

Langkah 1: Membuat akun di MDN

+ +

Untuk memulai kontribusi Anda di MDN, Anda memerlukan sebuah akun di MDN. Untuk keterangan lanjut, silahkan lihat bagaimana membuat sebuah akun.

+ +

Langkah 2: Ambil sebuah tugas untuk diselesaikan

+ +

Setelah Anda selesai login, bacalah deskripsi mengenai perbedaan tipe tugas pada daftar dibawah ini, dan tentukan mana yang menjadi daya tarik bagi Anda. Anda bisa mengambil tugas manapun yang Anda sukai sebagai kontribusi yang Anda berikan.

+ +

Langkah 3: Kerjakan tugas

+ +

Setelah Anda menentukan tugas seperti apa yang Anda ingin kerjakan, temukan halaman yang spesifik, misalnya kode, atau yang lainnya untuk dikerjakan, dan lakukanlah!

+ +

Jangan khawatir mengenai kesempurnaan dalam mengerjakan; kontributor MDN lainnya ada disini untuk membantu memperbaiki kesalahan yang terjadi. Jika Anda ingin melakukan percobaan sebelum melakukan sesuatu "yang nyata", Anda bisa mengedit halaman Kotakpasir. Jika Anda memiliki pertanyaan selama melakukan pekerjaan, kunjungi halaman Komunitas untuk informasi di daftar surat menyurat (mailing lists) dan saluran bercakap (Chat Channels) dimana Anda bisa mendapatkan jawaban.

+ +

Ketika Anda selesai, silahkan ambil item lainnya, atau lihat lagi Hal lain yang Anda bisa lakukan di MDN.

+ +

Jenis-jenis tugas yang memungkinkan

+ +

Ada banyak jalan yang dapat Anda ambil untuk berkontribusi untuk MDN tergantung keahlian yang Anda persiapkan dan sukai. Walaupun beberapa tugas bisa menghilangkan semangat, kami juga memiliki banyak kegiatan mudah yang tersedia. Kegiatan tersebut setidaknya hanya membutuhkan lima menit (atau kurang!) dari waktu Anda. Bersama dengan tugas dan dengan deskripsi yang pendek, Anda akan mengetahui berapa waktu perkiraan setiap jenis tugas biasanya akan diselesaikan.

+ +

Opsi 1: Saya menyukai kata-kata

+ +

Anda bisa membantu kami meninjau atau mengedit dokumen yang ada, dan menerapkan label yang benar.

+ + + +
Catatan: Jika Anda sedang meninjau artikel atau menulis artikel yang baru, kami berharap Anda meninjau Panduan Gaya. Ini akan membantu untuk meyakinkan bahwa artikel tersebut sesuai.
+ +

Opsi 2: Saya menyukai kode

+ +

Kami membutuhkan lebih banyak sampel kode! Anda juga dapat membantu membangun perangkat halaman kami, Kuma!

+ + + +

Opsi 3: Saya menyukai kata-kata dan kode

+ +

Kami memiliki tugas-tugas yang membutuhkan teknis dan kemampuan bahasa bersama, seperti menulis artikel baru, meninjau keakurasian teknis, atau mengadapsikan dokumen-dokumen.

+ + + +

Opsi 4: Saya ingin MDN ada di bahasa saya

+ +

Semua lokalisasi and terjemahan selesai dikerjakan di MDN oleh komunitas sukarelawan kami yang mengagumkan.

+ + + +

Opsi 5: Saya menemukan beberapa kesalahan informasi tapi saya tidak tahu bagaimana memperbaikinya

+ +

Anda dapat melaporkan masalah tersebut dengan mengisi dokumentasi kesalahan. (5 menit)

+ +

Gunakan nilai bidang ini:

+ + + + + + + + + + + + + + + + + + + + + + + + +
Bidang BugzillaNilai
produkDokumentasi Pengembang
komponen[memilih daerah yang sesuai dengan topik, atau "Umum" jika Anda tidak yakin atau Anda tidak melihat mana yang benar]
URLHalaman dimana Anda menemukan masalah
DeskripsiSebanyak yang Anda ketahui atau memiliki waktu untuk mengutarakan masalah tersebut dan dimana menemukan informasi yang benar. Ini dapat berisi orang-orang yang ("berbicara jadi-dan-jadi") sebaik mungkin seperti tautan Web.
+ +

Hal-hal lai yang bisa Anda lakukan di MDN

+ + diff --git a/files/id/mdn/contribute/howto/create_an_mdn_account/index.html b/files/id/mdn/contribute/howto/create_an_mdn_account/index.html new file mode 100644 index 0000000000..aba3020441 --- /dev/null +++ b/files/id/mdn/contribute/howto/create_an_mdn_account/index.html @@ -0,0 +1,44 @@ +--- +title: Bagaimana Membuat Akun MDN +slug: MDN/Contribute/Howto/Create_an_MDN_account +tags: + - Bagaimana + - Dokumentasi + - MDN Meta + - Panduan + - Pemula +translation_of: MDN/Contribute/Howto/Create_an_MDN_account +--- +
{{MDNSidebar}}

Untuk melakukan perubahan isi MDN, Anda membutuhkan sebuah MDN profil. Anda tidak perlu profil jika Anda hanya ingin membaca dan mencari info di kumpulan dokumen MDN. Panduan ini akan membantu anda melakukan pengaturan profil akun MDN anda.

+ +
Mengapakah MDN membutuhkan alamat email saya?
+
+Alamat email Anda digunakan dalam pemulihan akun dan juga digunakan oleh administrator MDN untuk menghubungi Anda tentang akun atau kegiatan Anda dalam situs web.
+
+Selanjutnya, Anda dapat mendaftar untuk menerima pemberitahuan (seperti pada situs-situs tertentu diubah) serta pesan (misalnya, jika Anda ingin bergabung tim tes beta kami, Anda mungkin menerima email tentang fitur-fitur baru yang membutuhkan tes).
+
+Alamat email Anda tidak akan ditampilkan pada MDN dan akan digunakan mengikuti kebijakan privasi kami saja.
+ +
    +
  1. Pada bagian atas tiap halaman MDN Anda dapat menemukan tombol "Masuk melalui". Arahkan mouse Anda pada tombol ini (atau sentuh, jika Anda menggunakan perankat seluler) untuk menampilkan daftar otentikasi layanan yang kami mendukung untuk login ke MDN.
  2. +
  3. Pilih satu layanan login dari yang tersedia ditampilan. Saat ini hanya mendukung layanan melalui akun GitHub. Perlu diingat bahwa jika anda gunakan akun GitHub, profil GitHub Anda akan terhubung dengan halaman profil MDN anda.
  4. +
  5. Ikuti halaman yang mengarah ke halaman masuk akun GitHub tersebut untuk menghubungkan ke akun MDN Anda.
  6. +
  7. Saat layanan otentikasi kembali ke akun MDN, Anda akan diminta untuk mendaftarkan satu nama pengguna dan alamat email. Nama pengguna Anda akan tampil secara publik untuk kredit kerja yang Anda lakukan. Janganlah menggunakan alamat email Anda sebagai nama pengguna.
  8. +
  9. Tekan tombol berlabel Create my MDN profile.
  10. +
  11. Jika alamat email yang Anda masukkan pada langkah 4 tidak sama dengan alamat email yang Anda gunakan dengan layanan otentikasi, silahkan verifikasi email dengan mengecek email Anda dan tekan pada link pada email konfirmasi yang telah dikirim kepada Anda.
  12. +
+ +

Begitu saja! Anda telah memiliki akun MDN dan Anda dapat segera menyunting halaman!
+
+ Anda bisa klik pada nama Anda di bagian atas setiap halaman MDN untuk melihat profil publik Anda. Dari sana, Anda bisa klik tombol Edit untuk membuat perubahan pada profil atau melakukan penambahan pada profil Anda.

+ +
+

Note: Nama pengguna baru tidak boleh berisi spasi atau karakter "@". Ingatlah nama pengguna akan ditampilkan secara publik untuk menunjukkan kreasi yang Anda buat!

+
+ +

 

diff --git a/files/id/mdn/contribute/howto/do_a_technical_review/index.html b/files/id/mdn/contribute/howto/do_a_technical_review/index.html new file mode 100644 index 0000000000..7a9ffab8a9 --- /dev/null +++ b/files/id/mdn/contribute/howto/do_a_technical_review/index.html @@ -0,0 +1,49 @@ +--- +title: How to do a technical review +slug: MDN/Contribute/Howto/Do_a_technical_review +translation_of: MDN/Contribute/Howto/Do_a_technical_review +--- +
{{MDNSidebar}}

A Technical review consists of reviewing the technical accuracy and completeness of an article and correcting it if necessary. If a writer of an article wants someone else to check the technical content of an article, the writer ticks the "Technical review" checkbox while editing. Often the writer contacts a specific engineer to perform the technical review, but anyone with technical expertise in the topic can do one.

+ +

This article describes how to perform a technical review, thereby helping to ensure that MDN's content is accurate.

+ +
+
What is the task?
+
Reviewing and correcting the articles for technical accuracy and completeness.
+
Where does it need to be done?
+
In specific articles that are marked as requiring a technical review.
+
What do you need to know to do the task?
+
+
    +
  • Expert knowledge of the topic of the article you are reviewing. If reading the article doesn't teach you anything significantly new, consider yourself an expert.
  • +
  • How to edit a wiki article on MDN.
  • +
+
+
What are the steps to do it?
+
+
    +
  1. Pick an article to review: +
      +
    1. Go to the list of pages that need technical reviews. This lists all the pages for which a technical review has been requested.
    2. +
    3. Choose a page whose topic you are very familiar with.
    4. +
    5. Click on the article link to load the page.
    6. +
    +
  2. +
  3. Read the article, paying close attention to technical details: Is the article correct? Is there anything missing? Don't hesitate to switch to a different page if the first one you choose doesn't suit you.
  4. +
  5. If there are no errors, you don't need to edit the article to mark it as reviewed. Look for the "quick review" box in the left sidebar of the page. This yellow box lists any pending reviews and lets you clear their review request flag. It looks like this if a technical review has been requested:
    + Screenshot of the sidebar's box listing reviews that have been requested and allowing the flags to be changed.
  6. +
  7. Deselect the Technical checkbox, and click Save.
  8. +
  9. If you find errors that need to be corrected, you'll be glad to know that you can also change the review request status from within the editor. Here's the workflow: +
      +
    1. To edit the page, click the Edit button near the top of the page; this puts you into the MDN editor.
    2. +
    3. Fix any technical information is not correct, and/or add any important information that is missing.
    4. +
    5. Enter a Revision Comment at the bottom of the article. This is a brief message that describes what you did, like 'Technical review completed.' If you corrected information, include that in your comment, for example 'Technical review and fixed parameter descriptions.' This helps other contributors and site editors know what you changed and why. You can also mention if there were specific bits that you didn't feel qualfied to review
    6. +
    7. Deselect the Technical box under Review Needed? just below the Revision Comment area of the page.
    8. +
    9. Click the PUBLISH button.
    10. +
    +
  10. +
+ +

Congratulations! You've finished your first technical review! Thank you for your help!

+
+
diff --git a/files/id/mdn/contribute/howto/do_an_editorial_review/index.html b/files/id/mdn/contribute/howto/do_an_editorial_review/index.html new file mode 100644 index 0000000000..74aff54886 --- /dev/null +++ b/files/id/mdn/contribute/howto/do_an_editorial_review/index.html @@ -0,0 +1,52 @@ +--- +title: How to do an editorial review +slug: MDN/Contribute/Howto/Do_an_editorial_review +tags: + - Dokumentasi + - MDN Meta + - Panduan +translation_of: MDN/Contribute/Howto/Do_an_editorial_review +--- +
{{MDNSidebar}}
{{IncludeSubnav("/id/docs/MDN")}}
+ +

Ulasan redaksi terdiri dari memperbaiki kesalahan ketik, ejaan, tata bahasa, pemakaian, atau teks yang salah dalam artikel. Tidak semua relawan ahli bahasa, tetapi terlepas dari pengetahuan mereka sangat berkontribusi pada artikel yang berguna, dimana membutuhkan salin-ubah dan koreksi cetakan.

+ +

Artikel ini menggambarkan bagaimana cara melakukan ulasan redaksi, dengan demikian membantu memastikan bahwa konten MDN akurat .

+ +
+
Apa sih tugasnya?
+
Salin-ubah dan perbaikan cetakan dari artikel yang membutuhkan ulasan redaksi.
+
Dimana ulasan redaksi dikerjakan?
+
Diantara artikel yang sudah ditandai membutuhkan ulasan redaksi.
+
Apa yang harus diketahui untuk menyelesaikan tugas?
+
Baik dalam tata bahasa dan kemampuan eja berbahasa Inggris. Seseorang pengulas redaksi memastikan tata bahasa, ejaan, dan kata dengan benar serta masuk akal, dan berikut juga MDN writing style guide.
+
Apa langkah-langkah untuk melakukannya?
+
+
    +
  1. Pilih artikel yang ingin diulas: +
      +
    1. Ke daftar artikel yang membutuhkan ulasan.  Ini berisi halaman yang diminta untuk diulas.
    2. +
    3. Pilih halaman yang meiliki judul bahasa Inggris dan yang tidak diawali Template: (Template: halaman yang mengandung MDN macro code.)
    4. +
    5. Klik tautan pada artikel untuk menampilkan halaman.
    6. +
    +
  2. +
  3. Baca artikelnya, berikan perhatian pada kesalahan ketik, ejaan, tata bahasa, atau penggunaan kata yang salah. Jangan ragu untuk beralih ke halaman yang berbeda jika pertama yang Anda pilih tidak sesuai dengan Anda .
  4. +
  5. Jika tidak terdapat kesalahan, anda tidak perlu merubah artikel untuk menandakan itu telah diulas. Cari kotak "quick review" di sisi kiri dari halaman:
    + Screenshot of the editorial review request sidebar box
    + Hapus centang pada kotak Editorial dan klik Save.
  6. +
  7. Jika anda menemukan error yang perlu di koreksi: +
      +
    1. Klik tombol Sunting di atas halaman; ini akan membawa anda ke MDN editor.
    2. +
    3. Mengoreksi kesalahan ketik, penulisan, tata bahasa, atau penggunaan kode yang error yang anda temukan. Anda tidak perlu memperbaiki semuanya, tapi pastikan anda meninggalkan permintaan editor review pada halaman yang anda rasa belum sepenuhnya sempurna untuk anda menyelesaikannya hingga keseluruhan artikel.
    4. +
    5. Masukan Revision Comment pada bawah artikel; seperti 'Editorial review: perbaikan salah ketik, tata bahasa & penulisan.' Ini memungkinkan kontributor lain dan editor situs tahu apa yang anda rubah dan kenapa.
    6. +
    7. Hapus centang pada kotak Editorial dibawah Review Needed?. Tepatnya pada bawah komentar revisi pada halaman.
    8. +
    9. Klik tombol Publish.
    10. +
    +
  8. +
+ +
+

Perubahan yang anda buat mungkin tidak langsung di tampilkan setelah disimpan; disini ada rentang waktu ketika halaman di proses dan disimpan.

+
+
+
diff --git a/files/id/mdn/contribute/howto/index.html b/files/id/mdn/contribute/howto/index.html new file mode 100644 index 0000000000..1ac1697957 --- /dev/null +++ b/files/id/mdn/contribute/howto/index.html @@ -0,0 +1,16 @@ +--- +title: How-to guides +slug: MDN/Contribute/Howto +tags: + - Documentation + - Landing + - MDN + - NeedsTranslation + - TopicStub +translation_of: MDN/Contribute/Howto +--- +
{{MDNSidebar}}
{{IncludeSubnav("/id/docs/MDN")}}
+ +

Artikel berikut menyediakan pedoman langkah - langkah untuk mencapai tujuan tertentu ketika berkontribusi di MDN.

+ +

{{LandingPageListSubpages}}

diff --git a/files/id/mdn/contribute/howto/set_the_summary_for_a_page/index.html b/files/id/mdn/contribute/howto/set_the_summary_for_a_page/index.html new file mode 100644 index 0000000000..ad89ef0686 --- /dev/null +++ b/files/id/mdn/contribute/howto/set_the_summary_for_a_page/index.html @@ -0,0 +1,46 @@ +--- +title: How to set the summary for a page +slug: MDN/Contribute/Howto/Set_the_summary_for_a_page +translation_of: MDN/Contribute/Howto/Set_the_summary_for_a_page +--- +
{{MDNSidebar}}

You can define the summary of a page on MDN, to be used in various ways, including in search engine results, in other MDN pages such as topical landing pages, and in tooltips. It should be text that makes sense both in the context of the page, and when displayed in other contexts, without the rest of the page content.

+

A summary can be explicitly defined within a page. If it is not explicitly defined, then typically the first sentence or so is used, which is not always the best text for this purpose.

+ + + + + + + + + + + + + + + + + + + +
What is the task?Marking the text within a page that should be used as its summary in other contexts; this task might include writing appropriate text if needed.
Where does it need to be done?In pages that lack a summary or have a less-than-great summary.
What do you need to know to do the task?Ability to use the MDN editor; good English writing skills; enough familiarity with the topic of the page to write a good summary.
What are the steps to do it? +
    +
  1. Pick a page on which to set the summary: +
      +
    1. In the MDN documentation status page, click the link under Sections for a topic that you know something about (for example, HTML).
    2. +
    3. On the topic's documentation status page, click the Pages header in the Summary table. This takes you to an index of all the pages in that topic section; it shows the page links in the left column, and the tags and summaries in the right column.
    4. +
    5. Pick a page that is missing a summary, or that has a poor summary.
    6. +
    7. Click the link to go to that page.
    8. +
    +
  2. +
  3. Click Edit to open the page in the MDN editor.
  4. +
  5. Look for a sentence or two that works as a summary out of context. If needed, edit the existing content to create or modify sentences to be a good summary.
  6. +
  7. Select the text to be used as a summary.
  8. +
  9. In the Styles widget of the editor toolbar, select SEO Summary. (In the page source, this creates a {{HTMLElement("span")}} element with class="seoSummary" around the selected text.)
  10. +
  11. Save your changes with a revision comment like "Set the page summary."
  12. +
+
+

 

+

 

+

 

diff --git a/files/id/mdn/contribute/howto/tag/index.html b/files/id/mdn/contribute/howto/tag/index.html new file mode 100644 index 0000000000..8b0d868f78 --- /dev/null +++ b/files/id/mdn/contribute/howto/tag/index.html @@ -0,0 +1,373 @@ +--- +title: How to properly tag pages +slug: MDN/Contribute/Howto/Tag +translation_of: MDN/Contribute/Howto/Tag +--- +
{{MDNSidebar}}

One important feature of MDN that helps users find content is the article tag. Each page can be tagged with zero or more tags (preferably at least one) to help categorize the content. There are many ways tags are used to help organize information on MDN; this page will help you learn how to best tag pages to help information be organized, sorted, and located by readers.

+ +

For a guide to the user interface for editing tags on pages, see the tagging section in our editor guide.

+ +

Note that proper use of tags is important; we are increasingly using automation to generate lists of content, landing pages, and cross-linking of articles. Failure to properly tag articles as indicated below can prevent articles from being listed correctly.

+ +

Ways tags are used on MDN

+ +

There are several ways tags get used on MDN:

+ +
+
Categorization
+
What type of document is it? Is it a reference? A tutorial? A landing page? These can be used when filtering searches, so they're really important!
+
Topic identification
+
What topic does the article cover? Is it about an API? The DOM? Graphics? These, too, are important, because they can be used as filters on searches.
+
Technology status
+
What's the status of the technology? Is it non-standard? Obsolete or deprecated? Experimental?
+
Skill level
+
For tutorials and guides, how advanced is the material covered by the article?
+
Document metadata
+
The writing community often needs a way to track information about pages in need of specific kinds of work. This is done using tags.
+
+ +

Tag type guide

+ +

Here's a quick guide to the types of tags and possible values for them.

+ +

Category

+ +

Tagging an article with one of these categories will help automatically constructed landing pages, table of contents pages, and the like be more accurately built. These terms will also be used by our new search system, eventually, to let the user locate reference or guide information by their choice.

+ +

The following category names are standard tagging terms used on MDN.

+ +
+
{{Tag("Intro")}}
+
The article provides introductory material about a topic. In theory there should be only one of these per technology area.
+
{{Tag("Featured")}}
+
The article is a high-importance article that should be featured in a special way on landing pages; this must be used sparingly. Only three or fewer of these should exist in any documentation area.
+
{{Tag("Reference")}}
+
The article contains reference material about an API, element, attribute, property, or the like.
+
{{Tag("Landing")}}
+
The page is a landing page.
+
{{Tag("Guide")}}
+
The article is a how-to or guide page.
+
{{Tag("Example")}}
+
The article is a code sample page, or has code samples. This shouldn't be used for very one-liner "syntax examples" but actual snippets of useful code, or for full usable samples.
+
+ +

Topic

+ +

By identifying the article's topic area, you can also help to generate better search results as well as landing pages and other navigational aids.

+ +

While there's some room for flexibility here as new topic areas are identified, we try to keep these to the names of APIs or technologies. Some useful examples:

+ + + +

In general, the name of an interface that has a number of related pages, such as Node (which has many pages for its various properties and methods) makes a good topic identification tag, as does the name of an overall technology or technology type. A page about WebGL might be tagged with Graphics and WebGL, for example, while a page about the {{HTMLElement("canvas")}} element might be tagged HTML, Element, Canvas, and Graphics.

+ +

Technology status

+ +

To help the reader understand how viable a technology is, we use tags to label pages as to what the status of the technology's specification is. This isn't as detailed as actually explaining what the spec is and where in the specification process the technology is (that's what the Specifications table is for), but it will help the reader judge, at a glance, whether using the technology described in the article is a good idea or not.

+ +

Here are possible values for these tags:

+ +
+
{{Tag("Non-standard")}}
+
Indicates that the technology or API described on the page is not part of a standard, but is considered stable in the browser or browsers that do implement it. If you don't use this tag, the assumption is made that the article covers something that's standard. The compatibility table on the page should clarify which browser(s) support this technology or API.
+
{{Tag("Deprecated")}}
+
The technology or API covered on the page has been marked as deprecated in the specification, and is expected to eventually be removed, but is generally still available in current versions of browsers.
+
{{Tag("Obsolete")}}
+
The technology or API has been deemed obsolete and has been removed (or is actively in the process of being removed) from all or most current browsers.
+
{{Tag("Experimental")}}
+
The technology is not standardized, and is an experimental technology or API that may or may not ever become part of a standard.
+
{{Tag("Needs Privileges")}}
+
The API requires privileged access to the device on which the code is running.
+
{{Tag("Certified Only")}}
+
The API only works in certified code.
+
+ +

Regardless of the use of these tags, you should be sure to include a compatibility table in your article!

+ +

Skill level

+ +

The skill level tag type is only used for guides and tutorials (that is, pages tagged Guide). It's used to help users whittle down tutorials based on their familiarity level with a technology, for example. There are three values for this:

+ +
+
{{Tag("Beginner")}}
+
Articles designed to introduce the reader to a technology they've never used or have only a passing familiarity with.
+
{{Tag("Intermediate")}}
+
Articles for users that have gotten started with the technology but aren't experts.
+
{{Tag("Advanced")}}
+
Articles about stretching the capabilities of a technology and of the reader.
+
+ +

Document metadata

+ +

The writing community uses tags to label articles as requiring specific types of work. Here's a list of the ones we use most:

+ +
+
{{Tag("junk")}}
+
The article needs to be deleted.
+
{{Tag("NeedsContent")}}
+
The article is a stub, or is otherwise lacking information. This tag means that someone should review the content and add more details and/or finish writing the article.
+
{{Tag("NeedsExample")}}
+
The article needs one or more examples created to help illustrate the article's point. These examples should use the live sample system.
+
{{Tag("NeedsLiveSamples")}}
+
The article has one or more examples that need to be updated to use the live sample system.
+
{{Tag("NeedsUpdate")}}
+
The content is out of date and needs to be updated.
+
{{Tag("l10n:exclude")}}
+
The content is not really worth localizing and will not appear on localization status pages.
+
{{Tag("l10n:priority")}}
+
The content is important and should be marked as a priority for MDN translators. Shows up in an extra priority table on localization status pages.
+
+ +

Web Literacy Map

+ +

The WebMaker project, through the Web Literacy Map, has defined a set of tags to qualify the various competencies and skills recommended to get better at reading, writing and participating on the Web. We use them on MDN to help our users to find the best resources to suit their needs:

+ +
+
{{Tag("Navigation")}}
+
The articles provides information on how to browse the web.
+
{{Tag("WebMechanics")}}
+
The article provides information on how the web is organized and how it's working.
+
{{Tag("Search")}}
+
The article provides information on how to locate information, people and resources via the web.
+
{{Tag("Credibility")}}
+
The article provides information on how to critically evaluate information found on the web.
+
{{Tag("Security")}}
+
The article provides information on how to keep systems, identities, and content safe.
+
{{Tag("Composing")}}
+
The article provides information on how to create and curate content for the web.
+
{{Tag("Remixing")}}
+
The article provides information on how to modify existing web resources to create something new.
+
{{Tag("DesignAccessibility")}}
+
The article provides information on how to create universally effective communications through web resources.
+
{{Tag("CodingScripting")}}
+
The article provides information on how to code and/or create interactive experiences on the web.
+
{{Tag("infrastructure")}}
+
The article provides information which help understanding the Internet technical stack.
+
{{Tag("Sharing")}}
+
The article provides information on how to create resources with others.
+
{{Tag("Collaborating")}}
+
The article provides information on how to work with each other.
+
{{Tag("Community")}}
+
The article provides information on how to get involved in web communities and understanding their practices.
+
{{Tag("Privacy")}}
+
The article provides information on how to examine the consequences of sharing data online.
+
{{Tag("OpenPractices")}}
+
The article provides information on how to help keep the web universally accessible.
+
+ +

Putting it all together

+ +

So, with these different types of tags, you assemble them together to get the full set of tags for a page. A few examples:

+ +
+
A tutorial about WebGL for beginners
+
Appropriate tags would be: WebGL, Graphics, Guide, Beginner
+
Reference page for the {{HTMLElement("canvas")}} element
+
This should be tagged with Canvas, HTML, Element, Graphics Reference
+
A landing page for Firefox OS developer tools
+
This should be tagged with Tools, Firefox OS, Landing
+
+ +

Tagging and search filters

+ +

The upcoming search filter implementation, which will let users restrict the results of their searches based on criteria they specify, will rely on proper tagging of pages on MDN. Here's a table of the various search filters and which tags they look for.

+ +
+

Note: If multiple tags are listed under "Tag name," that means any one or more of those tags need to be present for the article to match.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Filter groupSearch filter nameTag name
TopicOpen Web Apps{{Tag("Apps")}}
 HTML{{Tag("HTML")}}
 CSS{{Tag("CSS")}}
 JavaScript{{Tag("JavaScript")}}
 APIs and DOM{{Tag("API")}}
 Canvas{{Tag("Canvas")}}
 SVG{{Tag("SVG")}}
 MathML{{Tag("MathML")}}
 WebGL{{Tag("WebGL")}}
 XUL{{Tag("XUL")}}
 Marketplace{{Tag("Marketplace")}}
 Firefox{{Tag("Firefox")}}
 Firefox for Android{{Tag("Firefox Mobile")}}
 Firefox for Desktop{{Tag("Firefox Desktop")}}
 Firefox OS{{Tag("Firefox OS")}}
 Mobile{{Tag("Mobile")}}
 Web Development{{Tag("Web Development")}}
 Add-ons & Extensions{{Tag("Add-ons ")}}|| {{Tag("Extensions")}} || {{Tag("Plugins")}} || {{Tag("Themes")}}
 Games{{Tag("Games")}}
Skill levelI'm an Expert{{Tag("Advanced")}}
 Intermediate{{Tag("Intermediate")}}
 I'm Learning{{Tag("Beginner")}}
Document typeDocsThis will restrict the search to docs content, leaving out Hacks and other MDN content.
 DemosThis will include Demo Studio content in the search results.
 Tools{{Tag("Tools")}}
 Code Samples{{Tag("Example")}}
 How-To & Tutorial{{Tag("Guide")}}
 Developer ProfilesThis will include developer profiles from the MDN site in the search results.
 External ResourcesThis is something the dev team will need to figure out.
+ +

Tagging problems you can fix

+ +

There are several types of problems with tags you can help fix:

+ +
+
No tags
+
All articles should have at least one tag, and usually more than one. Generally, at a minimum, articles should have at least a "category" tag and a "topic" tag. Often other tags are appropriate as well, but if you can help us ensure that at least these are present, you'll be a documentation hero!
+
Tags that don't follow our tagging standards
+
We have a Tagging standards guide that explains how we use tags, including lists of appropriate tags to use on various types of documentation. Ideally, all articles should follow these standards, so if you see a page whose tags don't do so, please fix it!
+
Incorrect tags
+
If you're looking at an article about HTML and it's got the "JavaScript" tag on it, that's probably wrong! Similarly, if an article is about Mozilla internals but has the "Web" tag on it, that's probably wrong too. Remove these tags (and, if missing, add the right ones). This type of problem includes misspelled tags. "JavaScript" or "Javascript" for example (the latter actually will match, since tags are case-insensitive, but it's just not right!).
+
Missing tags
+
If an article has some tags, but not all of the appropriate ones, feel free to add more. Maybe you're looking at a page in the JavaScript reference, which is correctly tagged with "JavaScript" but has no other tags. Since it's a reference page, this should also have the "Reference" tag. You're invited to add it!
+
Tag spam
+
This insidious beast is the most revolting tag problem of all: some Web vermin has deposited its droppings in the tags for a page, leaving a page with tags like "Free warez!" or "Hey I was browsing your site and wanted to ask you if you could help me solve this problem I'm having with Flash crashing all the time". These need to be deleted posthaste!
+
+ +

If you see one (or more) of these problems, you can help by logging into MDN, then clicking the Edit button at the top right of the MDN window. Once the editor loads up, scroll down to the bottom of the page, where you'll see the tag box. For more details on the tagging interface, see "The tags box" in the MDN editor guide.

diff --git a/files/id/mdn/contribute/index.html b/files/id/mdn/contribute/index.html new file mode 100644 index 0000000000..4d76fd020d --- /dev/null +++ b/files/id/mdn/contribute/index.html @@ -0,0 +1,23 @@ +--- +title: Contributing to MDN +slug: MDN/Contribute +tags: + - Documentation + - Guide + - Landing + - MDN + - NeedsTranslation + - TopicStub +translation_of: MDN/Contribute +--- +
{{MDNSidebar}}
{{IncludeSubnav("/en-US/docs/MDN")}}
+ +

Selamat Datang! Dengan mengunjungi halaman ini, anda telah mengambil satu langkah menjadi kontributor di MDN!

+ +

Daftar paduan disini memuat semua aspek kontribusi ke MDN, diantaranya paduan style, paduan menggunakan alat dan editor kami, dan banyak lagi. Pastikan anda membaca (dan aduan tentang) Mozilla Terms sebelum mengedit atau membuat halaman.

+ +

Jika anda belum pernah berkontribusi di MDN, Paduan Memulai bisa membantu anda memulai.

+ +
 
+ +

{{LandingPageListSubPages()}}

diff --git a/files/id/mdn/contribute/processes/index.html b/files/id/mdn/contribute/processes/index.html new file mode 100644 index 0000000000..d01213c69f --- /dev/null +++ b/files/id/mdn/contribute/processes/index.html @@ -0,0 +1,23 @@ +--- +title: Proses dokumentasi +slug: MDN/Contribute/Processes +tags: + - ButuhPenerjemahan + - Landing + - MDN Meta + - Meta MDN + - NeedsTranslation + - Pendaratan + - Processes + - Proses + - RintisanTopik + - TopicStub +translation_of: MDN/Contribute/Processes +--- +
{{MDNSidebar}}
+ +
{{IncludeSubnav("/en-US/docs/MDN")}}
+ +

The MDN documentation project is enormous; there are a huge number of technologies to cover, and we have hundreds of contributors all over the world. To help bring order to chaos, we've got standard processes to follow when working on specific documentation-related tasks. Here you'll find guides to those processes.

+ +

{{LandingPageListSubPages()}}

diff --git a/files/id/mdn/contribute/tugas/index.html b/files/id/mdn/contribute/tugas/index.html new file mode 100644 index 0000000000..c72f962d66 --- /dev/null +++ b/files/id/mdn/contribute/tugas/index.html @@ -0,0 +1,25 @@ +--- +title: Tugas untuk dilakukan di MDN +slug: MDN/Contribute/Tugas +tags: + - Dokumentasi + - MDN + - Panduan + - Proyek MDC +translation_of: MDN/Contribute/Getting_started +--- +
{{MDNSidebar}}

Anda ingin membuat MDN menjadi lebih baik ? Ada banyak sekali cara untuk membantu: dari memperbaiki ejaan kalimat sampai membuat konten baru, Atau bahkan membantu mengembangkan platform Kurma dimana website ini dibuat. Panduan kontributor MDN mencakup semua hal yang bisa anda bantu dan lakukkan untuk mereka. Dibawah ini, anda bisa mencari daftar spesifikasi dari tugas yang perlu diselesaikan.

+ +

Ada banyak hal yang bisa anda lakukan untuk membantu MDN. Kami punya panduan untuk tugas yang ingin anda lakukan pada artikel Memulai MDN. Berikut caranya: 

+ + + +

Untuk ide lebih lanjut bagaimana anda bisa membantu dengan MDN, lihat Panduan kami. Anda bisa mencari daftar kategori dari halaman yang anda butuhkan untuk membantu pada bagian  Status Dokumen.

diff --git a/files/id/mdn/guidelines/index.html b/files/id/mdn/guidelines/index.html new file mode 100644 index 0000000000..fdedce143e --- /dev/null +++ b/files/id/mdn/guidelines/index.html @@ -0,0 +1,16 @@ +--- +title: MDN content and style guides +slug: MDN/Guidelines +tags: + - Documentation + - Landing + - MDN + - NeedsTranslation + - TopicStub +translation_of: MDN/Guidelines +--- +
{{MDNSidebar}}
{{IncludeSubnav("/en-US/docs/MDN")}}
+ +

Paduan berikut memberikan detail bagaimana dokumentasi MDN harus ditulis dan format tulisannya, juga cara bagaimana contoh kode dan konten lainnya di sampaikan. Dengan mengikuti paduan berikut, anda dapat memastikan bahwa semua material yang anda buat asli dan mudah digunakan.

+ +

{{LandingPageListSubpages}}

diff --git a/files/id/mdn/guidelines/layout/index.html b/files/id/mdn/guidelines/layout/index.html new file mode 100644 index 0000000000..9bb0fe9ea3 --- /dev/null +++ b/files/id/mdn/guidelines/layout/index.html @@ -0,0 +1,7 @@ +--- +title: MDN page layout guide +slug: MDN/Guidelines/Layout +translation_of: Archive/Meta_docs/MDN_page_layout_guide +--- +
{{MDNSidebar}}

These guides supplement the MDN style guide with specific layouts for the various types of pages on MDN. This helps contributors create new content that's structurally consistent with the rest of MDN.

+

{{LandingPageListSubpages}}

diff --git a/files/id/mdn/guidelines/writing_style_guide/index.html b/files/id/mdn/guidelines/writing_style_guide/index.html new file mode 100644 index 0000000000..b3ad6bb25f --- /dev/null +++ b/files/id/mdn/guidelines/writing_style_guide/index.html @@ -0,0 +1,802 @@ +--- +title: Writing style guide +slug: MDN/Guidelines/Writing_style_guide +tags: + - tags bahasa Indonesia +translation_of: MDN/Guidelines/Writing_style_guide +--- +
{{MDNSidebar}}
+ +
{{IncludeSubnav("/en-US/docs/MDN")}}
+ +

To present documentation in an organized, standardized, and easy-to-read manner, the MDN Web Docs style guide describes how text should be organized, spelled, formatted, and so on. These are guidelines rather than strict rules. We are more interested in content than formatting, so don't feel obligated to learn the style guide before contributing. Do not be upset or surprised, however, if an industrious volunteer later edits your work to conform to this guide.

+ +

The language aspects of this guide apply primarily to English-language documentation. Other languages may have (and are welcome to create) style guides. These should be published as subpages of the localization team's page.

+ +

For style standards that apply to content written for sites other than MDN, refer to the One Mozilla style guide.

+ +

Basics

+ +

The best place to start in any extensive publishing style guide is with some very basic text standards to help keep documentation consistent. The following sections outline some of these basics to help you.

+ +

Page titles

+ +

Page titles are used in search results and also used to structure the page hierarchy in the breadcrumb list at the top of the page. The page title (which is displayed at the top of the page and in the search results) can be different from the page "slug", which is the portion of the page's URL following "<locale>/docs/".

+ +

Title and heading capitalization

+ +

Page titles and section headings should use sentence-style capitalization (only capitalize the first word and proper nouns) rather than headline-style capitalization:

+ + + +

We have many older pages that were written before this style rule was established. Feel free to update them as needed if you like. We're gradually getting to them.

+ +

Choosing titles and slugs

+ +

Page slugs should be kept short; when creating a new level of hierarchy, the new level's component in the slug should just be a word or two.

+ +

Page titles, on the other hand, may be as long as you like, within reason, and they should be descriptive.

+ +

Creating new subtrees

+ +

When you need to add some articles about a topic or subject area, you will typically do so by creating a landing page, then adding subpages for each of the individual articles. The landing page should open with a paragraph or two describing the topic or technology, then provide a list of the subpages with descriptions of each page. You can automate the insertion of pages into the list using some macros we've created.

+ +

For example, consider the JavaScript guide, which is structured as follows:

+ + + +

Try to avoid putting your article at the top of the hierarchy, which slows the site down and makes search and site navigation less effective.

+ +
+

Note: Adding articles requires page creation privileges.

+
+ +

General article content guidelines

+ +

When writing any document, it's important to know how much to say. If you ramble on too long, or provide excessive detail, the article becomes tedious to read and nobody will use it. Getting the amount of coverage right is important for several reasons. Among those reasons: to ensure that the reader finds the information they truly need, and to provide enough quality material for search engines to adequately analyze and rank the article.

+ +

We'll discuss the former (providing the information the reader may need) here. To learn a little about ensuring that pages are properly classified and ranked by search engines, see the article How to write for SEO on MDN.

+ +

The goal is to write pages that include all the information that readers may need without going on too long about it all. We have a few recommendations in this area.

+ +

Consider your audience

+ +

Keep in mind that these are guidelines. Some of these tips may not apply in every case. Certainly keep your article's audience in mind. An article on advanced network techniques likely doesn't need to go into as much detail about basic networking concepts as the typical article on networking code, for instance.

+ +

Provide a useful summary

+ +

Make sure the article's summary—that is, the opening paragraph or paragraphs before the first heading—provides enough information for the reader to understand if the article is likely to be covering what they're interested in reading about.

+ +

In guide or tutorial content, the summary should let the reader know what topics will be covered and what they're already expected to know, if anything. It should mention the technology, technologies, and/or APIs that are being documented or discussed, with links to those, and it should offer hints as to the situations in which the article's contents might be useful.

+ +
Example: Too short!
+ +

This example of a summary is far too short. It leaves out too much information, such as what it means exactly to "stroke" text, where the text is drawn, and so forth.

+ +
+

CanvasRenderingContext2D.strokeText() draws a string.

+
+ +
Example: Too long!
+ +

Here, we've updated the summary, but now it's far too long. Too much detail is included, and the text gets far too much into other methods and properties.

+ +

Instead, the summary should focus on the strokeText() method, and should refer to the appropriate guide where the other details are offered.

+ +
+

When called, the Canvas 2D API method CanvasRenderingContext2D.strokeText() strokes the characters in the specified string beginning at the coordinates specified, using the current pen color. In the terminology of computer graphics, "stroking" text means to draw the outlines of the glyphs in the string without filling in the contents of each character with color.

+ +

The text is drawn using the context's current font as specified in the context's {{domxref("CanvasRenderingContext2D.font", "font")}} property.

+ +

The placement of the text relative to the specified coordinates are determined by the context's textAlign, textBaseline, and direction properties. textAlign controls the placement of the string relative to the X coordinate specified; if the value is "center", then the string is drawn starting at x - (stringWidth / 2), placing the specified X-coordinate in the middle of the string. If the value is "left", the string is drawn starting at the specified value of x. And if textAlign is "right", the text is drawn such that it ends at the specified X-coordinate.

+ +

(etc etc etc...)

+ +

You can, optionally, provide a fourth parameter that lets you specify a maximum width for the string, in pixels. If you provide this parameter, the text is compressed horizontally or scaled (or otherwise adjusted) to fit inside a space that wide when being drawn.

+ +

You can call the fillText() method to draw a string's characters as filled with color instead of only drawing the outlines of the characters.

+
+ +
Example: Much better!
+ +

Here we see a much better overview for the strokeText() method.

+ +
+

The {{domxref("CanvasRenderingContext2D")}} method strokeText(), part of the Canvas 2D API, strokes—that is, draws the outlines of—the characters of a specified string, anchored at the position indicated by the given X and Y coordinates. The text is drawn using the context's current {{domxref("CanvasRenderingContext2D.font", "font")}}, and is justified and aligned according to the {{domxref("CanvasRenderingContext2D.textAlign", "textAlign")}}, {{domxref("CanvasRenderingContext2D.textBaseline", "textBaseline")}}, and {{domxref("CanvasRenderingContext2D.direction", "direction")}} properties.

+ +

For more details and further examples, see {{SectionOnPage("/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics", "Text")}} in the Learning Area as well as our main article on the subject, Drawing text.

+
+ +

Include all relevant examples

+ +

More pages should have examples than not. The majority of pages probably deserve multiple examples, in fact.

+ +

It's important to ensure that you use examples to clarify what every parameter is used for, and to clarify any edge cases that may exist. You should also use examples to demonstrate solutions for common tasks, and you should use examples to demonstrate solutions to problems that may arise.

+ +

Each example should be preceded by text explaining what the example does and anything the reader should know before beginning to read or try out the example.

+ +
Code Examples
+ +

Each piece of code should include an explanation of how it works. Keep in mind that it may make sense to break up a large piece of code into smaller portions so they can be described individually.

+ +

The text following each piece of code should explain anything relevant, using an appropriate level of detail.

+ + + +

When using the live sample system, it's helpful to be aware that all of the {{HTMLElement("pre")}} blocks in the area that contains the sample are concatenated together before running the example, which lets you break any or all of the HTML, CSS, and JavaScript into multiple segments, each optionally with its own descriptions, headings, and so forth. This makes documenting code incredibly powerful and flexible.

+ +

Overly-short articles are hard to find

+ +

If an article is "thin"—that is, too short—it may not be indexed properly (or at all) by search engines. As a rule of thumb, the article's body text should be at least 250–300 words. Don't artificially inflate a page, but treat this guideline as a minimum target length when possible.

+ +

Sections, paragraphs, and newlines

+ +

Use heading levels in decreasing order: {{HTMLElement("h2")}} then {{HTMLElement("h3")}} then {{HTMLElement("h4")}}, without skipping levels.

+ +

H2 is the highest level allowed because H1 is reserved for the page title. If you need more than three or four levels of headers, consider breaking up the article into several smaller articles with a landing page, and linking them together using the following macros: {{TemplateLink("Next")}}, {{TemplateLink("Previous")}}, and {{TemplateLink("PreviousNext")}}.

+ +

Heading dos and donts

+ + + +

The Enter (or Return) key on your keyboard starts a new paragraph. To insert a newline, rather than a new paragraph (that is, to create a {{HTMLElement("br")}} instead of a {{HTMLElement("p")}}), hold down the Shift key while pressing Enter.

+ +

Lists

+ +

Lists should be formatted and structured uniformly across all contributions. Individual list items should be written with suitable punctuation, regardless of the list format. However, depending on the type of list you are creating, you will want to adjust your writing as described in the sections below.

+ +

Bulleted lists

+ +

Bulleted lists should be used to group related pieces of concise information. Each item in the list should follow a similar sentence structure. Phrases and sentences in bulleted lists should include standard punctuation. Periods must appear at the end of each sentence in a bulleted list, including the item's final sentence, just as would be expected in a paragraph.

+ +

An example of a correctly structured bulleted list:

+ +
+

In this example we should include:

+ + +
+ +

Note how the same sentence structure repeats from bullet to bullet. In this example, each bullet point states a condition followed by a comma and a brief explanation, and each item in the list ends with a period.

+ +

Numbered lists

+ +

Numbered lists are used primarily to enumerate steps in a set of instructions. Because instructions can be complex, clarity is a priority, especially if the text in each list item is lengthy. As with bulleted lists, follow standard punctuation usage.

+ +

An example of a correctly structured numbered list:

+ +
+

In order to correctly structure a numbered list, you should:

+ +
    +
  1. Open with a heading or brief paragraph to introduce the instructions. It's important to provide the user with context before beginning the instructions.
  2. +
  3. Start creating your instructions, and keep each step in its own numbered item. Your instructions may be quite extensive, so it is important to write clearly and use correct punctuation.
  4. +
  5. After you have finished your instructions, close off the numbered list with a brief summary or explanation of the expected outcome upon completion.
  6. +
+ +

This is an example of writing a closing explanation. We have created a short numbered list that provides instructive steps to produce a numbered list with the correct formatting.

+
+ +

Note how the items in numbered lists read like short paragraphs. Because numbered lists are routinely used for instructional purposes, or to walk someone through an orderly procedure, be sure to keep each item focused: one item per number or step.

+ +

Text formatting and styles

+ +

Use the "Formatting Styles" drop-down list to apply predefined styles to selected content.

+ +
The "Note Box" style is used to call out important notes, like this one.
+ +
Similarly, the "Warning Box" style creates warning boxes like this.
+ +

Unless specifically instructed to do so, do not use the HTML style attribute to manually style content. If you can't do it using a predefined class, ask for help in the MDN discussion forum.

+ +

Code sample style and formatting

+ +
+

Note: This section deals with the styling/formatting of code as it appears on an MDN article. If you want guidelines on actually writing code examples, see our Code sample guidelines.

+
+ +

Tabs and line breaks

+ +

Use two spaces per tab in all code examples. Indent the code cleanly, with open-brace ("{") characters on the same line as the statement that opens the block. For example:

+ +
if (condition) {
+  /* handle the condition */
+} else {
+  /* handle the "else" case */
+}
+
+ +

Long lines shouldn't be allowed to stretch off horizontally to the extent that they require horizontal scrolling to read. Instead, break at natural breaking points. Some examples follow:

+ +
if (class.CONDITION || class.OTHER_CONDITION || class.SOME_OTHER_CONDITION
+       || class.YET_ANOTHER_CONDITION ) {
+  /* something */
+}
+
+var toolkitProfileService = Components.classes["@mozilla.org/toolkit/profile-service;1"]
+                           .createInstance(Components.interfaces.nsIToolkitProfileService);
+
+ +

Inline code formatting

+ +

Use the "Code" button (labeled with two angle brackets "<>") to apply inline code-style formatting to function names, variable names, and method names. (This uses the {{HTMLElement("code")}} element). For example: "the frenchText() function".

+ +

Method names should be followed by a pair of parentheses: doSomethingUseful(). The parentheses help differentiate methods from other code terms.

+ +

Syntax highlighting

+ +

Screenshot of the 'Syntax Highlighter' menu.Entire lines (or multiple lines) of code should be formatted using syntax highlighting rather than the {{HTMLElement("code")}} element. Select the appropriate language from the language list button (the one with the two code blocks), as seen in the screenshot to the right. This will insert a preformatted code box with line numbers and syntax highlighting for the chosen language.

+ +
+

Note: Do not use the {{HTMLElement("code")}} element inside the {{HTMLElement("pre")}} block!

+ +

While this structure is used on some sites, we do not do so on MDN; nesting these elements will break certain aspects of our styling.

+
+ +

The following example shows text with JavaScript formatting:

+ +
+
for (let i = 0, j = 9; i <= 9; i++, j--)
+  document.writeln("a[" + i + "][" + j + "]= " + a[i][j]);
+
+ +

If no appropriate language is available, use ("No Highlight" in the language menu). This will result in code without syntax highlighting:

+ +
x = 42;
+ +

Syntax definitions

+ +

When writing the syntax description section of a reference page, use the "Syntax Box" option in the "Styles" drop-down menu in the editor toolbar. This creates a specially-formatted box used specifically for syntax definitions, distinguishing them from other code blocks.

+ +

Blocks not referring to code

+ +

There are a few use cases where a <pre> block does not refer to code and doesn't have syntax highlighting nor line numbers. In such cases you should add a <pre> without a class attribute. Those cases include things like tree structures:

+ +
root/
+
+  folder1/
+    file1
+
+  folder2/
+    file2
+    file3
+
+ +

To create preformatted content without syntax highlighting and line numbers click the "pre" button in the toolbar. Then start to type the text.

+ +

Styling mentions of HTML elements

+ +

There are specific rules to follow when writing about HTML elements. These rules produce consistent descriptions of elements and their components. They also ensure correct linking to detailed documentation.

+ +
+
Element names
+
Use the {{TemplateLink("HTMLElement")}} macro, which creates a link to the page for that element. For example, writing \{{HTMLElement("title")}} produces "{{HTMLElement("title")}}". If you don't want to create a link, enclose the name in angle brackets and use the "Inline Code" style (e.g., <title>).
+
Attribute names
+
Use "Inline Code" style to put attribute names in code font. Additionally, put them in bold face when the attribute is mentioned in association with an explanation of what it does, or the first time it's used in the article.
+
Attribute definitions
+
Use the {{TemplateLink("htmlattrdef")}} macro (e.g., \{{htmlattrdef("type")}}) for the definition term, so that it can be linked to from other pages easily by simply using the {{TemplateLink("htmlattrxref")}} macro (e.g., \{{htmlattrxref("attr","element")}}) to reference attribute definitions.
+
Attribute values
+
Use the "Inline Code" style to apply <code> to attribute values, and don't use quotation marks around string values, unless needed by the syntax of a code sample.
+
For example: "When the type attribute of an <input> element is set to email or tel ..."
+
+ +

Latin abbreviations

+ +

In notes and parentheses

+ + + +

In running text

+ + + +

Meanings and English equivalents of Latin abbreviations

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AbbrevLatinEnglish
cf.confercompare
e.g.exempli gratiafor example
et al.et aliiand others
etc.et ceteraand so forth, and so on
i.e.id estthat is, in other words
N.B.nota benenote well
P.S.post scriptumpostscript
+ +
+

Always consider whether it's truly beneficial to use a Latin abbreviation. Some of these are used so rarely that many readers won't understand the meaning, and others are often confused with one another.

+ +

Also, be sure that you use them correctly, if you choose to do so. For example, be careful not to confuse "e.g." with "i.e.", which is a common error.

+
+ +

Acronyms and abbreviations

+ +

Capitalization and periods

+ +

Use full capitals and delete periods in all acronyms and abbreviations, including organizations such as "US" and "UN".

+ + + +

Expansion

+ +

On the first mention of a term on a page, expand acronyms likely to be unfamiliar to users. When in doubt, expand it, or, better, link it to the article or glossary entry describing the technology.

+ + + +

Plurals of acronyms and abbreviations

+ +

For plurals of acronyms or abbreviations, add s. Don't use an apostrophe. Ever. Please.

+ + + +

"Versus", "vs.", and "v."

+ +

The contraction "vs." is preferred.

+ + + +

Capitalization

+ +

Use standard English capitalization rules in body text, and capitalize "World Wide Web." It is acceptable to use lower case for "web" (used alone or as a modifier) and "internet;" this guideline is a change from a previous version of this guide, so you may find many instances of "Web" and "Internet" on MDN. Feel free to change these as you are making other changes, but editing an article just to change capitalization is not necessary.

+ +

Keyboard keys should use sentence-style capitalization, not all-caps capitalization. For example, "Enter" not "ENTER." The only exception is that if you wish to abbreviate the name of the "Escape" key, you may use "ESC".

+ +

Certain words should always be capitalized (such as trademarks which include capital letters), or words derived from the name of a person (unless it's being used within code, and the rules of the language in which the code is written mandate lower-casing). Some examples:

+ + + +

Contractions

+ +

Our writing style tends to be casual, so you should feel free to use contractions (e.g., "don't", "can't", "shouldn't"), if you prefer.

+ +

Pluralization

+ +

Use English-style plurals, not the Latin- or Greek-influenced forms.

+ + + +

Hyphenation

+ +

Hyphenate compounds when the last letter of the prefix is a vowel and is the same as the first letter of the root.

+ + + +

Gender-neutral language

+ +

It is a good idea to use gender-neutral language in any writing where gender is irrelevant to the subject matter, to make the text as inclusive as possible. So, for example, if you are talking about the actions of a specific man, usage of "he"/"his" is fine; but if the subject is a person of either gender, "he"/"his" isn't appropriate.
+
+ Let's take the following example:

+ +
+

A confirmation dialog appears, asking the user if he allows the Web page to make use of his Web cam.

+
+ +
+

A confirmation dialog appears, asking the user if she allows the Web page to make use of her Web cam.

+
+ +

Both versions are gender-specific. To fix this, use gender-neutral pronouns:

+ +
+

A confirmation dialog appears, asking the user if they allow the Web page to make use of their Web cam.

+
+ +
+

MDN allows the use of this very common syntax (which is controversial among usage authorities) to make up for the lack of a neutral gender in English.

+ +

The use of the third-person plural as a gender neutral pronoun (that is, using "they," "them", "their," and "theirs") is an accepted practice, commonly known as "singular 'they.'"

+
+ +

You can use both genders:

+ +
+

A confirmation dialog appears, asking the user if he or she allows the web page to make use of his/her web cam.

+
+ +

Making the users plural:

+ +
+

A confirmation dialog appears, asking the users if they allow the web page to make use of their web cams.

+
+ +

The best solution, of course, is to rewrite and eliminate the pronouns:

+ +
+

A confirmation dialog appears, requesting the user's permission for web cam access.

+
+ +
+

A confirmation dialog box appears, which asks the user for permission to use the web cam.

+
+ +

The last way of dealing with the problem is arguably better. It is not only grammatically more correct, but removes some of the complexity associated with dealing with genders across different languages that may have wildly different gender rules. This solution can make translation easier for both readers and localizers.

+ +

Numbers and numerals

+ +

Dates

+ +

For dates (not including dates in code samples) use the format "January 1, 1990".

+ + + +

Alternately, you can use the YYYY/MM/DD format.

+ + + +

Decades

+ +

For decades, use the format "1990s". Don't use an apostrophe.

+ + + +

Plurals of numerals

+ +

For plurals of numerals add "s". Don't use an apostrophe.

+ + + +

Commas

+ +

In running text, use commas only in five-digit and larger numbers.

+ + + +

Punctuation

+ +

Serial comma

+ +

Use the serial comma. The serial (also known as "Oxford") comma is the comma that appears before the conjunction in a series of three or more items.

+ + + +
+

This is in contrast to the One Mozilla style guide, which specifies that the serial comma is not to be used. MDN is an exception to this rule.

+
+ +

Apostrophes and quotation marks

+ +

Do not use "curly" quotes and quotation marks. On MDN, we only use straight quotes and apostrophes.

+ +

There are a couple of reasons for this.

+ +
    +
  1. We need to choose one or the other for consistency.
  2. +
  3. If curly quotes or apostrophes make their way into code snippets—even inline ones—readers may copy and paste them, expecting them to function (which they will not).
  4. +
+ + + +

Spelling

+ +

For words with variant spellings, always use their American English spelling.

+ +

In general, use the first entry at Dictionary.com, unless that entry is listed as a variant spelling or as being primarily used in a non-American form of English. For example, if you look up "behaviour", you find the phrase "Chiefly British" followed by a link to the American standard form, "behavior". Do not use variant spellings.

+ + + +

Terminology

+ +

HTML elements

+ +

Use "elements" to refer to HTML and XML elements, rather than "tags". In addition, they should almost always be wrapped in "<>", and should be in the {{HTMLElement("code")}} style.

+ +

When you reference a given element for the first time in a section, you should use the {{TemplateLink("HTMLElement")}} macro to create a link to the documentation for the element (unless you're writing within that element's reference document page).

+ + + +

Parameters vs. arguments

+ +

The preferred term on MDN is parameters. Please avoid the term "arguments" for consistency whenever possible.

+ +

User interface actions

+ +

In task sequences, describe user interface actions using the imperative mood. Identify the user interface element by its label and type.

+ + + +

Voice

+ +

While the active voice is preferred, the passive voice is also acceptable, given the informal feel of our content. Try to be consistent, though.

+ +

Wiki markup and usage

+ + + +

Links are a large part of what makes a wiki a powerful learning and teaching tool. Below you'll find some basic information, but you can find a complete guide to creating and editing links on MDN in our editor guide.

+ +

We encourage you to create appropriate links among articles; they help improve navigation and discoverability of content, and they provide important context to search engines like Google to help them provide better results. Every page should have a good set of links from words or phrases to other pages that expand upon the relevant ideas. This can be used both to define terms and to provide more in-depth or detailed documentation about a topic, or to connect to a related page that offers examples or information that may be of further interest.

+ +

You can easily create links not only among pages on MDN (internal links) but also to pages outside MDN (external links).

+ +

There are two ways to create links: you explicitly create a link using the Link button in the editor's toolbar—or by pressing Ctrl+K (Cmd-K on the Mac)—or you can use MDN's powerful macro system to generate links automatically or based on an input value.

+ +

When deciding what text to use as a link, there are a few guidelines you can follow:

+ + + +

URL schemes

+ +

For security reasons, you should only create links that use the following schemes:

+ + + +

Others may or may not work, but are not supported and will probably be removed by editorial staff.

+ +
+

In particular, avoid the about: or chrome:// schemes, as they will not work. Similarly, the javascript: scheme is blocked by most modern browsers, as is jar:.

+
+ +

Page tags

+ +

Tags provide meta information about a page and/or indicate that a page has specific improvements needed to its content. Every page in the wiki should have tags.

+ +

You can find details on tagging in our How to properly tag pages guide.

+ +

The tagging interface lives at the bottom of a page while you're in edit mode, and looks something like this:

+ +

Screenshot of the UX for adding and removing tags on MDN

+ +

To add a tag, click in the edit box at the end of the tag list and type the tag name you wish to add. Tags will autocomplete as you type. Press enter (or return) to submit the new tag. Each article may have as many tags as needed. For example, an article about using JavaScript in AJAX programming might have both "JavaScript" and "AJAX" as tags.

+ +

To remove a tag, just click the little "X" icon in the tag.

+ +

Tagging pages that need work

+ +

In addition to using tags to track information about the documentation's quality and content, we also use them to mark articles as needing specific types of work.

+ +

Tagging obsolete pages

+ +

Use the following tags for pages that are not current:

+ +
+
Junk
+
Use for spam, pages created by mistake, or content that is so bad that it should be deleted. Pages with this tag are deleted from time to time.
+
Obsolete
+
Use for content that is technically superseded, but still valid in context. For example an HTML element that is obsolete in HTML5 is still valid in HTML 4.01. You can also use the {{TemplateLink("obsolete_header")}} macro to put a prominent banner on the topic.
+
Archive
+
Use for content that is technically superseded and no longer useful. If possible, add a note to the topic referring readers to a more current topic. For example, a page that describes how to use the Mozilla CVS repository should refer readers to a current topic on using Mercurial repos. (If no corresponding current topic exists, use the NeedsUpdate tag, and add an explanation on the Talk page.) Pages with the Archive tag are eventually moved from the main content of MDN to the Archive section.
+
+ +

SEO summary

+ +

The SEO summary provides a short description of a page. It will be reported as a summary of the article to robots crawling the site, and will then appear in search results for the page. It is also used by macros that automate the construction of landing pages inside MDN itself. (In other words, it's not just for SEO.)

+ +

By default, the first paragraph of the page is used as the SEO summary. However, you can override this behavior by marking a section with the "SEO summary" style in the WYSIWYG editor.

+ +

Landing pages

+ +

Landing pages are pages at the root of a topic area of the site, such as the main CSS or HTML pages. They have a standard format that consists of three areas:

+ +
    +
  1. A brief (typically one paragraph) overview of what the technology is and how it's used. See {{anch("Writing a landing page overview")}} for tips.
  2. +
  3. A two-column list of links with appropriate headings. See {{anch("Creating a page link list")}} for guidelines.
  4. +
  5. An optional "Browser compatibility" section at the bottom of the page.
  6. +
+ + + +

The link list section of an MDN landing page consists of two columns. These are created using the following HTML:

+ +
<div class="row topicpage-table">
+  <div class="section">
+    ... left column contents ...
+  </div>
+  <div class="section">
+    ... right column contents ...
+  </div>
+</div>
+ +

The left column should be a list of articles, with an <h2> header at the top of the left column explaining that it's a list of articles about the topic (e.g., "Documentation and tutorials about foo"); this header should use the CSS class "Documentation". Below that is a <dl> list of articles with each article's link in a <dt> block and a brief one-or-two sentence summary of the article in the corresponding <dd> block.

+ +

The right column should contain one or more of the following sections, in order:

+ +
+
Getting help from the community
+
This should provide information on Matrix chat rooms and mailing lists available on the topic. The heading should use the class "Community".
+
Tools
+
A list of tools the user can look at to help with the use of the technology described in this section of MDN. The heading should use the class "Tools".
+
Related topics
+
A list of links to landing pages for other, related, technologies of relevance. The heading should use the class "Related_Topics".
+
+ +

{{TODO("Finish this once we finalize the landing page standards")}}

+ +

Using and inserting images

+ +

It's sometimes helpful to provide an image in an article you create or modify, especially if the article is very technical. To include an image:

+ +
    +
  1. Before uploading your image, please ensure that it's as small as possible by using an image optiization tool. +
      +
    1. For bitmap images (JPG or PNG), consider a tool such as ImageOptim (macOS), TinyPNG (web service), or Trimage (Linux).
    2. +
    3. For SVG images, use the svgo tool to optimize the SVG file before sending it. The default configuration is fine.
    4. +
    +
  2. +
  3. Attach the desired image file to the article (at the bottom of every article in edit mode). If your artwork is a diagram in SVG format (which is ideal if there is text that may need to be localized), you can't upload it directly, but you can ask an MDN admin to do it for you.
  4. +
  5. Click the "insert image" button in the MDN documentation WYSIWYG editor.
  6. +
  7. In the WYSIWYG editor, in the drop-down list of attachments, select the newly created attachment that is your image.
  8. +
  9. Press OK.
  10. +
+ +
+

Important: Remember to save any changes you've made before uploading an attachment to your article! The editor is closed during the upload process, and currently does not verify whether or not you wish to save your work when it does so.

+
+ +

Other references

+ +

Preferred style guides

+ +

If you have questions about usage and style not covered here, we recommend referring to the Microsoft Writing Style Guide or, failing that, the Chicago Manual of Style. An unofficial crib sheet for the Chicago Manual of Style is available online.

+ +

Preferred dictionary

+ +

For questions of spelling, please refer to Dictionary.com. The spelling checker for this site uses American English. Please do not use variant spellings (e.g., use color rather than colour).

+ +

We will be expanding the guide over time, so if you have specific questions that aren't covered in this document, please post them on the MDN discussion forum, so we know what should be added.

+ +

MDN-specific

+ + + +

Language, grammar, spelling

+ +

If you're interested in improving your writing and editing skills, you may find the following resources to be helpful.

+ + diff --git a/files/id/mdn/index.html b/files/id/mdn/index.html new file mode 100644 index 0000000000..3d34d67796 --- /dev/null +++ b/files/id/mdn/index.html @@ -0,0 +1,46 @@ +--- +title: The MDN project +slug: MDN +tags: + - Landing + - MDN + - MDN Meta +translation_of: MDN +--- +
+

Pink or blue: what color choice for her wedding evening dress

+ +

The wedding party dresses are a class of outfits that impress with their richness and variety of models they offer. However, if there is one criterion that determines the choice of evening dress for women, it is the color. It is first she who catches the eye before any interest is paid to other details. When it comes to colors, the same wealth of possibilities can be observed at marriage. However, there are two colors that have charm and are a true expression of femininity; pink and blue.

+ +

If you want to buy khaadi pret dresses and khaadi latest summer dresses you can visit online Khaadi sale. They offer the latest eid collection and summer lawn dresses collection with good quality.

+ +

 Suki Waterhouse in a pink wedding dress & Bradley Cooper

+ +

 Pink and blue are colors that have charm in common, although each has its own characteristics. The pink evening dress is a piece that makes the difference at first sight, because of its hue. Color symbolizing romanticism, pink brings to your style, an effect of novelty and more radiance. Attractive, it seduces the eye and commands admiration. Therefore, the pink wedding dress, therefore, represents a distinguished option, which adapts to various forms of evening dresses, to allow you to be as radiant as possible. Thus, it can be short and stand out through details and embellishments, as it can belong, low-cut, open back, or openwork. It should still be noted that these multiple options of evening wear all guarantee you a clean and elegant look.

+ +

Gul Ahmed sale offers the latest dress design with good quality if you want to buy these dresses you can visit at an online store.

+ +

Jennifer Lawrence simple blue dress for wedding

+ +

 For its part, blue is one of the most popular colors for evening dresses. The wedding evening dress in blue is a refined choice, imbued with visibility and expression. It is well suited for flaunting since it sublimates your appearance by making you shine. It is characterized by the many variations in which it is available, ranging from royal blue to dark blue, not to mention pale blue. This same diversity applies to the shapes of the wedding party dress which can also be short and sexy, long and tight, decorated with rhinestones, sequins, or other embellishments according to preference. The blue evening dress ensures you a perfect and elegant outfit, with a sensual or luxurious tone depending on the model.

+ +

 Pink V-neck dress & blue vintage wedding party dress

+ +

 So, pink or blue? Opinions will certainly differ, although in either case, you will have sported an authentic and sumptuous outfit. On robespourmariage.fr, the midnight blue princess evening dress with V-neck back and guipure lace applied and the sexy pink dress with a plunging neckline are able to guide your choice.

+ +

The gray evening dress: as remarkable as it is unnoticed

+ +

A good time, a good atmosphere, and what could be better than being well undermined. For the occasion, we want to be on our 31. So the fateful question of what to wear begins to trot in the head. As soon as you decide on a gray evening dress, there are still several questions. What model, what cut, what material, what accessories and adornments, and above all that color of the dress to wear. What if we decided on a gray dress? Bland, who told you such nonsense! Did you not know that the trend is gray? Highlighted properly, it eclipses all other colors. 

+ +

A mixture of black and white, it is an interesting alternative for lovers of black & white. Know that with your gray dress, you will be of the sexiest refinement. Gray is suitable for all women regardless of their skin color. It is a neutral color to which we give the desired shine. There are several shades of it from the lightest to the darkest. So you have the possibility to choose your evening dress for weddings ranging from pearl gray to metallic gray. The materials in which it is found are numerous, each bringing its own touch to color. If you choose a maxi dress in silky satin or silk, the shine effect is more than guaranteed, especially since the gray hangs well in the light. Rather a dress in chiffon, lace, here implies a play of transparency of majestic softness.

+ +

Chic gray fluid dress Kate Middleton asymmetric style

+ +

The gray wedding dress is not just wintery, as we often think. Although so much whiteness contrasts very well with it, it goes well in all seasons, well in both hot and cool weather. To go to a party during the spring-summer, you could opt for a short gray dress in silk or satin strapless or with straps. Sheath or ballerina according to the desire of each one. A great choice for a slim person. If you want to go lengthwise, a clean fabric such as lace, tulle, or muslin, for an empire, mermaid, or duchess cut. Fall-winter, we will focus on volume, why not a gray velvet dress, mermaid cut, or a satin dress with a sumptuous drape with long sleeves and a play of transparency.

+ +

In terms of accessories, you should know that gray is very suitable for other colors but should not be overshadowed. If your dress is not already adorned with rhinestones, beading, sequins, and more, then adornments that add sparkle would be welcome. Clutch and shoe will probably match, black, white, or why not a total gray look.

+ +

Gray evening dresses the short strapless A-line heart-shaped evening dress adorned with strapless rhinestones or the pleated & appliquéd evening dress with illusion collar; yes muslin, vaporous materials are in vogue. Greek goddess or princess, that's what these two models inspire. Both in the same style, yet the first a dark ash gray and the second a very light gray. The difference is also at the level of the asymmetrically decorated bustier for the second and stepped for the first. On the online store of robespourmariage.fr, you can customize them.

+ + +
diff --git a/files/id/mdn/komunitas/conversations/index.html b/files/id/mdn/komunitas/conversations/index.html new file mode 100644 index 0000000000..d39080c8a3 --- /dev/null +++ b/files/id/mdn/komunitas/conversations/index.html @@ -0,0 +1,56 @@ +--- +title: MDN community conversations +slug: MDN/Komunitas/Conversations +tags: + - Komunitas + - MDN Meta + - Panduan +translation_of: MDN/Community/Conversations +--- +
{{MDNSidebar}}

"Pekerjaan" dari MDN terjadi di situs MDN, tetapi "Komunitas" juga juga melakukannya melalui diskusi (tidak tersinkronisasi) dan chatting serta meeting (tersinkronisasi)

+ +

Diskusi Tidak Tersinkronisasi

+ +

Untuk berbagi informasi dan berdiskusi, MDN memiliki kategori sendiri ("MDN") di forum Wacana Mozilla. Gunakan kategori ini untuk semua topik yang terkait dengan MDN, termasuk pembuatan konten dokumentasi, terjemahan, dan perawatan; Pengembangan platform MDN; Dan perencanaan, penetapan tujuan, dan pelacakan kemajuan.

+ + + +

Arsip sejarah

+ +

Sebelum Juni 2017, diskusi terkait MDN berlangsung dalam daftar surat yang dikirimkan dan diarsipkan dengan kelompok Google. Jika Anda ingin mencari diskusi terakhir ini, Anda dapat melihat grup Google yang sesuai dengan milis lama. (Ya, kita tahu nama-nama ini tumpang tindih dan membingungkan. Kecelakaan pada masa sebelumnya. maafkan hal ini.)

+ +
+
mozilla.dev.mdc a.k.a. dev-mdc
+
Daftar ini untuk diskusi tentang konten dokumentasi di MDN.
+
mozilla.dev.mdn a.k.a. dev-mdn
+
Daftar ini adalah tentang pengembangan pekerjaan pada platform Kuma yang mendasari MDN.
+
mozilla.mdn a.k.a mdn@
+
Forum ini untuk diskusi perencanaan dan prioritas tingkat tinggi, untuk situs web MDN dan prakarsa terkait lainnya.
+
+ +

Obrolan di IRC

+ +

Internet Relay Chat (IRC) adalah Metode yang kami pilih untuk obrolan harian dan diskusi real-time antar anggota komunitas. Kami menggunakan beberapa saluran (channel) pada irc.mozilla.org server untuk diskusi terkait dengan MDN.

+ +
+
#mdn
+
channel ini adalah channel utama kami untuk mendiskusikan konten MDN. Kami berbicara tentang menulis, mengatur konten, dan sebagainya. Kami juga memiliki percakapan "water cooler" disini - Ini adalah cara komunitas kami tetap terhubung atau sekedar hang out. Ini juga merupakan tempat untuk berbicara tentang aspek-aspek lain dari MDN (selain pengembangan platform), seperti Demo Studio, profil, dan sebagainya
+
#mdndev
+
Channel ini adalah di mana tim pengembang kami - orang yang menulis kode atau yang membuat MDN bekerja - hang out dan membahas pekerjaan mereka sehari-hari. Kamu dipersilakan untuk bergabung dan berpartisipasi dalam pengembangan atau hanya bertanya tentang masalah yang kamu lihat tentang software
+
+ +

Channel ini sangat aktif selama hari kerja di Amerika Utara.

+ +

Anda mungkin ingin mempelajari lebih lanjut tentang IRC dan menggunakan instalan IRC client seperti ChatZilla. Hal ini dijalankan sebagai Firefox add-on, yang membuatnya cepat dan mudah untuk menginstal dan menggunakan. Jika Anda tidak terbiasa dengan IRC, cara mudah untuk bergabung menggunakan klien IRC berbasis web seperti scrollback, yang merupakan pra-dikonfigurasi dengan mdn dan mandev saluran.

+ +

Join our meetings (and other events)

+ +

The MDN team holds a number of regular meetings that are open to the MDN community. See the MDN Meetings page on the Mozilla wiki for details on the schedule, agendas and notes, and info on how to join.

+ +

See the MDN Events calendar for these and other meetings, local meetups, and other events. The recurring meetings are summarized on the MDN Meetings wiki page.

+ +

See the MDN Events calendar for these and other meetings, doc sprints, and other events. The recurring meetings are summarized on the MDN Meetings wiki page.

diff --git a/files/id/mdn/komunitas/index.html b/files/id/mdn/komunitas/index.html new file mode 100644 index 0000000000..a60c631f76 --- /dev/null +++ b/files/id/mdn/komunitas/index.html @@ -0,0 +1,75 @@ +--- +title: Gabung di Komunitas MDN +slug: MDN/Komunitas +translation_of: MDN/Community +--- +
{{MDNSidebar}}
{{IncludeSubnav("/en-US/docs/MDN")}}
+ +

Ringkasan

+ +
+

MDN (yang merupakan singkatan dari jaringan pengembang Mozilla) lebih dari wiki: Ini adalah komunitas pengembang bekerja sama untuk membuat MDN sumber daya yang luar biasa bagi para pengembang yang menggunakan teknologi Web terbuka. "Pekerjaan" yang terjadi di situs MDN, tapi "komunitas" juga terjadi melalui (asynchronous) diskusi dan (sinkron) chat online.

+
+ +

Kami akan senang jika kamu berkonstribusi di MDN, tapi kami akan lebih senang jika kamu berpartisipasi didalam komunitas MDN. Berikut adalah cara untuk bisa terhubung, ada tiga langkah mudah:

+ +
    +
  1. Buat akun MDN.
  2. +
  3. Berlangganan diskusi dev-mdc.
  4. +
  5. masuk ke IRC.
  6. +
+ +

Buat akun MDN

+ +

{{page("/en-US/docs/MDN/Contribute/Howto/Create_an_MDN_account") }}

+ +

Bergabung milis kami

+ +

untuk berbagi informasi dan memiliki diskusi yang sedang berlangsung, Mozilla memilki beberapa milis yang berguna. Berikut yang khusus untuk MDN adalah:

+ +
+
dev-mdc
+
Daftar ini adalah di mana kita memiliki diskusi yang sedang berlangsung tentang dokumentasi di MDN. Kami berbicara tentang perubahan proses, perbaikan yang kami buat, dan kami memilah-milah siapa yang ingin bekerja di mana konten. Ini sangat disarankan agar Anda bergabung di daftar ini jika Anda tertarik serius menyelam ke dokumentasi di MDN!
+
dev-mdn
+
Daftar ini adalah di mana kita memegang diskusi tentang pekerjaan pengembangan pada platform Kuma yang mendasari MDN ini. Jika anda penasaran tentang pekerjaan pengembangan yang terjadi di belakang layar, ingin terlibat dalam proses pembuatan decsisions tentang platform, atau bekerja pada patch untuk memperbaiki platform, Anda pasti harus terlibat dalam daftar ini.
+
mdn-drivers
+
Milis ini digunakan untuk membantu memutuskan prioritas pengembangan MDN. ini umumnya digunakan untuk diskusi apa yang harus dikerjakan selanjutnya, dan di mana kami pergi untuk menarik perhatian tim pengembangan ketika sebuah masalah serius perlu diperbaiki, setelah kita mengajukan bug untuk masalah ini.
+
+ +

Ada juga beberapa daftar khusus untuk masyarakat lokalisasi MDN. Jika komunitas anda sangat besar dan aktif, anda mungkin bisa mendapatkan daftar dibuat untuk komunitas anda; hanya meminta kami dan kami akan melihat ke dalamnya. Saat ini, bahasa ini memiliki daftar: Spanyol, Jepang dan Portugis.

+ +

Mengapa "dev-mdc"? Di masa lalu, ini dikenal sebagai "Mozilla Developer Center", atau MDC. Milis berawal dari masa itu, jadi dev-mdc. Ada juga dev-mdn mailing list, yaitu untuk diskusi tentang pengembangan platform Kuma yang MDN berjalan pada. Anda dipersilakan untuk bergabung itu juga, tapi itu tidak diperlukan jika Anda hanya tertarik pada konten MDN.

+ +

Masuk ke IRC

+ +

Internet Relay Chat (IRC) adalah metode pilihan untuk hari-hari chatting dan waktu nyata diskusi di antara anggota masyarakat. Kami menggunakan beberapa saluran pada irc.mozilla.org server untuk diskusi yang berkaitan dengan MDN.

+ +
+
#mdn
+
Saluran ini merupakan saluran utama untuk mendiskusikan konten MDN. Kami membahas tentang tulisan, organisasi konten dan sebagainya. Kami juga memiliki "air pendingin" dalam percakapan kami di sini - sebagai cara komunitas kami berbagi dan saling berhubungan. Juga sebagai tempat untuk membicarakan  aspek lain dari MDN (lebih dari pengembangan platform), semisal Studio Tampil, profile dan sebagainya.
+
#mdndev
+
Saluran ini adalah di mana tim-pengembangan kami orang yang menulis kode yang membuat MDN kerja-hang out dan membahas pekerjaan mereka sehari-hari. Anda dipersilakan untuk bergabung dan baik berpartisipasi dalam pembangunan atau hanya bertanya tentang masalah yang Anda lihat dengan perangkat lunak.
+
+ +

Saluran ini yang paling mungkin untuk menjadi aktif selama hari kerja di Amerika Utara.

+ +

Jika Anda tidak terbiasa dengan IRC, Cara tercepat untuk bergabung menggunakan Scrollback - a web-based IRC client yang pra-dikonfigurasi dengan mdn dan mdndev channel. Anda juga mungkin ingin Belajar tentang IRC dan menggunakan IRC client diinstal seperti ChatZilla. Hal ini dilaksanakan sebagai Firefox add-on, yang membuatnya cepat dan mudah untuk menginstal dan menggunakan.

+ +

Join our biweekly meetings (and other events)

+ +

Every other week, the MDN community holds an IRC-based meeting to exchange notes, talk about what we've been doing, and sort out what we'd like to do for the next two weeks. We also talk about development plans for the MDN platform itself, and often get updates about new and upcoming features of the site. These are casual, fun meetings, and everyone's welcome to participate.

+ +

See the MDN Community Meetings page on the Mozilla wiki for details on the schedule as well as agendas and notes for past and upcoming meetings.

+ +

See the MDN Events calendar for these and other meetings, doc sprints, and other events.

+ +

Project administrators

+ +

kamu dapat menghubungi MDN project administrator melalui email. BIla kamu ingin berbicara dengan pemimpin MDN documentation, ia bernama {{UserLink("Sheppy", "Eric Shepherd")}}, dan ia senang untuk menjawab pertanyaan yang kamu ajukan, atau membantu mencarikan orang yang lebih tepat.

+ +

Langkah Berikutnya

+ + diff --git a/files/id/mdn/user_guide/index.html b/files/id/mdn/user_guide/index.html new file mode 100644 index 0000000000..b2e20cd131 --- /dev/null +++ b/files/id/mdn/user_guide/index.html @@ -0,0 +1,13 @@ +--- +title: MDN user guide +slug: MDN/User_guide +tags: + - Documentation + - Landing + - MDN + - NeedsTranslation + - TopicStub +translation_of: MDN/Tools +--- +
{{MDNSidebar}}

The Mozilla Developer Network site is an advanced system for finding, reading, and contributing to documentation and sample code for Web developers (as well as for Firefox and Firefox OS developers). The MDN user guide provides articles detailing how to use MDN to find the documentation you need, and, if you wish, how to help make the material better, more expansive, and more complete.

+

{{SubpagesWithSummaries}}

diff --git a/files/id/mdn/user_guide/menghapus_halaman/index.html b/files/id/mdn/user_guide/menghapus_halaman/index.html new file mode 100644 index 0000000000..df0ba8ef81 --- /dev/null +++ b/files/id/mdn/user_guide/menghapus_halaman/index.html @@ -0,0 +1,17 @@ +--- +title: Menghapus Halaman +slug: MDN/User_guide/Menghapus_halaman +tags: + - MDN + - Panduan + - Proyek MDC +translation_of: MDN/Tools/Page_deletion +--- +
{{MDNSidebar}}

Hanya Admin MDN yang bisa menghapus halaman. Artikel ini menjelaskan bagaimana meminta halaman yang dihapus dari MDN.

+

Untuk menyusun halaman yang ingin dihapus, Anda harus mengikuti cara berikut:

+
    +
  1. Jangan hapus atau mengganti konten dari halaman. Kami ingin memiliki catatan dari halaman seperti pertama dihapus.
  2. +
  3. Tambahkan label "sampah" di halaman tersebut. Jangan hapus label lainnya.
  4. +
  5. Jika halaman tersebut sangat mendesak untuk segera dihapus (Sebagai contoh, konten berisi hal yang tidak sopan, penghinaan, atau secara teknis berbahaya), beritahukan pada admin MDN.
  6. +
+

Admin akan menghapus halaman tersebut jika memungkinkan, setelah mengkonfirmasi bahwa penghapusan tersebut boleh dilakukan.

diff --git a/files/id/mozilla/add-ons/index.html b/files/id/mozilla/add-ons/index.html new file mode 100644 index 0000000000..f25d110860 --- /dev/null +++ b/files/id/mozilla/add-ons/index.html @@ -0,0 +1,16 @@ +--- +title: Add-ons +slug: Mozilla/Add-ons +translation_of: Mozilla/Add-ons +--- +

{{AddonSidebar}}

+ +

Add-ons Menambah fungsi baru pada aplikasi berbasis Gecko seperti Firefox, SeaMonkey dan Thunderbird. Ada dua jenis "add-on" :  Extensions menambahkan fitur ke aplikasi, sedangkan Tema merubah tampilan pada aplikasi.

+ +

Keduanya (Extention, dan Tema) ditemukan dalam addons.mozilla.org, dikenal juga sebagai AMO. Ketika Anda masukan add-ons ke AMO mereka meninjau, dan setelah melewati tinjauan maka mereka menyajikan untuk pengguna. Anda tidak harus masukan add-on ke AMO, tetapi anda lakukan, pengguna dapat menaruh keyakinan bahwa mereka telah ditinjau, dan Anda dapat keuntungan dari visibilitas AMO sebagai sumber add-on yang berguna.

+ +

Add-ons dapat mempengaruhi perilaku aplikasi host mereka. Kami telah membangun sekumpulan panduan untuk membantu memastikan bahwa mereka telah didukung mendapatkan pengalaman yang baik pada pengguna. Panduan ini digunakan untuk beberapa add-on, apakah mereka juga ditaruh di addons.mozilla.org atau tidak.

+ +

Extentions

+ +

Extention menambah fungsi dari aplikasi Mozzila seperti Firefox dan Thunderbird. Extension dapat menambahkan fitur pada peramban, seperti mengatur tab, dan mereka dapat merubah konten web untuk meningkatkan pengguanan atau keamanan website tertentu.

diff --git a/files/id/mozilla/add-ons/setting_up_extension_development_environment/index.html b/files/id/mozilla/add-ons/setting_up_extension_development_environment/index.html new file mode 100644 index 0000000000..6519e6752d --- /dev/null +++ b/files/id/mozilla/add-ons/setting_up_extension_development_environment/index.html @@ -0,0 +1,167 @@ +--- +title: Setting up an extension development environment +slug: Mozilla/Add-ons/Setting_up_extension_development_environment +translation_of: Archive/Add-ons/Setting_up_extension_development_environment +--- +

This article gives suggestions on how to set up your Mozilla application for extension development. Unless otherwise specified, these suggestions apply to both Firefox and Thunderbird as well as SeaMonkey version 2.0 and above.

+ +

Overview

+ + + +

Development profile

+ +

To avoid performance degradation from development-related prefs and extensions, and to avoid losing your personal data, you can use a separate profile for development work.

+ +

You can run two instances of Thunderbird or Firefox at the same time by using separate profiles and starting the application with parameters -no-remote and -P ProfileName. For example, the following command will start Firefox with a profile called "dev" whether an instance of Firefox is already running or not. (If there is no "dev" user yet, you'll get the profile selection screen instead, where you can create one.)

+ +

On Ubuntu (and many other Linux distributions):

+ +
/usr/bin/firefox -no-remote -P dev
+ +

On some other distributions of Linux/Unix:

+ +
/usr/local/bin/firefox -no-remote -P dev
+
+ +

On Mac OS Snow Leopard (10.6) and newer:

+ +
/Applications/Firefox.app/Contents/MacOS/firefox-bin -no-remote -P dev &
+
+ +

On Mac OS Leopard (10.5) and older, you must request the 32-bit portion of the Universal Binary (https://bugzilla.mozilla.org/show_bug.cgi?id=622970):

+ +
arch -arch i386 /Applications/Firefox.app/Contents/MacOS/firefox-bin -no-remote -P dev &
+
+ +

On Windows:

+ +
Start -> Run "%ProgramFiles%\Mozilla Firefox\firefox.exe" -no-remote -P dev
+
+ +

On Windows 64 bit:

+ +
Start -> Run "%ProgramFiles(x86)%\Mozilla Firefox\firefox.exe" -no-remote -P dev
+ +

To start Thunderbird or SeaMonkey instead of Firefox, substitute "thunderbird" or "seamonkey" for "firefox" in the examples above.

+ +

Note that you can run Firefox using your regular profile while developing.

+ +

Parameter -P ProfileName doesn't imply -no-remote, therefore use them together. Otherwise, if you already run a Firefox instance without -no-remote, and you attempt to start another instance with -P ProfileName but again without -no-remote, that second invocation would ignore its -P ProfileName parameter, but instead it would open a new blank window for the already running instance (sharing its profile, sessions etc.).

+ +

(There is a thread in the Mozillazine forums that explains how to use both stable and development versions of Firefox to check extension compatibility. See Installing Firefox 3 or Minefield while keeping Firefox 2.)

+ +

Development command flags

+ +

As of Gecko 2 (Firefox 4), JavaScript files are cached ("fastload"). The -purgecaches command-line flag disables this behavior. Alternatively, you can set the MOZ_PURGE_CACHES environment variable. See this bug for more information.

+ +

Development preferences

+ +

There is a set of development preferences that, when enabled, allows you to view more information about application activity, thus making debugging easier. However,  these preferences can degrade performance, so you may want to use a separate development profile when you enable these preferences.

+ +

Accessing Firefox development preferences

+ +

To change preference settings in Firefox or SeaMonkey, type about:config in the Location Bar. You can also use the Extension Developer's Extension, which provides a menu interface for Firefox settings. Alternatively, install the Developer Profile to set the preferences listed below and skip the rest of this section.

+ +

Accessing Thunderbird development preferences

+ +

To change preference settings in Thunderbird, open the "Preferences" (Unix) or "Options" (Windows) interface. On the "Advanced" page, select the "General" tab then click the "Config Editor" button.

+ + + +

Not all preferences are defined by default, and are therefore not listed by default. You will have to create new (boolean) entries for them. For more information about Mozilla preferences, refer to the mozillaZine article on "about:config". (Tip: Download addon DevPrefs, it will automatically handle this)

+ + + +

Never set {{pref("nglayout.debug.disable_xul_fastload")}} to true in a production environment; it exists solely to aid in debugging. In particular, add-ons should never change this preference.
.

+ +
+

Note:The Error Console is disabled by default starting in {{Gecko("2.0")}}. You can re-enable it by changing the devtools.errorconsole.enabled preference to true and restarting the browser. With this, javascript.options.showInConsole is also set to true by default.

+
+ +
+

Tip: Download the addon DevPrefs from AMO to automatically configure the preferences.

+
+ +

Development extensions

+ +

These extensions may help you with your development.

+ + + +

Firefox extension proxy file

+ +

Extension files are normally installed in the user profile. However, it is usually easier to place extension files in a temporary location, which also protects source files from accidental deletion. This section explains how to create a proxy file that points to an extension that is installed in a location other than the user profile.

+ +
    +
  1. Get the extension ID from the extension's install.rdf file.
  2. +
  3. Create a file in the "extensions" directory under your profile directory with the extension's ID as the file name (for example "your_profile_directory/extensions/{46D1B3C0-DB7A-4b1a-863A-6EE6F77ECB58}"). (How to find your profile directory) Alternatively, rather than using a GUID, create a unique ID using the format "name@yourdomain" (for example chromebug@mydomain.com) - then the proxy filename will be same as that ID, with no curly brackets {}.
  4. +
  5. +

    The contents of this file should be the path to the directory that contains your install.rdf file, for example /full/path/to/yourExtension/ on Mac and Linux, and C:\full\path\to\yourExtension\ on Windows. Remember to include the closing slash and remove any trailing whitespace.

    + +
      +
    • Note: If you already installed the extension via XPI, you should uninstall it first before creating the pointer file.
    • +
    • Also note that the use of proxy files requires that the extension's chrome.manifest defines its chrome urls using traditional directories, rather than a JARed structure. See below.
    • +
    +
  6. +
  7. Place the file in the extensions folder of your profile and restart the application.
  8. +
+ +

Using directories rather than JARs

+ +

Regardless of whether you choose to eventually package your extension's chrome in a JAR or in directories, developing in directories is simpler. If you choose a JARed structure for releasing, you can still develop with a directory structure by editing your chrome.manifest. For example, rather than having

+ +
content	myExtension	jar:chrome/myExtension.jar!/content/
+
+ +

use

+ +
content	myExtension	chrome/content/
+
+ +

{{ h1_gecko_minversion("Preventing the first launch extension selector", "8.0") }}

+ +

Starting in Firefox 8, on the first launch of a new version of Firefox, it presents user interface letting users select which third party add-ons to keep. This lets them weed out add-ons that were installed without their knowledge, or that are no longer needed.

+ +

However, this interface can be disruptive when debugging add-ons. You can avoid this by setting the preference extensions.autoDisableScopes to 14.

+ +

{{ languages( { "de": "de/Einrichten_einer_Entwicklungsumgebung_für_Erweiterungen", "fr": "fr/Configuration_d'un_environnement_de_développement_d'extensions", "ja": "ja/Setting_up_extension_development_environment", "zh-cn": "cn/Setting_up_extension_development_environment", "pl": "pl/Przygotowanie_środowiska_programowania_rozszerzenia", "ru": "ru/Настройка_среды_разработки_расширений" } ) }}

diff --git a/files/id/mozilla/add-ons/webextensions/apa_itu_webextensions/index.html b/files/id/mozilla/add-ons/webextensions/apa_itu_webextensions/index.html new file mode 100644 index 0000000000..63c093bc53 --- /dev/null +++ b/files/id/mozilla/add-ons/webextensions/apa_itu_webextensions/index.html @@ -0,0 +1,34 @@ +--- +title: Apa itu WebExtensions? +slug: Mozilla/Add-ons/WebExtensions/Apa_Itu_WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions +--- +
{{AddonSidebar}}
+ +

Add-ons memperluas dan memodifikasi fungsi dari web browser. Mereka ditulis menggunakan teknologi Web standar - JavaScript, HTML, dan CSS - ditambah beberapa API JavaScript. Antara lain, add-ons dapat menambahkan fitur baru untuk browser atau mengubah tampilan atau konten dari situs web tertentu.

+ +

WebExtensions adalah sistem cross-browser untuk mengembangkan browser add-ons. Untuk sebagian besar API tersebut kompatibel dengan ekstensi API yang didukung oleh Google Chrome dan Opera. Ekstensi ditulis untuk browser ini dalam banyak kasus akan berjalan di Firefox atau Microsoft Edge hanya dengan beberapa perubahan. API ini juga sepenuhnya kompatibel dengan multiprocess Firefox.

+ +

Kami juga berniat untuk memperpanjang API untuk mendukung kebutuhan para pengembang, jadi jika Anda memiliki ide, kami akan senang mendengar mereka. Anda dapat menghubungi kami dev-addons mailing list atau #webextensions di IRC.

+ +

Sebelum WebExtensions, Anda bisa mengembangkan Firefox add-ons menggunakan salah satu dari tiga sistem yang berbeda: XUL/XPCOM overlays, bootstrapped extensions, atau Add-on SDK. Di masa depan, WebExtensions akan menjadi cara yang direkomendasikan untuk mengembangkan add-ons pada Firefox, dan sistem lainnya akan dihentikan.

+ +

Apa berikutnya?

+ + diff --git a/files/id/mozilla/add-ons/webextensions/api/browsersettings/index.html b/files/id/mozilla/add-ons/webextensions/api/browsersettings/index.html new file mode 100644 index 0000000000..2372f738e0 --- /dev/null +++ b/files/id/mozilla/add-ons/webextensions/api/browsersettings/index.html @@ -0,0 +1,63 @@ +--- +title: browserSettings +slug: Mozilla/Add-ons/WebExtensions/API/browserSettings +translation_of: Mozilla/Add-ons/WebExtensions/API/browserSettings +--- +
{{AddonSidebar}}
+ +
Enables an extension to modify certain global browser settings. Each property of this API is a {{WebExtAPIRef("types.BrowserSetting", "BrowserSetting")}} object, providing the ability to modify a particular setting.
+ +
+ +
Because these are global settings, it's possible for extensions to conflict. See the documentation for BrowserSetting.set() for details of how conflicts are handled.
+ +
+ +
+

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

+
+ +

Properties

+ +
+
{{WebExtAPIRef("browserSettings.allowPopupsForUserEvents")}}
+
Determines whether code running in web pages can display popups in response to user events.
+
{{WebExtAPIRef("browserSettings.cacheEnabled")}}
+
Determines whether the browser cache is enabled or not.
+
{{WebExtAPIRef("browserSettings.closeTabsByDoubleClick")}}
+
Determines whether the selected tab can be closed with a double click.
+
{{WebExtAPIRef("browserSettings.contextMenuShowEvent")}}
+
Determines the mouse event that triggers a context menu popup.
+
{{WebExtAPIRef("browserSettings.ftpProtocolEnabled")}}
+
Determines whether the FTP protocol is enabled.
+
{{WebExtAPIRef("browserSettings.homepageOverride")}}
+
Read the value of the browser's home page.
+
{{WebExtAPIRef("browserSettings.imageAnimationBehavior")}}
+
Determines how the browser treats animated images.
+
{{WebExtAPIRef("browserSettings.newTabPageOverride")}}
+
Reads the value of the browser's new tab page.
+
{{WebExtAPIRef("browserSettings.newTabPosition")}}
+
Controls the position of newly opened tabs relative to already open tabs.
+
{{WebExtAPIRef("browserSettings.openBookmarksInNewTabs")}}
+
Determines whether bookmarks are opened in the current tab or a new tab.
+
{{WebExtAPIRef("browserSettings.openSearchResultsInNewTabs")}}
+
Determines whether search results are opened in the current tab or a new tab.
+
{{WebExtAPIRef("browserSettings.openUrlbarResultsInNewTabs")}}
+
Determines whether address bar autocomplete suggestions are opened in the current tab or a new tab.
+
{{WebExtAPIRef("browserSettings.overrideDocumentColors")}}
+
Controls whether the user-chosen colors override the page's colors.
+
{{WebExtAPIRef("browserSettings.useDocumentFonts")}}
+
Controls whether the browser will use the fonts specified by a web page or use only built-in fonts.
+
{{WebExtAPIRef("browserSettings.webNotificationsDisabled")}}
+
Prevents websites from showing notifications using the Notification Web API.
+
{{WebExtAPIRef("browserSettings.zoomFullPage")}}
+
Controls whether zoom is applied to the entire page or to text only.
+
{{WebExtAPIRef("browserSettings.zoomSiteSpecific")}}
+
Controls whether page zoom is applied on a per-site or per-tab basis. If {{WebExtAPIRef("privacy.websites")}}.resistFingerprinting is true, this setting has no effect and zoom is applied on a per-tab basis.
+
+ +

Browser compatibility

+ +

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

+ +

{{WebExtExamples("h2")}}

diff --git a/files/id/mozilla/add-ons/webextensions/api/index.html b/files/id/mozilla/add-ons/webextensions/api/index.html new file mode 100644 index 0000000000..9b63bd59e8 --- /dev/null +++ b/files/id/mozilla/add-ons/webextensions/api/index.html @@ -0,0 +1,50 @@ +--- +title: JavaScript APIs +slug: Mozilla/Add-ons/WebExtensions/API +tags: + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Add-ons/WebExtensions/API +--- +
{{AddonSidebar}}
+ +
+

The WebExtension JavaScript APIs can be used inside the add-on's background scripts and in any browser action or page action popups that the add-on defines. A few of these APIs can also be accessed by an add-on's content scripts (see the list in the content script guide).

+ +

To use the more powerful APIs you need to request permission in your add-on's manifest.json.

+ +

You can access the APIs using the browser namespace:

+ +
function logTabs(tabs) {
+  console.log(tabs);
+}
+
+browser.tabs.query({currentWindow: true}, logTabs);
+
+ +
+

Many of the APIs are asynchronous, returning a Promise:

+ +
function logCookie(c) {
+  console.log(c);
+}
+
+function logError(e) {
+  console.error(e);
+}
+
+var setCookie = browser.cookies.set(
+  {url: "https://developer.mozilla.org/"}
+);
+setCookie.then(logCookie, logError);
+
+ +
+

Note that this is different from Google Chrome's extension system, which uses the chrome namespace instead of browser, and which uses callbacks instead of promises for asynchronous functions. As a porting aid, the Firefox implementation of WebExtensions supports chrome and callbacks as well as browser and promises. Mozilla has also written a polyfill which enables code that uses browser and promises to work unchanged in Chrome: https://github.com/mozilla/webextension-polyfill.

+ +

Microsoft Edge uses the browser namespace, but doesn't yet support promise-based asynchronous APIs. In Edge, for the time being, asynchronous APIs must use callbacks.

+ +

Not all browsers support all the APIs: for the details, see Browser support for JavaScript APIs.

+
+ +
{{SubpagesWithSummaries}}
diff --git a/files/id/mozilla/add-ons/webextensions/api/notifikasi/index.html b/files/id/mozilla/add-ons/webextensions/api/notifikasi/index.html new file mode 100644 index 0000000000..e4fb084bb2 --- /dev/null +++ b/files/id/mozilla/add-ons/webextensions/api/notifikasi/index.html @@ -0,0 +1,62 @@ +--- +title: notifikasi +slug: Mozilla/Add-ons/WebExtensions/API/notifikasi +tags: + - API + - Add-ons + - Ekstensi + - Notifikasi + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/API/notifications +--- +
{{AddonSidebar}}
+ +

Tampilkan pemberitahuan kepada pengguna, menggunakan mekanisme pemberitahuan sistem operasi yang mendasarinya. Karena API ini menggunakan mekanisme pemberitahuan sistem operasi, detail tentang bagaimana pemberitahuan muncul dan berperilaku mungkin berbeda sesuai dengan sistem operasi dan pengaturan pengguna.

+ +

Untuk menggunakan API ini Anda harus memiliki izin "notifikasi"

+ +

Tipe

+ +
+
{{WebExtAPIRef("notifications.NotificationOptions")}}
+
Menentukan isi pemberitahuan.
+
{{WebExtAPIRef("notifications.TemplateType")}}
+
Jenis pemberitahuan. Misalnya, ini menentukan apakah pemberitahuan dapat memuat gambar.
+
+ +

Fungsi

+ +
+
{{WebExtAPIRef("notifications.clear()")}}
+
Hapus pemberitahuan khusus, berikan ID-nya.
+
{{WebExtAPIRef("notifications.create()")}}
+
Buat dan tampilkan pemberitahuan baru.
+
{{WebExtAPIRef("notifications.getAll()")}}
+
Dapatkan semua notifikasi.
+
{{WebExtAPIRef("notifications.update()")}}
+
Perbarui notifikasi
+
+ +

Events

+ +
+
{{WebExtAPIRef("notifications.onButtonClicked")}}
+
Dipecat ketika pengguna mengklik tombol di notifikasi.
+
{{WebExtAPIRef("notifications.onClicked")}}
+
Dipecat ketika pengguna mengklik pemberitahuan, tetapi tidak pada tombol.
+
{{WebExtAPIRef("notifications.onClosed")}}
+
Dipecat ketika pemberitahuan ditutup, baik oleh sistem atau karena pengguna memecatnya.
+
{{WebExtAPIRef("notifications.onShown")}}
+
Dipecat segera setelah pemberitahuan telah ditampilkan.
+
+ +

Kompatibilitas peramban

+ +

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

+ +

{{WebExtExamples("h2")}}

+ +
Ucapan terima kasih + +

API ini berdasarkan pada API Chromium chrome.notifications.

+
diff --git a/files/id/mozilla/add-ons/webextensions/api/windows/createtype/index.html b/files/id/mozilla/add-ons/webextensions/api/windows/createtype/index.html new file mode 100644 index 0000000000..569dbc0b97 --- /dev/null +++ b/files/id/mozilla/add-ons/webextensions/api/windows/createtype/index.html @@ -0,0 +1,65 @@ +--- +title: windows.CreateType +slug: Mozilla/Add-ons/WebExtensions/API/windows/CreateType +translation_of: Mozilla/Add-ons/WebExtensions/API/windows/CreateType +--- +
{{AddonSidebar()}}
+ +

Menentukan jenis browser window yang akan dibuat.

+ +

Tipe

+ +

Nilai dari tipe ini adalah strings. Nilai yang tersedia adalah:

+ + + +

Browser compatibility

+ + + +

{{Compat("webextensions.api.windows.CreateType")}}

+ +

{{WebExtExamples}}

+ +
Acknowledgements + +

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

+ +

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

+
+ + diff --git a/files/id/mozilla/add-ons/webextensions/api/windows/index.html b/files/id/mozilla/add-ons/webextensions/api/windows/index.html new file mode 100644 index 0000000000..d0611824cd --- /dev/null +++ b/files/id/mozilla/add-ons/webextensions/api/windows/index.html @@ -0,0 +1,127 @@ +--- +title: windows +slug: Mozilla/Add-ons/WebExtensions/API/windows +tags: + - API + - Add-ons + - Extensions + - Interface + - NeedsTranslation + - Non-standard + - Reference + - TopicStub + - WebExtensions + - Windows +translation_of: Mozilla/Add-ons/WebExtensions/API/windows +--- +
{{AddonSidebar}}
+ +

Interact with browser windows. You can use this API to get information about open windows and to open, modify, and close windows. You can also listen for window open, close, and activate events.

+ +

Types

+ +
+
{{WebExtAPIRef("windows.WindowType")}}
+
The type of browser window this is.
+
{{WebExtAPIRef("windows.WindowState")}}
+
The state of this browser window.
+
{{WebExtAPIRef("windows.Window")}}
+
Contains information about a browser window.
+
{{WebExtAPIRef("windows.CreateType")}}
+
Specifies the type of browser window to create.
+
+ +

Properties

+ +
+
{{WebExtAPIRef("windows.WINDOW_ID_NONE")}}
+
The windowId value that represents the absence of a browser window.
+
{{WebExtAPIRef("windows.WINDOW_ID_CURRENT")}}
+
The windowId value that represents the current window.
+
+ +

Functions

+ +
+
{{WebExtAPIRef("windows.get()")}}
+
Gets details about a window, given its ID.
+
{{WebExtAPIRef("windows.getCurrent()")}}
+
Gets the current window.
+
{{WebExtAPIRef("windows.getLastFocused()")}}
+
Gets the window that was most recently focused — typically the window 'on top'.
+
{{WebExtAPIRef("windows.getAll()")}}
+
Gets all windows.
+
{{WebExtAPIRef("windows.create()")}}
+
+

Creates a new window.

+
+
{{WebExtAPIRef("windows.update()")}}
+
Updates the properties of a window. Use this to move, resize, and (un)focus a window, etc.
+
{{WebExtAPIRef("windows.remove()")}}
+
Closes a window, and all its tabs.
+
+ +

Events

+ +
+
{{WebExtAPIRef("windows.onCreated")}}
+
Fired when a window is created.
+
{{WebExtAPIRef("windows.onRemoved")}}
+
Fired when a window is closed.
+
{{WebExtAPIRef("windows.onFocusChanged")}}
+
Fired when the currently focused window changes.
+
+ +

Browser compatibility

+ +

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

+ + + +

Edge incompatibilities

+ +

Promises are not supported in Edge. Use callbacks instead.

+ +

{{WebExtExamples("h2")}}

+ +
Acknowledgements + +

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

+ +

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

+
+ + diff --git a/files/id/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html b/files/id/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html new file mode 100644 index 0000000000..96ab65479e --- /dev/null +++ b/files/id/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html @@ -0,0 +1,21 @@ +--- +title: Browser support for JavaScript APIs +slug: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs +translation_of: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs +--- +
{{AddonSidebar}}
+ + + +

{{WebExtAllCompatTables}}

+ +
Acknowledgments + +

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

+
+ +

See also

+ + diff --git a/files/id/mozilla/add-ons/webextensions/content_scripts/index.html b/files/id/mozilla/add-ons/webextensions/content_scripts/index.html new file mode 100644 index 0000000000..da5a653034 --- /dev/null +++ b/files/id/mozilla/add-ons/webextensions/content_scripts/index.html @@ -0,0 +1,554 @@ +--- +title: Content scripts +slug: Mozilla/Add-ons/WebExtensions/Content_scripts +translation_of: Mozilla/Add-ons/WebExtensions/Content_scripts +--- +
{{AddonSidebar}}
+ +

A content script is a part of your extension that runs in the context of a particular web page (as opposed to background scripts which are part of the extension, or scripts which are part of the web site itself, such as those loaded using the {{HTMLElement("script")}} element).

+ +

Background scripts can access all the WebExtension JavaScript APIs, but they can't directly access the content of web pages. So if your extension needs to do that, you need content scripts.

+ +

Just like the scripts loaded by normal web pages, content scripts can read and modify the content of their pages using the standard DOM APIs.

+ +

Content scripts can only access a small subset of the WebExtension APIs, but they can communicate with background scripts using a messaging system, and thereby indirectly access the WebExtension APIs.

+ +
+

Note that content scripts are blocked on the following domains:

+ + + +

If you try to inject a content script into a page in these domains, it fails and the page logs a CSP error.

+ +

Because these restrictions include addons.mozilla.org, users may attempt to use your extension immediately after installation—only to find that it doesn't work! You may want to add an appropriate warning, or an onboarding page to move users away from addons.mozilla.org.

+
+ +
+

Values added to the global scope of a content script with let foo or window.foo = "bar" may disappear due to bug 1408996.

+
+ +

Loading content scripts

+ +

You can load a content script into a web page in one of three ways:

+ +
    +
  1. +
    +
    At install time, into pages that match URL patterns.
    +
    Using the content_scripts key in your manifest.json, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern.
    +
    +
  2. +
  3. +
    +
    At runtime, into pages that match URL patterns.
    +
    Using the {{WebExtAPIRef("contentScripts")}} API, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern. (This is similar to method 1, except that you can add and remove content scripts at runtime.)
    +
    +
  4. +
  5. +
    +
    At runtime, into specific tabs.
    +
    Using the tabs.executeScript() API, you can load a content script into a specific tab whenever you want. (For example, in response to the user clicking on a browser action.)
    +
    +
  6. +
+ +

There is only one global scope per frame, per extension. This means that variables from one content script can directly be accessed by another content script, regardless of how the content script was loaded.

+ +

Using methods (1) and (2), you can only load scripts into pages whose URLs can be represented using a match pattern.

+ +

Using method (3), you can also load scripts into pages packaged with your extension, but you can't load scripts into privileged browser pages (like "about:debugging" or "about:addons").

+ +

Content script environment

+ +

DOM access

+ +

Content scripts can access and modify the page's DOM, just like normal page scripts can. They can also see any changes that were made to the DOM by page scripts.

+ +

However, content scripts get a "clean" view of the DOM. This means:

+ + + +

In Firefox, this behavior is called Xray vision.

+ +

Consider a web page like this:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+  </head>
+
+  <body>
+    <script src="page-scripts/page-script.js"></script>
+  </body>
+</html>
+ +

The script page-script.js does this:

+ +
// page-script.js
+
+// add a new element to the DOM
+let p = document.createElement("p");
+p.textContent = "This paragraph was added by a page script.";
+p.setAttribute("id", "page-script-para");
+document.body.appendChild(p);
+
+// define a new property on the window
+window.foo = "This global variable was added by a page script";
+
+// redefine the built-in window.confirm() function
+window.confirm = function() {
+  alert("The page script has also redefined 'confirm'");
+}
+ +

Now an extension injects a content script into the page:

+ +
// content-script.js
+
+// can access and modify the DOM
+let pageScriptPara = document.getElementById("page-script-para");
+pageScriptPara.style.backgroundColor = "blue";
+
+// can't see page-script-added properties
+console.log(window.foo);  // undefined
+
+// sees the original form of redefined properties
+window.confirm("Are you sure?"); // calls the original window.confirm()
+ +

The same is true in reverse; page scripts cannot see JavaScript properties added by content scripts.

+ +

This means that content scripts can rely on DOM properties behaving predictably, without worrying about its variables clashing with variables from the page script.

+ +

One practical consequence of this behavior is that a content script doesn't have access to any JavaScript libraries loaded by the page. So, for example, if the page includes jQuery, the content script can't see it.

+ +

If a content script needs to use a JavaScript library, then the library itself should be injected as a content script alongside the content script that wants to use it:

+ +
"content_scripts": [
+  {
+    "matches": ["*://*.mozilla.org/*"],
+    "js": ["jquery.js", "content-script.js"]
+  }
+]
+ +
+

Note: Firefox does provide some APIs that enable content scripts to access JavaScript objects created by page scripts, and to expose their own JavaScript objects to page scripts.

+ +

See Sharing objects with page scripts for more details.

+
+ +

WebExtension APIs

+ +

In addition to the standard DOM APIs, content scripts can use the following WebExtension APIs:

+ +
+
From extension:
+
+ +
+
From runtime:
+
+ +
+
From i18n:
+
+ +
+
From menus:
+
+ +
+
Everything from:
+
storage
+
+ +

XHR and Fetch

+ +

Content scripts can make requests using the normal window.XMLHttpRequest and window.fetch() APIs.

+ +
+

In Firefox, content script requests (for example, using fetch()) happen in the context of an extension, so you must provide an absolute URL to reference page content.

+ +

In Chrome, these requests happen in context of the page, so they are made to a relative URL.  For example, /api is sent to https://«current page URL»/api.

+
+ +

Content scripts get the same cross-domain privileges as the rest of the extension: so if the extension has requested cross-domain access for a domain using the permissions key in manifest.json, then its content scripts get access that domain as well.

+ +

This is accomplished by exposing more privileged XHR and fetch instances in the content script, which has the side-effect of not setting the Origin and Referer headers like a request from the page itself would; this is often preferable to prevent the request from revealing its cross-origin nature.

+ +
+

In Firefox, extensions that need to perform requests that behave as if they were sent by the content itself can use  content.XMLHttpRequest and content.fetch() instead.

+ +

For cross-browser extensions, the presence of these methods must be feature-detected.

+
+ +

Communicating with background scripts

+ +

Although content scripts can't directly use most of the WebExtension APIs, they can communicate with the extension's background scripts using the messaging APIs, and can therefore indirectly access all the same APIs that the background scripts can.

+ +

There are two basic patterns for communicating between the background scripts and content scripts:

+ + + +

One-off messages

+ +

To send one-off messages, with an optional response, you can use the following APIs:

+ + + + + + + + + + + + + + + + + + + + + +
In content scriptIn background script
Send a messagebrowser.runtime.sendMessage()browser.tabs.sendMessage()
Receive a messagebrowser.runtime.onMessagebrowser.runtime.onMessage
+ +

For example, here's a content script that listens for click events in the web page.

+ +

If the click was on a link, it sends a message to the background page with the target URL:

+ +
// content-script.js
+
+window.addEventListener("click", notifyExtension);
+
+function notifyExtension(e) {
+  if (e.target.tagName != "A") {
+    return;
+  }
+  browser.runtime.sendMessage({"url": e.target.href});
+}
+ +

The background script listens for these messages and displays a notification using the notifications API:

+ +
// background-script.js
+
+browser.runtime.onMessage.addListener(notify);
+
+function notify(message) {
+  browser.notifications.create({
+    "type": "basic",
+    "iconUrl": browser.extension.getURL("link.png"),
+    "title": "You clicked a link!",
+    "message": message.url
+  });
+}
+
+ +

(This example code is lightly adapted from the notify-link-clicks-i18n example on GitHub.)

+ +

Connection-based messaging

+ +

Sending one-off messages can get cumbersome if you are exchanging a lot of messages between a background script and a content script. So an alternative pattern is to establish a longer-lived connection between the two contexts, and use this connection to exchange messages.

+ +

Both sides have a runtime.Port object, which they can use to exchange messages.

+ +

To create the connection:

+ + + +

This returns a runtime.Port object.

+ + + +

Once each side has a port, the two sides can:

+ + + +

For example, as soon as it loads, the following content script:

+ + + +
// content-script.js
+
+let myPort = browser.runtime.connect({name:"port-from-cs"});
+myPort.postMessage({greeting: "hello from content script"});
+
+myPort.onMessage.addListener(function(m) {
+  console.log("In content script, received message from background script: ");
+  console.log(m.greeting);
+});
+
+document.body.addEventListener("click", function() {
+  myPort.postMessage({greeting: "they clicked the page!"});
+});
+ +

The corresponding background script:

+ + + +
// background-script.js
+
+let portFromCS;
+
+function connected(p) {
+  portFromCS = p;
+  portFromCS.postMessage({greeting: "hi there content script!"});
+  portFromCS.onMessage.addListener(function(m) {
+    portFromCS.postMessage({greeting: "In background script, received message from content script:" + m.greeting});
+  });
+}
+
+browser.runtime.onConnect.addListener(connected);
+
+browser.browserAction.onClicked.addListener(function() {
+  portFromCS.postMessage({greeting: "they clicked the button!"});
+});
+
+ +

Multiple content scripts

+ +

If you have multiple content scripts communicating at the same time, you might want to store connections to them in an array.

+ + + +
// background-script.js
+
+let ports = []
+
+function connected(p) {
+  ports[p.sender.tab.id] = p
+  //...
+}
+
+browser.runtime.onConnect.addListener(connected)
+
+browser.browserAction.onClicked.addListener(function() {
+  ports.forEach( p => {
+        p.postMessage({greeting: "they clicked the button!"})
+    })
+});
+
+ + + +

Choosing between one-off messages and connection-based messaging

+ +

The choice between one-off and connection-based messaging depends on how your extension expects to make use of messaging.

+ +

The recommended best practices are:

+ +
+
Use one-off messages when…
+
+
    +
  • Only one response is expected to a message.
  • +
  • A small number of scripts listen to receive messages ({{WebExtAPIRef("runtime.onMessage")}} calls).
  • +
+
+
Use connection-based messaging when…
+
+
    +
  • Scripts engage in sessions where multiple messages are exchanged.
  • +
  • The extension need to know about task progress, needs to know if a task is interrupted, or may want to interrupt a task initiated using messaging.
  • +
+
+
+ +

Communicating with the web page

+ +

By default, content scripts don't get access to objects created by page scripts. However, they can communicate with page scripts using the DOM window.postMessage and window.addEventListener APIs.

+ +

For example:

+ +
// page-script.js
+
+let messenger = document.getElementById("from-page-script");
+
+messenger.addEventListener("click", messageContentScript);
+
+function messageContentScript() {
+  window.postMessage({
+    direction: "from-page-script",
+    message: "Message from the page"
+  }, "*");
+}
+
+ +
// content-script.js
+
+window.addEventListener("message", function(event) {
+  if (event.source == window &&
+      event.data &&
+      event.data.direction == "from-page-script") {
+    alert("Content script received message: \"" + event.data.message + "\"");
+  }
+});
+ +

For a complete working example of this, visit the demo page on GitHub and follow the instructions.

+ +
+

Be very careful when interacting with untrusted web content in this manner! Extensions are privileged code which can have powerful capabilities and hostile web pages can easily trick them into accessing those capabilities.

+ +

To give a trivial example, suppose the content script code that receives the message does something like this:

+ +
// content-script.js
+
+window.addEventListener("message", function(event) {
+  if (event.source == window &&
+      event.data.direction   &&
+      event.data.direction == "from-page-script") {
+    eval(event.data.message);
+  }
+});
+ +

Now the page script can run any code with all the privileges of the content script.

+
+ +

Using eval() in content scripts

+ +
+
In Chrome
+
{{jsxref("eval")}} always runs code in the context of the content script, not in the context of the page.
+
In Firefox
+
+

If you call eval(), it runs code in the context of the content script.

+ +

If you call window.eval(), it runs code in the context of the page.

+
+
+ +

For example, consider a content script like this:

+ +
// content-script.js
+
+window.eval('window.x = 1;');
+eval('window.y = 2');
+
+console.log(`In content script, window.x: ${window.x}`);
+console.log(`In content script, window.y: ${window.y}`);
+
+window.postMessage({
+  message: "check"
+}, "*");
+ +

This code just creates some variables x and y using window.eval() and eval(),  logs their values, and then messages the page.

+ +

On receiving the message, the page script logs the same variables:

+ +
window.addEventListener("message", function(event) {
+  if (event.source === window && event.data && event.data.message === "check") {
+    console.log(`In page script, window.x: ${window.x}`);
+    console.log(`In page script, window.y: ${window.y}`);
+  }
+});
+ +
+
In Chrome, this produces output like this:
+
+
In content script, window.x: 1
+In content script, window.y: 2
+In page script, window.x: undefined
+In page script, window.y: undefined
+
+
In Firefox, this produces output like this:
+
+
In content script, window.x: undefined
+In content script, window.y: 2
+In page script, window.x: 1
+In page script, window.y: undefined
+
+
+ +

The same applies to setTimeout(), setInterval(), and Function().

+ +
+

Be very careful when running code in the context of the page! 

+ +

The page's environment is controlled by potentially malicious web pages, which can redefine objects you interact with to behave in unexpected ways:

+ +
// page.js redefines console.log
+
+let original = console.log;
+
+console.log = function() {
+  original(true);
+}
+
+ + +
// content-script.js calls the redefined version
+
+window.eval('console.log(false)');
+
+
diff --git a/files/id/mozilla/add-ons/webextensions/index.html b/files/id/mozilla/add-ons/webextensions/index.html new file mode 100644 index 0000000000..a486f8391c --- /dev/null +++ b/files/id/mozilla/add-ons/webextensions/index.html @@ -0,0 +1,91 @@ +--- +title: WebExtensions +slug: Mozilla/Add-ons/WebExtensions +tags: + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Add-ons/WebExtensions +--- +
{{AddonSidebar}}
+ +

WebExtensions adalah sistem cross-browser untuk mengembangkan browser add-ons. Untuk sebagian besar API tersebut kompatibel dengan extension API yang didukung oleh Google Chrome dan Opera. Ekstensi ditulis untuk browser ini dalam banyak kasus akan berjalan di Firefox atau Microsoft Edge hanya dengan beberapa perubahan. API ini juga sepenuhnya kompatibel dengan multiprocess Firefox.

+ +

Kami juga berniat untuk memperpanjang API untuk mendukung kebutuhan para pengembang, jadi jika Anda memiliki ide, kami akan senang mendengar mereka. Anda dapat menghubungi kami dev-addons mailing list atau #webextensions di IRC.

+ +
+ + +
+

Reference

+ + + +

JavaScript APIs

+ +
{{ ListSubpages ("/en-US/Add-ons/WebExtensions/API") }}
+ +

Manifest keys

+ +
{{ ListSubpages ("/en-US/Add-ons/WebExtensions/manifest.json") }}
+
+
diff --git a/files/id/mozilla/add-ons/webextensions/your_first_webextension/index.html b/files/id/mozilla/add-ons/webextensions/your_first_webextension/index.html new file mode 100644 index 0000000000..27204f8504 --- /dev/null +++ b/files/id/mozilla/add-ons/webextensions/your_first_webextension/index.html @@ -0,0 +1,153 @@ +--- +title: WebExtensions Pertama Anda +slug: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension +translation_of: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension +--- +
{{AddonSidebar}}
+ +

Dalam artikel ini kita akan mulai menciptakan WebExtension untuk Firefox, dari awal sampai akhir. add-on ini hanya menambahkan garis merah untuk setiap halaman yang dimuat dari "mozilla.org" atau subdomainnya.

+ +

Kode sumber untuk contoh ini ada pada GitHub: https://github.com/mdn/webextensions-examples/tree/master/borderify.

+ +

Pertama, anda membutuhkan Firefox versi 45 atau lebih baru.

+ + + +

Buat sebuah directory baru dan arahkan kesana:

+ +
mkdir borderify
+cd borderify
+ +

manifest.json

+ +

Sekarang buat file baru dengan nama "manifest.json" di dalam folder "borderify". Berikan kode seperti berikut:

+ +
{
+
+  "manifest_version": 2,
+  "name": "Borderify",
+  "version": "1.0",
+
+  "description": "Adds a red border to all webpages matching mozilla.org.",
+
+  "icons": {
+    "48": "icons/border-48.png"
+  },
+
+  "content_scripts": [
+    {
+      "matches": ["*://*.mozilla.org/*"],
+      "js": ["borderify.js"]
+    }
+  ]
+
+}
+ + + +

Kunci yang paling menarik di sini adalah content_scripts, yang memberitahu Firefox untuk memuat script ke Halaman web dengan URL yang cocok dengan pola tertentu. Dalam hal ini, Kita akan meminta Firefox untuk memuat script yang di disebut "borderify.js" ke semua halaman HTTP atau HTTPS yang disajikan dari "mozilla.org" atau subdomainnya.

+ + + +
+

Jika anda menggunakan Firefox versi 48 kebawah, Anda juga akan memerlukan key tambahan yang disebut applications:

+ +
"applications": {
+  "gecko": {
+    "id": "borderify@example.com",
+    "strict_min_version": "42.0",
+    "strict_max_version": "50.*",
+    "update_url": "https://example.com/updates.json"
+  }
+}
+
+ +

icons/border-48.png

+ +

Add-on harus memiliki ikon. Ini akan ditampilkan di sebelah list add-on di Add-ons Manager. Manifest.json menjanjikan bahwa kita akan memiliki ikon di "icons/border-48.png".

+ +

Membuat sebuah folder "ikon" pada folder "borderify". Simpan ikon dengan nama "border-48.png".  Anda dapat menggunakan salah satu dari contoh kami, yang diambil dari ikon Google Material Design iconset, dan digunakan di bawah ketentuan lisensi Creative Commons Attribution-ShareAlike.

+ +

Jika Anda memilih untuk menggunakan ikon Anda sendiri, itu harus berukuran 48x48 pixel. Anda juga bisa menggunakan ikon 96x96 pixel, untuk display resolusi tinggi, dan jika Anda melakukan hal ini akan ditentukan property 96 milik ikon objek di manifest.json:

+ +
"icons": {
+  "48": "icons/border-48.png",
+  "96": "icons/border-96.png"
+}
+ +

Atau, Anda bisa menggunakan file SVG, dan itu akan ditingkatkan dengan benar.

+ + + +

borderify.js

+ +

Akhirnya, buat file dengan nama "borderify.js" pada folder "borderify". Berikan kode seperti berikut:

+ +
document.body.style.border = "5px solid red";
+ +

Script ini akan dimuat ke dalam halaman yang cocok dengan pola yang diberikan dalam key content_scripts pada manifest.json. Script memiliki akses langsung ke dokumen, seperti script dimuat oleh halaman itu sendiri.

+ + + +

Trying it out

+ +

Pertama, periksa bahwa Anda memiliki file yang tepat di tempat yang tepat:

+ +
borderify/
+    icons/
+        border-48.png
+    borderify.js
+    manifest.json
+ +

Pemasangan

+ +

Buka "about:debugging" di Firefox, klik "Load Temporary Add-on" dan pilih file pada folder add-on anda:

+ +

{{EmbedYouTube("cer9EUKegG4")}}

+ +

Add-on kini akan diinstal, dan akan tetap sampai Anda me-restart Firefox.

+ +

Atau, Anda dapat menjalankan WebExtension dari baris perintah menggunakan web-ext tool.

+ +

Testing

+ +

Sekarang coba kunjungi halaman dengan domain "mozilla.org", dan Anda akan melihat garis merah melingkar pada halaman:

+ +

{{EmbedYouTube("rxBQl2Z9IBQ")}}

+ +
+

Jangan mencobanya pada addons.mozilla.org! skrip konten saat ini diblokir pada domain tersebut..

+
+ +

Coba bereksperimen sedikit. Edit script konten untuk mengubah warna garis, atau melakukan sesuatu yang lain untuk konten halaman. Simpan script konten, kemudian muat kembali file add-on dengan mengklik button "Reload" pada about:debugging. Anda dapat melihat perubahan segera.

+ +

{{EmbedYouTube("NuajE60jfGY")}}

+ + + +

Packaging dan publishing

+ +

Bagi orang lain yang akan untuk menggunakan add-on, Anda perlu memaketkan itu dan mengirimkannya ke Mozilla untuk penandaan. Untuk mempelajari lebih lanjut tentang itu, lihat "Publishing your WebExtension".

+ +

Apa berikutnya?

+ +

Sekarang Anda punya ide dari proses pengembangan WebExtension untuk Firefox, coba:

+ + diff --git a/files/id/mozilla/connect/index.html b/files/id/mozilla/connect/index.html new file mode 100644 index 0000000000..e9d3f28280 --- /dev/null +++ b/files/id/mozilla/connect/index.html @@ -0,0 +1,95 @@ +--- +title: Connect with Mozilla +slug: Mozilla/Connect +translation_of: Mozilla/Connect +--- +
+

Aktifkan, menginspirasi dan berkolaborasi untuk membuat Web platform utama yang digunakan untuk menciptakan pengalaman di semua perangkat yang terhubung.

+
+ + +
+
+
+ +
+ +
+ +
+ +
+ +
+
+ +
+

Terhubung dengan Mozilla

+ +

Pengembang menciptakan masa depan dengan membangun layanan dan aplikasi untuk orang di seluruh dunia. Tujuan Hubungan Pengembang Mozilla adalah untuk membantu pengembang untuk menggunakan teknologi web terbuka dan standar untuk berhasil dalam mencapai tujuan mereka. Selain dokumentasi di sini di MDN, kami menawarkan bantuan dan sumber lainnya menuju tujuan ini, melalui berbagai saluran. Kami mengundang Anda untuk menghubungkan, belajar, dan berbagi pengetahuan Anda sendiri.

+ +

Kami menawarkan bantuan melalui Q & A pada Stack Overflow, untuk memecahkan masalah teknis yang spesifik dan tantangan yang mungkin Anda miliki. Kami juga memiliki newsletter menjaga Anda informasi tentang kejadian terbaru dalam adegan web sekitar aplikasi web dan banyak lagi. Langganan Apps & Hacks buletin.

+ +

Kami memiliki banyak rencana dan ide-ide untuk iteratif memperluas Hubungan Pengembang penawaran kami, dan kami ingin Anda terlibat seperti yang kita melakukannya! Jadi, ikuti tag pada Stack Overflow , berlangganan ke blog Hacks , berlangganan newsletter, dan mendaftar untuk sebuah account !

+
+ +
+
+

Q & A pada Stack Overflow Lihat semua Q & A ...

+ +

Kami memiliki Q & A untuk membahas tantangan dan masalah ketika mengembangkan, khususnya untuk Firefox OS dan Open Web di ponsel. Ini tersedia di Stack Overflow di bawah URL mudah http://stackoverflow.com/r/mozilla .

+ + +
Bentuk Stack
+ +

Terbaru Q & A Topik

+
+ +
 
+
+ +

Pengembang pada lokakarya Firefox OS di Madrid.

+ +
+
+

Dimana Mozilla? Lihat peserta dan rincian pada halaman Acara kami ...

+ +

Berikut ini adalah daftar peristiwa di mana perwakilan Mozilla akan berbicara. Pastikan untuk berbicara dengan mereka!

+
+ + +
+
+ +

 

diff --git a/files/id/mozilla/firefox/edisi_pengembang/index.html b/files/id/mozilla/firefox/edisi_pengembang/index.html new file mode 100644 index 0000000000..6f3a9a91bf --- /dev/null +++ b/files/id/mozilla/firefox/edisi_pengembang/index.html @@ -0,0 +1,57 @@ +--- +title: Edisi Pengembang +slug: Mozilla/Firefox/Edisi_Pengembang +translation_of: Mozilla/Firefox/Developer_Edition +--- +
{{FirefoxSidebar}}

+ +

Sebuah versi Firefox yang dikhususkan untuk para web developer.

+ +

Unduh Firefox Edisi Pengembang

+ +
+
+
+

Fitur Firefox terbaru

+ +

Firefox Edisi Pengembang menggantikan kanal Aurora pada Proses Rilis Firefox. Seperti Aurora, fitur-fitur baru akan tersedia pada versi ini setiap enam minggu, setelah distabilkan dari Nightly build.

+ +

Dengan menggunakan Edisi Pengembang, anda mendapatkan akses ke fitur peralatan dan platform 12 minggu lebih awal dari rilis Firefox utama.

+ +

Temukan apa yang baru dalam Edisi Pengembang.

+
+ +
+

Peralatan pengembang eksperimental

+ +

Kami akan memasukkan fitur-fitur eksperimental yang belum masuk di versi biasa.

+ +

Sebagai contoh, Edisi Pengembang memasukkan Firefox Tools Adapter, yang dapat membuat anda terhubung dengan peralatan pengembang Firefox ke browser lain seperti Chrome pada Android atau Safari di iOS.

+
+
+ +
+
+

Profil terpisah

+ +

Firefox Edisi Pengembang menggunakan profil terpisah dari versi Firefox lain yang terinstall di komputer anda. Artinya, anda bisa menjalankan Edisi Pengembang bersamaan dengan Firefox versi biasa atau Beta.

+
+ +
+

Dibuat untuk pengembang web

+ +

Kami telah mengatur beberapa pengaturan untuk pengembang web. Sebagai contoh, chrome dan debug remote telah diaktifkan dari awal.

+
+
+ +
+
+

Tema tersendiri

+ +

Termasuk di dalamnya akses cepat ke fitur pengembang.

+
+ +
 
+
+ +

 

diff --git a/files/id/mozilla/firefox/index.html b/files/id/mozilla/firefox/index.html new file mode 100644 index 0000000000..cf3e7acc66 --- /dev/null +++ b/files/id/mozilla/firefox/index.html @@ -0,0 +1,75 @@ +--- +title: Firefox +slug: Mozilla/Firefox +tags: + - Firefox + - Landing + - Mozilla +translation_of: Mozilla/Firefox +--- +
{{FirefoxSidebar}}
+ +

Firefox adalah peramban populer milik Mozilla, tersedia untuk berbagai platforms, termasuk Windows, Mac OS X dan Linux pada desktop dan perangkat mobile Android. Dengan kompatibilitas luas, teknologi Web terbaru dan alat pengembangan yang kuat, Firefox adalah yang terbesar untuk pengguna dan pengembang web.

+ +

Firefox adalah sebuah proyek open sorce, sebagian besar kode ini disumbangkan oleh komunitas besar relawan kami. Di sini Anda akan belajar cara untuk berkontribusi pada proyek Firefox dan Anda juga akan menemukan link ke informasi tentang pembuatan add-ons Firefox, memakai alat pengembang Firefox, dan tugas lainnya.

+ +
+

Pelajari cara membuat add-ons Firefox, cara mengembangkan dan membuat Firefox sendiri, dan cara internal dari Firefox dan subproyek-nya bekerja.

+
+ + + +

+ +

Channel Firefox

+ +

Firefox tersedia dalam lima channel.

+ +

Firefox Nightly

+ +

Each night we build Firefox from the latest code in mozilla-central. These builds are for Firefox developers or those who want to try out the very latest cutting edge features while they're still under active development.

+ +

Download Firefox Nightly

+ +

Firefox Developer Edition

+ +

This is a version of Firefox tailored for developers. Every six weeks, we take the features in Firefox Nightly that are stable enough and create a new version of Firefox Developer Edition. We also add some extra features for developers that are only available in this channel.

+ +

Learn more about Firefox Developer Edition.

+ +

Download Firefox Developer Edition

+ +

Firefox Beta

+ +

After spending six weeks in Firefox Developer Edition, we take the features that are stable enough, and create a new version of Firefox Beta. Firefox Beta builds are for Firefox enthusiasts to test what's destined to become the next released Firefox version.

+ +

Download Firefox Beta

+ +

Firefox

+ +

After stabilizing for another six weeks in Beta, we're ready to ship the new features to hundreds of millions of users in a new release version of Firefox.

+ +

Download Firefox

+ +

Firefox Extended Support Release (ESR)

+ +

Firefox ESR is the long-term support edition of Firefox for desktop for use by organizations including schools, universities, businesses and others who need extended support for mass deployments.

+ +

Learn more about Firefox Extended Support Release.

+ +

Download Firefox ESR

+ +

Firefox profiles

+ +

If you find yourself using multiple Firefox channels—or just multiple configurations—on a regular basis, you should read how to use multiple Firefox profiles by turning Firefox's Profile Manager and other profile management tools to your advantage.

diff --git a/files/id/mozilla/firefox/privacy/index.html b/files/id/mozilla/firefox/privacy/index.html new file mode 100644 index 0000000000..fe82422987 --- /dev/null +++ b/files/id/mozilla/firefox/privacy/index.html @@ -0,0 +1,22 @@ +--- +title: Privacy +slug: Mozilla/Firefox/Privacy +tags: + - NeedsTranslation + - Privacy + - Security + - TopicStub +translation_of: Mozilla/Firefox/Privacy +--- +
{{FirefoxSidebar}}
+ +

This document lists privacy-related documentation.

+ +

{{ ListSubpages () }}

+ +

See also

+ + diff --git a/files/id/mozilla/firefox/privacy/storage_access_policy/errors/cookieblockedtracker/index.html b/files/id/mozilla/firefox/privacy/storage_access_policy/errors/cookieblockedtracker/index.html new file mode 100644 index 0000000000..f4415aedc2 --- /dev/null +++ b/files/id/mozilla/firefox/privacy/storage_access_policy/errors/cookieblockedtracker/index.html @@ -0,0 +1,33 @@ +--- +title: 'Blocked: Storage access requests from trackers' +slug: Mozilla/Firefox/Privacy/Storage_access_policy/Errors/CookieBlockedTracker +translation_of: Mozilla/Firefox/Privacy/Storage_access_policy/Errors/CookieBlockedTracker +--- +
{{FirefoxSidebar}}
+ +

back up from last user

+ +

What went wrong?

+ +

A request to access cookies or storage was blocked because the browser identified it as coming from a tracker and content blocking is enabled.

+ +

The permission can be changed or removed by:

+ + + +

If the blocked resource doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to the relevant element.

+ +

See also

+ + diff --git a/files/id/mozilla/firefox/privacy/storage_access_policy/errors/index.html b/files/id/mozilla/firefox/privacy/storage_access_policy/errors/index.html new file mode 100644 index 0000000000..a1e1f54a75 --- /dev/null +++ b/files/id/mozilla/firefox/privacy/storage_access_policy/errors/index.html @@ -0,0 +1,24 @@ +--- +title: Errors +slug: Mozilla/Firefox/Privacy/Storage_access_policy/Errors +tags: + - Cookies + - Errors + - NeedsTranslation + - Storage + - TopicStub + - storage access policy +translation_of: Mozilla/Firefox/Privacy/Storage_access_policy/Errors +--- +
{{FirefoxSidebar}}
+ +

This page lists the errors that can be raised due to Firefox's anti-tracking functionality, governed by the Storage access policy. You can find further information about them by clicking on the links below:

+ +

A request to access cookies or storage was blocked because

+ + diff --git a/files/id/mozilla/firefox/privacy/storage_access_policy/index.html b/files/id/mozilla/firefox/privacy/storage_access_policy/index.html new file mode 100644 index 0000000000..801d5bfad1 --- /dev/null +++ b/files/id/mozilla/firefox/privacy/storage_access_policy/index.html @@ -0,0 +1,261 @@ +--- +title: 'Storage access policy: Block cookies from trackers' +slug: Mozilla/Firefox/Privacy/Storage_access_policy +tags: + - NeedsTranslation + - Privacy + - TopicStub + - storage access policy + - tracking protection +translation_of: Mozilla/Firefox/Privacy/Storage_access_policy +--- +
{{FirefoxSidebar}}
+ +

Firefox includes a new storage access policy that blocks cookies and other site data from third-party tracking resources. This policy is designed as an alternative to the older cookie policies, which have been available in Firefox for many years. This policy protects against cross-site tracking while minimizing the site breakage associated with traditional cookie blocking. This article explains how the policy works and how you can test it.

+ +

Testing in Firefox

+ +

This cookie policy has been available in Firefox since version 63. This documentation describes the policy that we intend to ship to Firefox Release users, but may not match what is implemented in the current Release version of Firefox. That's because we document new aspects of the policy as soon as they land in Firefox Nightly, our pre-release channel. Firefox Nightly may also contain experimental features that we don't yet plan to ship to Release users; experimental features will not be included in this documentation, but may nevertheless impact the functionality of domains classified as trackers.

+ +

We recommend sites test with Firefox Nightly, as this includes the newest version of our protections. As described above, note that Nightly may include additional protections that end up getting removed or changed before they reach our Release users. We’ll keep this page updated with the newest information as we strengthen our protections.

+ +

These protections are on by default in Nightly. The cookie policy can be enabled in other versions of Firefox through the Content Blocking settings (these steps will vary by version; the linked documentation includes a dropdown to select the appropriate Firefox version).

+ +

Report Broken Sites

+ +

If you find a website broken as a result of this change, file a bug under the Tracking Protection component within the Firefox product on Bugzilla. Alternatively you can report broken sites directly in Firefox by clicking "Report a Problem" in the Content Blocking section of the Control Center (this shortcut may not be available in all versions of Firefox).

+ +

Tracking protection explained

+ +

How does Firefox determine which resources are tracking resources?

+ +

Firefox uses the Tracking Protection list to determine which resources are tracking resources. The Tracking Protection list is maintained by Disconnect. When the list is applied in Firefox, we make two important changes:

+ + + +

Firefox uses the built-in Tracking Protection URL classifier to determine which resources match the tracking protection list. Domains are matched against the list in accordance with the SafeBrowsing v4 specification. Specifically, we check the exact hostname of the resource against the list, as well as the last four hostnames formed by starting with the last five components and successively removing the leading component. Consider the following examples:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Hostname on the listHostname of resourceMatched
example.comexample.comYes
example.coma.b.example.comYes
blah.example.comexample.comNo
a.b.example.comc.d.example.comNo
blah.example.comfoo.blah.example.comYes
+ +

What does the storage access policy block?

+ +

The storage access policy blocks resources identified as trackers from accessing their cookies and other site storage when they are loaded in a third-party context. This prevents those resources from retrieving tracking identifiers stored in cookies or site storage and using them to identify users across visits to multiple first parties. Specifically, Firefox does this by imposing the following restrictions:

+ +

Cookies:

+ + + +

DOM Storage:

+ + + +

Messaging and Workers:

+ + + +

DOM Cache:

+ + + +

Browser caches:

+ + + +

Network connections:

+ + + +

What is not blocked by the policy?

+ +
    +
  1. This policy does not currently restrict third-party storage access for resources that are not classified as tracking resources. We may choose to apply additional restrictions to third-party storage access in the future.
  2. +
  3. The restrictions applied by the policy will not prevent third-party scripts classified as tracking resources from accessing storage in the main context of the page. These scripts can continue to use storage scoped to the top-level origin.
  4. +
  5. Origins classified as trackers will have access to their own storage when they are loaded in a first-party context.
  6. +
  7. Cross-origin resources loaded from the same eTLD+1 as the top-level context will still have access to their storage.
  8. +
  9. Origins normally classified as trackers will not be blocked if the top-level page origin is determined to be from the same organization as them.
  10. +
+ +

Storage access grants

+ +

In order to improve web compatibility and permit third-party integrations that require storage access, Firefox will grant storage access scoped to the first party for a particular third-party origin as described in this section. Currently, Firefox includes some web compatibility heuristics that grant storage access to third-party resources classified as trackers when a user interacts with those third parties. We do this when we expect that not granting access would cause the web page to break. We also support an initial implementation of the Storage Access API, through which embedded {{htmlelement("iframe")}}s can request storage access by calling {{domxref("Document.requestStorageAccess()")}}. Although both of these approaches provide the same level of storage access, we recommend third parties switch to using the Storage Access API in order to guarantee their access to storage.

+ +

Automatic storage access upon interaction

+ +

In order to improve web compatibility, Firefox currently includes some heuristics to grant storage access automatically to third parties that receive user interaction. These heuristics are intended to allow some third-party integrations that are common on the web to continue to function. They are intended to be temporary and will be removed in a future version of Firefox. They should not be relied upon for current and future web development.

+ +

Third-party storage access may be granted to resources that have been classified as tracking resources when a user gesture triggers a pop-up window that has opener access to the originating document. When that occurs, there are two possible ways a third-party origin can be granted access:

+ + + +

Scope of storage access

+ +

When storage access is granted, it is scoped to the origin of the opener document or subdomains of that origin. Access that is granted on the subdomain of an origin does not extend to the top-level origin. As an example, if a resource from tracker.example is granted storage access on foo.example.com, then tracker.example will be able to access its cookies on bar.foo.example.com but not example.com. Instead, if tracker.example were granted access on example.com it would be able to access its storage on bar.foo.example.com, foo.example.com, and example.com.

+ +

When storage access is granted to tracker.example on example.com, all resources loaded from tracker.example on any top-level document loaded from example.com are immediately given storage access. This includes all resources loaded in the main context of the page, embedded <iframe>s, and resources loaded within embedded <iframe>s. Storage access is not extended to other resources loaded on example.com (e.g. other-tracker.example), nor to other first parties on which tracker.example is embedded (e.g. example.org).

+ +

Storage access grants extend into the first level of nested contexts, but no further. This means that <iframe>s embedded in the main context of the page and loaded from a domain classified as a tracker will have full access to all storage locations accessible through JavaScript. Similarly, requests for resources loaded in <iframe>s embedded in the main context of the page will have access to HTTP cookies. However, further nested contexts, including but not limited to those from the origin classified as a tracker, will not be granted storage access.

+ +

Consider the following embedding scenarios on a top-level page loaded from example.com on which tracker.example has been granted storage access.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Embeddingtracker.example resource storage access
An image is loaded from tracker.example and embedded in the main context of example.com.HTTP: Yes
+ JS: N/A
example.com embeds an <iframe> from example.org. That <iframe> goes on to load an image from tracker.example.HTTP: Yes
+ JS: N/A
example.com embeds an <iframe> from example.org. That <iframe> goes on to embed an <iframe> from tracker.example.HTTP: Yes
+ JS: No
example.com embeds an <iframe> from tracker.example.HTTP: Yes
+ JS: Yes
example.com embeds an <iframe> from example.com (same origin). The nested <iframe> embeds an <iframe> from tracker.example.HTTP: Yes
+ JS: No
+ +

Storage access expiration

+ +

The storage access grant expires after 30 days. Domains classified as tracking resources may be granted third-party storage access on multiple first parties, and the storage permission for each party expires independently. The above heuristics will also serve to extend the lifetime of a third-party storage permission on origins that have already been granted access.  Each time the heuristic is activated, or a success call to the Storage Access API is made, the pre-existing storage access expiration will be extended by 30 days, counting from the time the previous access was granted.

+ +

Please note that in the future we expect to make changes to how long storage access will remain valid for.  As mentioned before, the way to know that you will be able to use storage as a third-party going forward will be using the Storage Access API.

+ +

Debugging

+ +

We encourage site owners to test their sites, particularly those that rely on third-party content integrations. We’ve added several new features to Firefox to make testing easier.

+ +

Developer Tools notifications

+ +

The Network Monitor in Firefox Developer Tools now includes an indicator for all resource requests that have been classified as tracking resources. This indicator is shown as a shield icon in the domain column. In the sample image below, trackertest.org is classified as a tracking resource, while the request to example.com is not.

+ +

network requests in Firefox devtools indicating which ones are tracking resources with a small shield icon

+ +

Adding custom domains to the Tracking Protection list

+ +

Curious how things will work if a third-party domain on your site were classified as a tracker? We’ve added a preference that allows you to add custom domains to the Tracking Protection URL classifier. To do so:

+ +
    +
  1. Type about:config in your address bar. If you are presented with a page that warns you "This may void your warranty!", click "I accept the risk!"
  2. +
  3. Right click on the next page and click "New" > "String".
  4. +
  5. For the preference name enter "urlclassifier.trackingAnnotationTable.testEntries".
  6. +
  7. For the preference value enter comma separated origins that you’d like to have classified as trackers. E.g. "example.net,example.org".
  8. +
+ +
+

Warning: Be sure to remove these entries after you have finished testing.

+
+ +

FAQ

+ +

This cookie policy has the potential to lead to site breakage, but has been designed to allow common third-party integrations to continue to work while preventing cross-site tracking. In this section we describe the functionality you can expect in different integration scenarios.

+ +

Will this storage access policy block ads from displaying on my website?

+ +

No — this feature only restricts access to cookies and site data that can be used to track users across websites. Blocking tracking identifiers does not prevent the display of advertisements.

+ +

I use a third-party analytics service that is classified as a tracker. Will I still receive analytics data?

+ +

This depends on how the third-party analytics service is implemented. Third-party analytics providers will no longer be able to user their third-party storage to collect data. This means that providers using cookies which are scoped to their third-party domain, or local storage and other site data stored under their origin, will no longer have access to those identifiers across other websites.

+ +

If these services are embedded into the main context of the page, they can continue to use first-party cookies and site storage to track users across page visits on that specific first-party domain.

+ +

I use third-party services for social login, like, and share button integration. Will my users still be able to make use of these services?

+ +

This depends on how the social integration is implemented. We expect that many of the popular social integrations will continue to function as they do under Firefox’s current cookie policy with some minor differences in the user experience.

+ +

A social content provider that is classified as a tracker will not have access to their third-party cookies when the user first visits a new first party. Thus, the user may appear logged out to the service despite being logged in when they visit the provider’s website directly. Depending on the type of integration, the user may have to take some action to interact with the social content provider before the provider is given access to their cookies. For example:

+ + + +

After these interactions, the provider will receive third-party storage access if they prompt the user in a way that is captured by the storage access activation heuristics described above. These providers should consider switching to explicitly request storage access through the Storage Access API as soon as possible. An initial implementation of this API is currently available in Nightly.

+ +

I use third-party pixels and other tools to measure the effectiveness of my ad campaigns. Will I still be able to measure the conversion rate of my ads?

+ +

This depends on how the third party has implemented the measurement tool, but generally ad conversion measurement will be more difficult. Consider the following examples:

+ +
    +
  1. You run an ad on a social media website that is seen several times by a user, but never clicked. That user later visits your website, which includes a conversion tracking tag from the same social media website. This type of conversion is often referred to as a “view-through conversion.” Since the social media website does not have access to their third-party storage, they will not recognize the user as the same user that saw the advertisements on their website and the conversion will not be tracked. We expect that most view-through conversion tracking techniques will no longer work, including those offered by display networks.
  2. +
  3. You run an ad on a display network or social media website that is clicked by a user. That user lands on your website, which includes a conversion tracking tag from the same website that displayed your ad. This type of conversion is often referred to as a “click-through conversion.” Since the social media site or display network will not have access to their third-party storage, they will not recognize the user as the same user that saw the advertisements on their website and the conversion will not be tracked. We expect that this version of click-through conversion will no longer work.
  4. +
  5. You run an ad that appears on a social media website. A user clicks on your advertisement and is taken to a landing page that contains a conversion tracking tag from the third-party network. On the social media website, the network annotates the advertisement landing page URL with a query parameter that signals that the visit was the result of a click on an advertisement. On your website, the display network’s tag checks the URL query parameters and saves any ad tracking parameters to first-party storage. If a user later completes a conversion event, the network’s tag checks first-party storage to determine which click (or clicks) was responsible for the visit. We expect that click-through conversion implemented in this way will continue to work.
  6. +
diff --git a/files/id/mozilla/firefox/releases/index.html b/files/id/mozilla/firefox/releases/index.html new file mode 100644 index 0000000000..af6a0b7c7a --- /dev/null +++ b/files/id/mozilla/firefox/releases/index.html @@ -0,0 +1,12 @@ +--- +title: Firefox developer release notes +slug: Mozilla/Firefox/Releases +tags: + - Firefox + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Firefox/Releases +--- +
{{FirefoxSidebar}}

Dibawah ini anda bisa menemukan link ke catatan rilis pengembang untuk setiap rilis Firefox. Catatan yang ditulis dengan cinta ini memberikan detail tentang fitur dan API yang ditambahkan dan di tingkatkan serta bug yang disingkirkan pada setiap versi Firefox. Semuanya ditulis untuk memberikan informasi yang diperlukan oleh pengembang. Terima kasih.

+ +
{{ListSubpages("",1,1,1)}}
diff --git a/files/id/mozilla/gecko/index.html b/files/id/mozilla/gecko/index.html new file mode 100644 index 0000000000..a2fb0f60ab --- /dev/null +++ b/files/id/mozilla/gecko/index.html @@ -0,0 +1,69 @@ +--- +title: Gecko +slug: Mozilla/Gecko +translation_of: Mozilla/Gecko +--- +
+

Gecko adalah nama dari pengatur tata letak yang dikembangkan oleh Proyek Mozilla. It was originally named NGLayout. Gecko's function is to read web content, such as HTML, CSS, XUL, JavaScript, and render it on the user's screen or print it. In XUL-based applications Gecko is used to render the application's user interface as well.

+
+

Gecko di gunakan di banyak aplikasi, termasuk beberapa peramban (browsers), contohnya Firefox, SeaMonkey, dll. (for a complete list, please refer to Wikipedia's article on Gecko.) Products using the same version of Gecko have identical support for standards.

+ + + + + + + +
+

Documentation

+
+
+ Gecko FAQ
+
+ Frequently asked questions about Gecko.
+
+ Gecko DOM reference
+
+ Reference to the DOM.
+
+ Gecko event reference
+
+ Reference to events used within Gecko and Mozilla applications; for web-standard DOM events, see the DOM event reference.
+
+ Gecko versions and application versions
+
+ Versions of Gecko and the applications they're used in.
+
+ Introduction to Layout in Mozilla
+
+ Tech Talk on layout.
+
+ Embedding Mozilla
+
+ Using Gecko in your own application.
+
+ Character sets supported by Gecko
+
+ A list of the character sets supported by Gecko.
+
+ HTML parser threading
+
+ Description of multithreading in the HTML parser.
+
+ {{interwiki('wikimo', 'Gecko:Home_Page', 'Gecko Homepage on MozillaWiki')}}
+
+ Home for the active developers. Roadmaps and more up-to-date resources.
+
+

View All...

+
+

Community

+
    +
  • View Mozilla forums... {{DiscussionList("dev-tech-layout", "mozilla.dev.tech.layout")}}
  • +
+ +
+
+ Web Standards, XUL, Embedding Mozilla, Developing Mozilla
+
+
+

 

diff --git a/files/id/mozilla/index.html b/files/id/mozilla/index.html new file mode 100644 index 0000000000..ecbabce71c --- /dev/null +++ b/files/id/mozilla/index.html @@ -0,0 +1,13 @@ +--- +title: Mozilla +slug: Mozilla +tags: + - NeedsTranslation + - TopicStub +translation_of: Mozilla +--- +
+ {{draft}}
+

This will soon be an awesome landing page for Mozilla internals. For now, it's not.

+
+ {{LandingPageListSubpages}}
diff --git a/files/id/mozilla/localization/index.html b/files/id/mozilla/localization/index.html new file mode 100644 index 0000000000..ea5809653c --- /dev/null +++ b/files/id/mozilla/localization/index.html @@ -0,0 +1,30 @@ +--- +title: Pelokalan di Mozilla +slug: Mozilla/Localization +tags: + - ButuhPenerjemahan + - Landing + - Localization + - Mozilla + - NeedsTranslation + - Pelokalan + - Pendaratan + - Penerjemahan + - RintisanTopik + - TopicStub + - Translation + - l10n +translation_of: Mozilla/Localization +--- +

Pelokalan (L10n) adalah proses menerjemahkan antarmuka pengguna sebuah perangkat lunak dari satu bahasa ke bahasa yang lain, dan menyesuaikannya agar sesuai dengan kultur setempat. Semua sumber daya tersedia bagi siapa saja yang berminat dalam aspek teknis untuk terlibat dalam pelokalan, bagi para pengembang dan semua kontributor.

+ +

Lihat pula

+ +
+
Pelokalan MDN
+
Sumber daya ini mencakup pelokalan dokumentasi di MDN.
+
Pelokalan aplikasi
+
Kumpulan dokumen ini secara khusus digunakan untuk pelokalan aplikasi, termasuk aplikasi Firefox OS.
+
L10n
+
Dokumen referensi untuk API L10n yang digunakan Mozilla dalam pelokalan Firefox OS.
+
diff --git a/files/id/mozilla/localization/localizing_with_verbatim/index.html b/files/id/mozilla/localization/localizing_with_verbatim/index.html new file mode 100644 index 0000000000..14e7d665b6 --- /dev/null +++ b/files/id/mozilla/localization/localizing_with_verbatim/index.html @@ -0,0 +1,158 @@ +--- +title: Pelokalan dengan Verbatim +slug: Mozilla/Localization/Localizing_with_Verbatim +translation_of: Mozilla/Localization/Localizing_with_Pontoon +--- +

Verbatim adalah suatu alat berbasis web (khususnya Pootle yang dihosting Mozilla) untuk melokalkan konten web Mozilla. Alat tersebut dapat digunakan untuk melokalkan berbagai proyek Mozilla dan mampu mendukung bahasa apa saja. Panduan ini akan membantu Anda melakukan pelokalan proyek Mozilla pada umumnya. Tutorial yang disediakan di sini akan memberi Anda landasan yang bermanfaat dalam penggunaan Verbatim untuk melokalkan setiap proyek Mozilla yang ingin Anda ikut sertakan dalam upaya komunitas pelokalan Anda. Kita akan membahas proyek-proyek khusus yang sedang menggunakan Verbatim, cara untuk mulai menggunakan Verbatim, dan pekerjaan-pekerjaan yang umumnya dapat diselesaikan dengan Verbatim.

+ +

Mulai menggunakan Verbatim

+ +

Being that it is web-based, localizers must be online to use Verbatim. There are essentially two ways to get started with Verbatim: start a new localization or join an existing localization community's efforts. Either way, you will need to follow these steps to start working on a Verbatim project.

+ + + + + + + + + + + + + + + + + + + + + + +
Start a new localization on VerbatimJoin an existing localization on Verbatim
+
    +
  1. Point your browser to http://localize.mozilla.org. This is where Verbatim is hosted.
  2. +
+
+
    +
  1. Point your browser to http://localize.mozilla.org. This is where Verbatim is hosted.
  2. +
+
+
    +
  1. If you have a Mozilla LDAP account, simply sign in using your LDAP credentials. If not, register for an account and sign in once you've completed registration. The links for both are located in the upper right-hand corner of the page.
  2. +
+
+
    +
  1. If you have a Mozilla LDAP account, simply sign in using your LDAP credentials. If not, register for an account and sign in once you've completed registration. The links for both are located in the upper right-hand corner of the page.
  2. +
+
+
    +
  1. File a bug using this prefilled bugzilla template. Add your locale code and language name to the description field, as well as any other information you'd like to share. See the following example.
  2. +
+ +
Example: I would like to request that you add the en-US as a new localization in Verbatim. The langauge is English. Also, I like cookies. Lots and lots of cookies. I can easily be motivated by any and all baked goods.
+
+
    +
  1. Contact the community to find out which projects they need you to concentrate your efforts on. See the following example for what you could include in your email to the community leaders.
  2. +
+ +
Example: I would like to join your localization efforts on Verbatim for this locale. Where would be the best place for me to begin? Also, I would like to buy you a drink to encourage you to let me join the team!
+
+ +

Now that you're registered and logged in, we'll outline the general translation workflow, using the MDN project page as our example.

+ +

Translating

+ +

First thing's first, you need to find untranslated source strings to translate.

+ +
    +
  1. Navigate to the MDN project page.
  2. +
  3. Select your language from the Overview tab.
  4. +
  5. Now click on the the Translate tab. This tab will display the directories for the MDN user interface.
  6. +
  7. Select the LC Messages directory. This is where the project's .po files containing translatable strings are located. You will now see an overview of each .po file.
  8. +
  9. In the summary column, the number of words untranslated will be shown as a link. Click on that link to be taken directly to the first string that needs to be translated.
  10. +
+ +

Now you're ready to contribute translations and you won't believe how easy it is. Check it out, you can contribute translations in two simple steps:

+ +
    +
  1. Simply type your translation in the box to below the English string
  2. +
  3. Select Suggest. If you have approval permission, select Submit. You will then be taken to the next string that needs translating.
  4. +
  5. Hooray! You're translating! Repeat steps one and two for the remainder of the untranslated strings.
  6. +
+ +
Note: If you come across a string that already has a suggested translation, you can still suggest your own translation if you feel it is more accurate.
+ +

Some extra cool features on Verbatim

+ +

Here are a few additional items about the Verbatim interface that you should be aware of. Some of these can be seen in the screen shot below.

+ +

Translate Tab.png

+ + + +

Additional tasks

+ +

If you are a localizer with approval priviledges, here are a few more tasks that you should be aware of.

+ +

Review suggested translations

+ +
    +
  1. Click on the Review tab. It will show how many strings are waiting for review for each .po file.Review Tab1.png
  2. +
  3. Select Review suggestions to start approving suggestions. It will take you to the first string that needs to be reviewed.
  4. +
  5. You can accept the suggestion by clicking the green checkmark or reject the suggestion by clicking the red X (see the screen shot from the previous section).
  6. +
+ +

It is important to note that only submitted strings will appear in your localized pages. Neither suggestions nor fuzzy strings will appear. Before commiting your final localized product, make sure all strings have been submitted.

+ +

Using VCS on Verbatim

+ +

VCS (Version Control System) is the repository system we use to update the project's strings as well as push your translated content onto the web. The difference between the two tasks is simply a matter of which link to click.

+ +

VCS.pngTo push your strings onto the web and see your changes, simply select the Commit to VCS link underneath each file name. It usually takes about an hour before you can see your changes on the project site.

+ +

To update your .po files with new untranslated strings, simple select the Update from VCS link underneath each file name.

+ +

 

+ +

+Note: Some projects are automatically updated nightly while others require you to manually update them to receive new source content. Be sure to pay close attention to this, as it can alter your workflow.
+ +

Translating Verbatim files with an external application

+ +

While in the Translate tab, you have the option to export the .po and .xliff files and translate the strings with an external application (i.e., a text editor or translation memory tool).

+ +
    +
  1. To download the .po file, select the Download link found underneath each file name. To download the .xliff file, select the Download XLIFF link.
  2. +
  3. Proceed to translate the strings using your selected tool.
  4. +
+ +

Once you've finished your translations, you'll need to upload your file to Verbatim. You can do this from the Translate tab.

+ +
    +
  1. Navigate to the bottom of the files list to the Upload File section.
  2. +
  3. Click on the Browse button and select the file you wish to upload.
  4. +
  5. Select an upload setting from the options provided.
  6. +
  7. Once your upload setting has been selected, click Upload.
  8. +
+ +
+

Important: There have been some problems in the past with community members updating their source strings while others are in the process of localizing the previous updated files. This can cause community members to overlook new source strings, producing untranslated strings in a localized project. Be sure to coordinate these manual updates within your community to avoid this problem.

+
+ +

You're ready to go!

+ +

Whew! You've arrived at the end! Time to take what you've learned and put it to good use spreading Mozilla to everyone in your region. Have fun and let us know if you run into any difficulties. We'll be happy to help in any way we can.

+ +

 

+ +

Back: Quick Start Guide

diff --git a/files/id/mozilla/localization/quick_start_guide/index.html b/files/id/mozilla/localization/quick_start_guide/index.html new file mode 100644 index 0000000000..216207c9c4 --- /dev/null +++ b/files/id/mozilla/localization/quick_start_guide/index.html @@ -0,0 +1,50 @@ +--- +title: Panduan memulai cepat pelokalan +slug: Mozilla/Localization/Quick_start_guide +tags: + - ButuhPenerjemahan + - Guide + - Localization + - Mozilla + - NeedsTranslation + - Panduan + - Pelokalan + - Penerjemahan + - RintisanTopik + - TopicStub + - Translation +translation_of: Mozilla/Localization/Quick_start_guide +--- +

Selamat datang di pelokalan Mozilla (singkatnya L10n)!

+ +

Entah Anda berada di sini untuk memulai pelokalan Anda sendiri dalam proyek Mozilla ataupun untuk bergabung dalam upaya pelokalan yang sedang berlangsung, Anda datang ke tempat yang tepat! Panduan ini memuat semua informasi dasar dan teknis yang Anda perlukan untuk terlibat dalam program L10n Mozilla. Kami akan menunjukkan kepada Anda langkah-langkah untuk memulainya, dari pengaturan awal hingga pengetesan dan perilisan pelokalan Anda sendiri. Dalam prosesnya, Anda akan mempelajari berbagai proyek yang di dalamnya Anda dapat berkontribusi dan semua alat yang digunakan untuk pelokalan.

+ +

Bilamana kita berhadapan dengan kasus-kasus khusus, kita mengambilnya dari proyek Firefox sebagai proyek yang paling banyak dilakukan pelokalan di Mozilla. Dan ketika Anda hampir menyelesaikan panduan ini, Anda seharusnya mampu melakukan perubahan pada pengaturan lokal Firefox Anda dan menyaksikan perubahan pada antarmukanya. Akhir kata, setelah Anda menyelesaikan panduan ini, Anda akan memiliki semua alat yang diperlukan untuk mulai berkontribusi!

+ +

Ingat, panduan ini hanya memuat instruksi seputar aspek teknis L10n Mozilla saja. Kunjungi halaman Proses L10n untuk mempelajari keseluruhan prosesnya.

+ +
+

Pengaturan awal

+Persiapan teknis sebelum melakukan pelokalan.
+ +
+

Tahap penerjemahan

+Tutorial penggunaan alat L10n untuk penerjemahan.
+ +
+

Tahap QA

+Tutorial pengetesan L10n.
+ +
+

Tahap perilisan

+Langkah-langkah mengirimkan pekerjaan pelokalan Anda.
+ +
Keempat tahap ini merupakan sisi teknis dari program L10n. Untuk mempelajari lebih lanjut tentang semua ini, silakan klik salah satu tautan di atas. Untuk mendapatkan gambaran besarnya, kami sarankan Anda memulai dengan boks hijau dan melanjutkannya secara bertahap.
+ +

 

+ +
Note: This guide is written for two types of contributors: those starting a new localization and those joining an existing localization. It is important to know which information applies to which type of contributor. To help you filter through to the most applicable information, note that all information that is unique to those starting a new localization will be in orange font. All information that is unique to those joining an existing localization will be in blue font.
+ +

 

+ +

{{ Next("Localization_Quick_Start_Guide/Initial_setup") }}

diff --git a/files/id/mozilla/localization/quick_start_guide/qa_phase/index.html b/files/id/mozilla/localization/quick_start_guide/qa_phase/index.html new file mode 100644 index 0000000000..0ee69f43e4 --- /dev/null +++ b/files/id/mozilla/localization/quick_start_guide/qa_phase/index.html @@ -0,0 +1,197 @@ +--- +title: Tahap QA +slug: Mozilla/Localization/Quick_start_guide/QA_phase +translation_of: Mozilla/Localization/Quick_start_guide/QA_phase +--- +

Setelah hasil kerja keras anda dalam melokalisasi kami yakin bahwa anda tidak hanya ingin melihat hasil kerja anda tapi juga ingin memastikan bahwa itu tepat! Jika anda tidak begitu awam dengan kode, anda pasti khawatir akan merusak sesuatu (oops!). Sekarang kami akan menuntun anda melakukan test kualitas pekerjaan anda untuk memastikan anda berada di jalur yang tepat.

+ +

Jika anda melokalisasi halaman Mozilla, hasil pekerjaan anda akan ditampilkan segera setelah anda menyelesaikannya tanpa membutuhkan paket bahasa. Seperti halnya kasus ini, bagian dari pedoman ini tidak sepenuhnya dapat di aplikasikan oleh anda. Silahkan tekan tombol Next pada bagian paling bawah laman jika anda ingin melewati.

+ +

Untuk melihat hasil pekerjaan anda di Firefox (atau dalam aplikasi Mozilla yang lain), anda butuh paket bahasa yang terinstal pada direktori anda.

+ +

Manual & automated builds

+ +

Dengan menekan tombol, beberapa alat L10n (seperti Narro and Koala) secara otomatis membuat paket bahasa untuk anda. Jika anda menggunakan salah satu dari alat tersebut, silahkan menuju ke bagian Melihat pekerjaan anda, Sekarang mari menuju ke pembuatan paket bahasa anda sendiri secara manual.

+ +
Note: Remember all of those pre-requisite tools we asked you to install in the initial setup? Here's where you'll need almost all of them. If you haven't installed them yet, now is the time to do it.
+ +

Persiapan

+ +

Kita akan menggunakan file direktori berikut sebagai contoh:

+ +
your working directory (root)/
+    mozilla-aurora (en-US source, pulled from http://hg.mozilla.org/releases/mozilla-aurora  )/
+    l10n-central (directory for L10n directories, one per L10n; often referred to as "l10n base")/
+       your-locale-code (a directory with your L10n files, in this example we'll use x-testing)
+
+Example: root/mozilla-aurora & root/l10n-central/x-testing
+
+ +

Additionally, you will need to c

+ +

Please either follow the above structure closely or adjust the commands below according to your custom setup.

+ +

To copy this file to the appropriate directory, do the following:

+ +
    +
  1. Navigate to your working directory from your command-line terminal (i.e., where you created the folder structure described above).
  2. +
  3. Enter the following commands:
  4. +
+ +
mkdir -p l10n-central/x-testing/toolkit/
+
+cp mozilla-aurora/toolkit/locales/en-US/defines.inc l10n-central/x-testing/toolkit/defines.inc
+
+ +

Tah-dah! Copied!

+ +

Finally, you will need a file called .mozconfig to proceed with manual builds. This file contains the necessary build instructions.

+ +

To create and configure this file, follow these instructions:

+ +
    +
  1. Update the Mozilla source code:
  2. +
+ +

$ cd mozilla-aurora
+ $ hg pull -u

+ +
    +
  1. Enter the following command to create the .mozconfig file: $ nano -w .mozconfig
  2. +
  3. Enter the following lines in your .mozconfig file:
  4. +
+ +
mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/../firefox-build
+ac_add_options --disable-compile-environment
+ac_add_options --with-l10n-base=../l10n-central # path relative to MOZ_OBJDIR
+ac_add_options --enable-application=[browser or mail]
+
+ +

You will need to specify which application you're localizing in the fourth line (e.g., for Firefox, that's browser, Thunderbird would be mail).

+ +
    +
  1. Enter the following command to perform the configuration: $ mach configure
  2. +
  3. Once your command-line finishes spitting out the config command's output, navigate to the newy created directory: $ cd ../firefox-build/browser/locales
  4. +
+ +

Now you're ready to build! At this point you can choose between two build options. You can either:

+ + + +

Visit the links above to learn how to make these testing builds.

+ +

Testing your L10n & seeing your work

+ +

Now that you have your langpack or L10n repack, let's discuss seeing your work and testing it in the application.

+ +

Testing the langpack will put you one step closer to having your localization added to the L10n releases. Follow the steps below to test your localization:

+ +
    +
  1. Install Aurora in your preferred language.
  2. +
  3. Install the .xpi langpack you just created (or exported).
  4. +
  5. Set your language using the Quick Locale Switcher or Locale Switcher add-ons by navigating to Tools->Language->Your localization's language code.
  6. +
  7. Restart your browser and start testing!
  8. +
+ +

Now you should be able to see all of your work up to this point. Click here for guidelines on how to test your localization.

+ +

Don't lose your work!

+ +

You're work is SO important! We would really hate to see you lose any of it. After you test your localization, you should send it to a remote repository, which will serve as a backup for your work and will let others follow your progress. We're going to go through the process below.

+ +

The official localization teams use repositories at hg.mozilla.org. Before a team becomes official, we like to get the localizers comfortable with the Hg commands that allow for cloning, pulling, committing, and pushing work to an experimental repository.  We use a web service called Bit Bucket to start the learning process.

+ +
Note: You must have Mercurial configured before you begin. That step is back on the initial setup page. If you haven't done that yet, don't worry, we'll wait for you!
+ +

Pushing to your repository

+ +

There are a couple of things you should take note of before you push to your repository:

+ + + +

The instructions below will help you learn how to use your Hg repository.

+ +
    +
  1. After your new repository is created by the l10n-drivers, please visit the URL for your repo. We'll use x-testing here for our example. You can do this by entering the following URL into your browser: http://hg.mozilla.org/l10n-central/x-testing
  2. +
  3. Now, navigate to your locale's directory on your local machine.
  4. +
+ +

If you're using Koala, this should be located at /path/to/your/koala.project/locale/3.6/x-testing, otherwise, it should be located at /path/to/your/working_dir/l10n_base/x-testing.

+ +

In this directory, you should have an hg repository. You might have created it yourself by running hg init or hg clone or you might have had it created by Koala when you were setting up a new localization project. Also at this point, you shouldn't have any uncommitted changes (i.e., running the hg status command should show nothing). Let's see what the last revision in this repository is.

+ +
    +
  1. Enter the following command: $ hg log -l 1
  2. +
+ +

You should see an output similar to the one below:

+ +
changeset:   0:7c543e8f3a6a
+tag:         tip
+user:        Your Name <email@example.com>
+date:        Mon Nov 23 18:08:25 2009 +0100
+summary:     Added search bar strings
+
+ +
    +
  1. Now compare the local repository on your machine with the remote Hg repository by entering this command: $ hg outgoing http://hg.mozilla.org/l10n-central/x-testing
  2. +
+ +

The hg outgoing command compares the two repositories and lists all changesets that are present locally, but not in the remote repository. These changesets will need to be "pushed" to the remote repository. You can expect to see output like this:

+ +
comparing with http://hg.mozilla.org/l10n-central/x-testing
+searching for changes
+
+changeset:   0:7c543e8f3a6a
+tag:         tip
+user:        Your Name <email@example.com>
+date:        Mon Nov 23 18:08:25 2009 +0100
+summary:     Added search bar strings
+
+ +
    +
  1. Let's now push this changeset. Enter the following command: hg push http://hg.mozilla.org/l10n-central/x-testing
  2. +
  3. Mercurial will connect to your repo and ask you to provide your account information (i.e., the username and the password).
  4. +
+ +
real URL is http://hg.mozilla.org/l10n-central/x-testing
+pushing to http://hg.mozilla.org/l10n-central/x-testing
+searching for changes
+http authorization required
+realm: hg.mozilla.org HTTP
+user: your_id
+password:
+
+ +

After you enter your account information, the changeset will be pushed.

+ +
adding changesets
+adding manifests
+adding file changes
+added 1 changesets with 2 changes to 2 files
+bb/acl: your_id is allowed. accepted payload.
+quota: 979.7 KB in use, 150.0 MB available (0.64% used)
+
+ +

Your changeset has been successfully pushed to your repository!

+ +

As you begin to move through your translations, you should commit the changes locally and push your work to this experimental repository. For instance, if you have finished translating all the .dtd and .properties files in your x-testing/browser/chrome/browser/ directory, then you should run these commands:

+ +
$ hg status
+$ hg commit -m "Translated browser/chrome/browser/"
+$ hg outgoing
+$ hg push http://hg.mozilla.org/l10n-central/x-testing
+ +

Note that due to the distributed nature of Hg, hg commit saves the changes locally (i.e., in your computer's Hg repository). You can see the history of commits with hg log. After doing hg commit, you still need to send the changes to the remote repository. This is where hg push comes in. This sends your commits to the remote repository.

+ +

Now you're ready to proceed to the release phase!

+ +

 

+ +

{{ PreviousNext("Localization_Quick_Start_Guide/Translation_phase", "Localization_Quick_Start_Guide/Release_phase") }}

diff --git a/files/id/mozilla/localization/web_localizability/index.html b/files/id/mozilla/localization/web_localizability/index.html new file mode 100644 index 0000000000..e4ff426a11 --- /dev/null +++ b/files/id/mozilla/localization/web_localizability/index.html @@ -0,0 +1,33 @@ +--- +title: Kemampulokalan Web +slug: Mozilla/Localization/Web_Localizability +tags: + - Internationalization + - Localizability + - Localization + - NeedsTranslation + - TopicStub + - Web Development +translation_of: Mozilla/Localization/Web_Localizability +--- +

Kemampulokalan (atau singkatnya l12y) adalah karakteristik yang terkandung dalam suatu aplikasi atau konten yang memungkinkan untuk dilakukan pelokalan. Daftar berikut ini berisi tautan ke halaman yang menjabarkan langkah-langkah untuk membuat konten web dapat dilokalkan.  Dokumentasi dibagi menjadi 4 bagian:

+ +
    +
  1. How to create localizable content.
  2. +
  3. How to choose the right localization format.
  4. +
  5. How to create localizable web applications.
  6. +
  7. How to set up the infrastructure for localization.
  8. +
+ +

Why localizability is important

+ +

There are many reasons why you should start thinking about making your web app localizable as soon as possible.

+ +
    +
  1. You will make localizer's life easier, for which they will be grateful.
  2. +
  3. You will have quality content, localized and adapted to the needs of the local market.
  4. +
  5. Extending you web app to support new languages will be easy.
  6. +
  7. The content will be easier to maintain and update.
  8. +
  9. You will end up writing more semanticly-correct code, which is good for your SEO.
  10. +
  11. By reviewing your content and code for l12y, you will find and fix bugs in your original language too.
  12. +
diff --git a/files/id/mozilla/mercurial/basics/index.html b/files/id/mozilla/mercurial/basics/index.html new file mode 100644 index 0000000000..e3b797d0f2 --- /dev/null +++ b/files/id/mozilla/mercurial/basics/index.html @@ -0,0 +1,60 @@ +--- +title: Dasar-dasar Mercurial +slug: Mozilla/Mercurial/Basics +translation_of: Mozilla/Mercurial/Basics +--- +

Saya ingin berbagi pengetahuan denganmu tentang Mercurial yang mungkin dapat melindungimu dari frustasi. Halaman ini memang sinis dan survival-oriented. Tetapi saya masih menganggap Mercurial sedikit lebih baik dari pada CVS. —jorendorff 16:06, 12 May 2008 (PDT)

+ +

 

+ +

Expectations

+ +

Mercurial bukan CVS. Perintah-perintahnya tidak sama. The konsepnya tidak sama. Bagaimana Mercurial berbeda dengan CVS?

+ +

Sepanan ini sudah terisi. Anda dapat menembak dirimu sendiri. Anda dapat kehilangan pekerjaan. Perkakasa sudah mencoba melindungi Anda , tetapi kecelakan tetap dapat terjadi. Ada dua kesalahan umum: (a) Anda menjalankan perintah tanpa mengetahui apa yang akan dilakukan oleh perintah tersebut; (b) Anda melakukan hg commitatau hg qrefresh dengan salah paham pada status direktori kerja Anda. Oleh karena itu tanpa sengaja Anda membuat commit pada perubahan yang sebenarnya tidak ingin Anda buat commit; atau tanpa sengaka Anda membuat commit sebuah merge yang rusak; dlsb. Seringkali kesalahan seperti ini tidak langsung ketahuan.

+ +

Forewarned is forearmed. Don't do these things. Don't run commands without knowing what they're going to do—hg help is your friend. Don't commit without diffing and thinking. And don't let yourself get into "play mode" and stop paying attention to the fact that what you're playing with is your own uncommitted work.

+ +

Mercurial is not magic dust. Mercurial is flexible, powerful, and fun. It lets you attempt stuff you never would have tried in CVS. But of course not everything turns out to have been a good idea. (For example, we tried sharing patch queues. It sort of sucked.)

+ +

Avoiding trouble

+ +

Use the latest stable release of Mercurial.

+ +

Learn how to get your bearings. Use read-only commands (like hg status, hg head, hg parents, hg log, hg diff, hg outgoing) to check the status of your repository. This is a key skill.

+ +

Configure a merge program and make sure you know how to use it. DO IT NOW. Otherwise you will likely screw up your repository at some point.

+ +

Mercurial doesn't leave conflict markers in your files; instead, it wants you to fix the conflicts immediately, using a merge program (like kdiff3) which it can launch for you.

+ +

This can be error-prone. By default, Mercurial uses the first merge program it finds on your system, and merge programs can have a learning curve. Mercurial does not do a good job of detecting busted merges and refusing to proceed, so just by closing a window you can unwittingly put yourself in a bad state. Bad merges may lead to seemingly inexplicable Mercurial behavior in the future.

+ +

If a merge fails, make sure Mercurial knows that it has failed. When you're first learning the ropes, merges often go wrong. You might see this message:

+ +
0 files updated, 0 files merged, 0 files removed, 1 files unresolved
+There are unresolved merges, you can redo the full merge using:
+  hg update -C 2
+  hg merge 1
+
+ +

This means some conflicts weren't resolved during the merge. If you don't know exactly what they are and how to fix them, use that hg update -C command to tell Mercurial that you've given up on that merge.

+ +

If you don't, Mercurial won't know, and the next time you commit, it'll make a merge changeset. This is bad. The result can look a lot like accidentally destroying a bunch of work, actually, but the damage can be undone.

+ +

If hg parents shows two parents, you're merging.

+ +

If you use Mercurial Queues, back up your work. hg qrefresh destructively replaces the old patch with the new one! Use hg qinit -c to create a separate backup repository for your patches and hg commit --mq -m backup regularly.

+ +

Don't use Mercurial Queues in a repository that someone might pull from since applied (non-public) patches would also be pulled.

+ +

Recovering

+ +

Oops! Mercurial cut off your arm!

+ +

Don't randomly try stuff to see if it'll magically fix it. Remember what you stand to lose, and set down the chainsaw while you still have one good arm.

+ +

Get help on IRC. Try #hg or #developers on Mozilla IRC or #mercurial on freenode.

+ +

 

+ +

{{ languages( { "es": "es/Lo_b\u00e1sico_de_Mercurial", "fr": "fr/Les_bases_de_Mercurial", "ja": "ja/Mercurial_basics" } ) }}

diff --git a/files/id/mozilla/mercurial/index.html b/files/id/mozilla/mercurial/index.html new file mode 100644 index 0000000000..3e940e7690 --- /dev/null +++ b/files/id/mozilla/mercurial/index.html @@ -0,0 +1,45 @@ +--- +title: Mercurial +slug: Mozilla/Mercurial +tags: + - Developing Mozilla + - Mercurial + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Mercurial +--- +

 

+ +
+

Please refer to Mercurial For Mozillians at ReadTheDocs for current best-practices around Mercurial, including many helpful extra tools and guidelines that make using Mercurial fast and easy.

+
+ +

Mercurial (also known as "hg"), is the distributed version control software used for the development of Firefox, Thunderbird, and the shared Gecko core. It replaced CVS after Mozilla 1.9 was branched.

+ +

hg is the Mercurial command-line tool, Hg being the chemical symbol for the element mercury.

+ +

Installation, configuration, and getting the source

+ +

See Installing Mercurial for installation and configuration tips.

+ +

See Getting Mozilla Source Code Using Mercurial for getting a tree to build.

+ +

Learning to use Mercurial

+ +

If you are new to Mercurial, you should start with the official guide.

+ +

Then, move on to Mercurial basics and Mercurial FAQ and the version control tool docs for Mozilla-centric Mercurial information.

+ +

Further reading

+ +

The Mercurial tag lists the Mercurial-related articles on MDN.

+ +

And on wiki.mozilla.org, these helpful pages:

+ + + +

{{ languages( { "es": "es/Mercurial", "fr": "fr/Mercurial", "ja": "ja/Mercurial" } ) }}

diff --git a/files/id/mozilla/persona/index.html b/files/id/mozilla/persona/index.html new file mode 100644 index 0000000000..529d510e4d --- /dev/null +++ b/files/id/mozilla/persona/index.html @@ -0,0 +1,126 @@ +--- +title: Persona +slug: Mozilla/Persona +translation_of: Archive/Mozilla/Persona +--- +
+

Tetap berhubungan atau dapatkan bantuan!

+ +

Ikuti blog kami, bergabung dalam milis kami, atau cari kami dalam #identity di IRC.

+
+ +

Mozilla Persona adalah Sistem otentikasi yang sepenuhnya aman dan desentralisasi untuk web berdasarkan pada protokol BrowserID. Untuk memastikan Persona berkerja dimana saja dan untuk siapa saja, Mozilla saat ini mengoperasikan serangkaian kecil optional, centralized services yang terkait dengan Persona.

+ +

Mengapa Anda seharusnya menggunakan Persona pada situs web anda?

+ +
    +
  1. Persona sepenuhnya menghilangkan password situs-spesifik, membebaskan pengguna dan situs jejaring dari beban dalam menciptakan, mengatur, dan menyimpan kata sandi dengan aman.
  2. +
  3. Persona mudah digunakan. Hanya dengan dua kali klik pengguna Persona dapat masuk kedalam sebuah situs baru seperti Voost atau The Times Crossword, melewati kesulitan yang berhubungan dengan pembuatan akun.
  4. +
  5. Persona mudah diimplementasikan. Pengembang dapat menambah Persona kedalam sebuah situs hanya dalam semalam.
  6. +
  7. Yang terbaik dari semuanya, tidak adanya ketergantungan. Pengembang mendapat alamat-alamat surel yang telah diverifikasi dari semua pengguna mereka, dan pengguna situs dapat menggunakan surel apapun dengan Persona.
  8. +
  9. Persona dibuat dengan protokol BrowserID. Sekali penyedia peramban populer menggunakan BrowserID, mereka tidak perlu lagi ke Mozilla untuk log in.
  10. +
+ +

Baca Memulai!

+ +
Note: Persona sedang dalam pengembangan. ikuti blog kami untuk menemukan fitur-fitur baru, atau bergabunglah dengan milis kami dan tawarkan umpan-balik anda!
+ +

Gunakan Persona untuk laman anda

+ + + + + + + + + + + + +
+

Memulai

+ +
+
Kenapa Persona?
+
Pelajari tentang alasan Persona untuk pendukung dalam laman anda, dan bandingkan dengan sistem identitas otentikasi lainnya.
+
Pengaturan cepat
+
Pedoman cepat bagaimana cara untuk menambahkan Persona dalam laman/website anda.
+
+
+

Persona API

+ +
+
Referensi navigator.id API
+
Referensi untuk the navigator.id object, yang mana web developers dapat gunakan untuk memadukan Persona kedalam laman.
+
Verifikasi API
+
Referensi untuk remote verification API hosted at https://verifier.login.persona.org/verify.
+
+
+

Panduan

+ +
+
Perhatian Keamanan
+
Latihan dan Teknik untuk memastikan Persona anda aman.
+
Kococokan Peramban (Browser)
+
Pelajari dengan cermat peramban/browser mana yang mendukung Persona.
+
Internasionalisasi
+
Pelajari bagaimana Persona menangani Bahasa yang berbeda.
+
+
+
+
Pustaka dan plugins
+
Temukan pustaka Drop-in untuk Bahasa pemrograman favorit, web framework, blog, atau sistem konten manajemen anda.
+
Persona cookbook
+
Contoh kode sumber/source code untuk laman Persona. Termasuk snippets dalam C# (MVC3), PHP, Node.JS, dan lainnya.
+
Branding resources
+
Tombol Sign in dan gambar lainnya untuk membantu menampilkan Persona kepada anda.
+
+
+ + + + + + + + +
+

Informasi untuk penyedia layanan identitas

+ +

Jika anda penyedia layanan surel atau layanan penyedia Identitas lainnya, Periksa tautan/link dibawah ini untuk mempelajari bagaimana menjadi penyedia layanan Identitas untuk Persona.

+ +
+
Ringkasan IdP
+
Gambaran Persona Identity Providers.
+
Implementasi IdP
+
Pedoman teknis terinci untuk menjadi idP (Penyedia layanan Identitas).
+
Tips Pengembangan
+
Kumpulan tips dan trik yang berguna saat mengembangkan penyedia identitas baru.
+
.well-known/browserid
+
Ringkasan setruktur dan tujuan dari .well-known/browserid file, yang mana IdPs gunakan untuk meyatakan dukungannya.
+
+
+

Proyek Persona

+ +
+
Istilah
+
Definisi istilah BrowserID and Persona.
+
FAQ
+
Jawaban untuk pertanyaan umum.
+
Ringkasan Protokol
+
Ringkasan teknik menengah yang mendasar dari BrowserID protocol.
+
Keriptografi
+
lihat konsep kriptografi dibalik Persona dan BrowserID.
+
Sepesifikasi
+
Detail teknis mendalam langsung sisini.
+
Laman Persona
+
To get Persona going, we're hosting three services at https://login.persona.org: a fallback Identity Provider, a portable implementation of the {{ domxref("navigator.id") }} APIs, and an identity assertion verification service.
+
Kode sumber Persona
+
The code behind the Persona website lives in a repository on GitHub. Patches welcome!
+
+
+ +

 

+ +
 
diff --git a/files/id/mozilla/projects/index.html b/files/id/mozilla/projects/index.html new file mode 100644 index 0000000000..c1e43934a2 --- /dev/null +++ b/files/id/mozilla/projects/index.html @@ -0,0 +1,14 @@ +--- +title: Projects +slug: Mozilla/Projects +tags: + - Mozilla + - NeedsContent + - NeedsTranslation + - Projects + - TopicStub +translation_of: Mozilla/Projects +--- +

{{ draft() }}

+

Below you'll find links to documentation about various Mozilla projects; these are often parts of Firefox or other products, but may also be used in other projects as well.

+

{{ LandingPageListSubpages() }}

diff --git a/files/id/mozilla/projects/nss/index.html b/files/id/mozilla/projects/nss/index.html new file mode 100644 index 0000000000..3f7f3ed094 --- /dev/null +++ b/files/id/mozilla/projects/nss/index.html @@ -0,0 +1,180 @@ +--- +title: Network Security Services +slug: Mozilla/Projects/NSS +translation_of: Mozilla/Projects/NSS +--- +

Keamanan Jaringan Layanan (NSS) adalah satu set perpustakaan yang dirancang untuk mendukung pengembangan cross-platform dari klien dan server aplikasi keamanan-diaktifkan. Aplikasi yang dibangun dengan NSS dapat mendukung SSL v2 dan v3, TLS, PKCS # 5, PKCS # 7, PKCS # 11, # 12 PKCS, S / MIME, sertifikat X.509 v3, dan standar keamanan lainnya.

+ +

Untuk informasi rinci tentang standar yang didukung, lihat Ikhtisar NSS. Untuk daftar pertanyaan yang sering diajukan, lihat FAQ.

+ +

NSS tersedia di bawah Mozilla Public License. Untuk informasi tentang men-download NSS rilis sebagai file tar, melihat Unduh PKI Sumber.

+ +

Jika Anda seorang pengembang dan ingin berkontribusi NSS, Anda mungkin ingin membaca dokumen ikhtisar highlevel rincian internal NSS dan memulai dengan NSS.

+ + + + + + + + +
+

Dokumentasi

+ +

Informasi latar belakang

+ +
+
Ikhtisar NSS
+
Memberikan ringkasan singkat dari NSS dan kemampuannya.
+
NSS FAQ
+
Menjawab pertanyaan dasar tentang NSS.
+
Pengantar Kriptografi Public-Key
+
Menjelaskan konsep dasar kriptografi kunci publik yang mendasari NSS.
+
Pengantar SSL
+
Memperkenalkan protokol SSL, termasuk informasi tentang cipher kriptografi didukung oleh SSL dan langkah-langkah yang terlibat dalam jabat tangan SSL.
+
+ +

Mulai

+ +
+
NSS Pers
+
Halaman ini berisi informasi tentang rilis saat ini dan masa lalu dari NSS.
+
Dapatkan kode sumber dan Membangun
+
Petunjuk tentang bagaimana membangun NSS pada platform yang didukung berbeda.
+
Dapatkan Mozilla Source Code Menggunakan Mercurial
+
Informasi tentang dengan bekerja sama dengan Mercurial.
+
Dapatkan Mozilla Source Code Menggunakan CVS (usang)
+
Old usang dokumentasi CVS.
+
+ +

NSS API

+ +
+
Pengantar Keamanan Jaringan
+
Memberikan gambaran tentang perpustakaan NSS dan apa yang perlu Anda ketahui untuk menggunakannya.
+
Fungsi NSS Umum
+
Merangkum diekspor oleh perpustakaan NSS bersama API.
+
NSS Referensi
+
API yang digunakan untuk memanggil operasi SSL.
+
Pedoman API NSS
+
Menjelaskan bagaimana perpustakaan dan kode diatur, dan pedoman untuk mengembangkan kode (konvensi penamaan, penanganan error, benang pengaman, dll)
+
NSS Catatan Teknis
+
Link ke NSS catatan teknis, yang menyediakan informasi terbaru tentang fitur NSS baru dan dokumentasi tambahan untuk topik-topik lanjutan dalam pemrograman dengan NSS.
+
+ +

Alat, pengujian, dan rincian teknis lainnya

+ +
+
Membangun Petunjuk untuk NSS
+
Jelaskan bagaimana untuk memeriksa dan membangun NSS rilis.
+
+ +
+
NSS Tutorial Pengembang
+
Bagaimana membuat perubahan di NSS. Coding gaya, menjaga kompatibilitas ABI.
+
+ +
+
NSS Alat
+
Alat untuk mengembangkan, debugging, dan mengelola aplikasi yang menggunakan NSS.
+
Contoh Kode
+
Menunjukkan bagaimana NSS dapat digunakan untuk operasi kriptografi, penanganan sertifikat, SSL, dll
+
NSS 3.2 Uji Suite
+
Versi diarsipkan. Menjelaskan bagaimana menjalankan tes NSS standar.
+
NSS Laporan Kinerja
+
Versi diarsipkan. Link laporan kinerja untuk NSS 3.2 dan rilis berikutnya.
+
Enkripsi Teknologi Tersedia dalam NSS 3.11
+
Versi diarsipkan. Mencantumkan algoritma kriptografi yang digunakan oleh NSS 3.11.
+
NSS 3.1 loadable Sertifikat Akar
+
Versi diarsipkan. Menjelaskan skema untuk sertifikat CA memuat akar.
+
cert7.db
+
Versi diarsipkan. Format Umum database cert7.db.
+
+ +

PKCS # 11 informasi

+ + + +
+
+ +

CA sertifikat pre-loaded ke NSS

+ + + +
+
+ +

NSS dibangun di atas Netscape Portabel Runtime (NSPR)

+ +
+
Netscape Portabel Runtime
+
Halaman proyek NSPR.
+
NSPR Referensi
+
NSPR dokumentasi API.
+
+ +

informasi tambahan

+ + + +

Pengujian

+ + + +

Perencanaan

+ +

Informasi tentang perencanaan NSS dapat ditemukan di wiki.mozilla.org, termasuk:

+ + +
+

Masyarakat

+ +
    +
  • Lihat forum Mozilla Keamanan ...
  • +
+ +

{{DiscussionList ("dev-keamanan", "mozilla.dev.security")}}

+ +
    +
  • Lihat forum Mozilla Kriptografi ...
  • +
+ +

{{DiscussionList ("dev-tech-kripto", "mozilla.dev.tech.crypto")}}

+ + + + +
+ +

 

diff --git a/files/id/mozilla/projects/rhino/index.html b/files/id/mozilla/projects/rhino/index.html new file mode 100644 index 0000000000..8396dc5c22 --- /dev/null +++ b/files/id/mozilla/projects/rhino/index.html @@ -0,0 +1,25 @@ +--- +title: Rhino +slug: Mozilla/Projects/Rhino +tags: + - JavaScript + - Mozilla + - NeedsUpdate + - Rhino +translation_of: Mozilla/Projects/Rhino +--- +

Image:rhino.jpg

+ +

Rhino adalah implementasi sumber-terbuka dari JavaScript yang ditulis keseluruhannya dalam bahasa pemrograman Java. Ini biasanya disisipkan di aplikasi Java untuk memberikan fasilitas scripting pada pengguna. Rhino telah disisipkan di J2SE 6 sebagai mesin scripting utama.

+ +

Unduh Rhino

+ +

Bagaimana mendapatkan sumber dan binari

+ +

Dokumentasi Rhino

+ +

Informasi tentang Rhino bagi penulis script dan yang menyisipkannya.

+ +

Bantuan Rhino

+ +

Beberapa sumber jika anda mengalami kebuntuan.

diff --git a/files/id/pengembangan_web/index.html b/files/id/pengembangan_web/index.html new file mode 100644 index 0000000000..1033bba848 --- /dev/null +++ b/files/id/pengembangan_web/index.html @@ -0,0 +1,78 @@ +--- +title: Pengembangan Web +slug: Pengembangan_Web +translation_of: Web/Guide +--- +

Pengembangan web terdiri dari semua aspek dalam mengembangkan sebuah situs web atau aplikasi web

+ +

Pelajari cara membuat apapun dari situs web sederhana sampai yang kompleks , situs web yang sangat interaktif dengan menggunakan teknologi Web terbaru yang dapat anda temukan dari berbagai artikel di sini

+ + + + + + + + +
+

Topik Dokumentasi

+ +

Teknologi

+ +
+
Pengantar Ke Pengembangan Web
+
Sebuah paduan untuk belajar bagaimana mengembangkan Web .
+
HTML
+
HyperText Markup Language merupakan bahasa dasar untuk membuat halaman web dan dokumen lain yang di tampilkan di browser.
+
CSS
+
Cascading Style Sheets memungkinkan untuk mengatur tata letak dan desain halaman Web.
+
JavaScript
+
JavaScript merupakan bahasa scripting yang umum digunakan untuk membangun aplikasi web; juga di gunakan pada pengembangan perangkat lunak berbasis Mozilla.
+
DOM
+
The Document Object Model is an API for HTML and XML documents, providing a structural representation of the document that you can modify in order to alter its visual presentation.
+
AJAX
+
Asynchronous JavaScript and XML isn't so much a technology as a combination of technologies; using JavaScript and other modern web technologies together to create dynamic web applications.
+
XHTML
+
Extensible HyperText Markup Language is an XML-based HTML-like language that offers a stricter syntax than HTML.
+
SVG
+
Scalable Vector Graphics is an XML markup language for describing 2D vector graphics.
+
+ +

Strategi

+ +
+
Web standar
+
Learn how to make your Web site or application reach the largest number of users through compatibility with the open Web.
+
Desain Web Responsive
+
Use CSS to present the same content across all hardware platforms, from mobile phones to wide-screen, high-res desktop displays.
+
Writing forward-compatible websites
+
Best practices for creating websites that do not break when browsers are updated.
+
Pengembangan Web Mobile
+
Developing sites for be viewed on mobile devices involves some unique approaches that may not be familiar to those accustomed to developing for desktop browsers.
+
Pengembang Mozilla Web  FAQ
+
Frequently asked questions from Web developers. With answers!
+
+ +

Lihat Semua...

+
+

Komunitas

+ + + +

Alat

+ + + +

Lihat Semua...

+
+ +

 

diff --git a/files/id/sandbox/index.html b/files/id/sandbox/index.html new file mode 100644 index 0000000000..7d1668aea0 --- /dev/null +++ b/files/id/sandbox/index.html @@ -0,0 +1,201 @@ +--- +title: Sandbox +slug: Sandbox +translation_of: Sandbox +--- +

This is a page

+ +
+
Sample HTML Content
+
+
+ +

{{EmbedLiveSample('file')}}

+ +

coucou les amis

+ +

HTML

+ +
Sample HTML Content
+ +

CSS Content

+ +
Sample CSS Content
+ +

JavaScript Content

+ +
Sample JavaScript Content
+ +

Result

+ +

{{ EmbedLiveSample('asdfghjk') }}

+ + + +
<html>
+</html>
+ + + + + +

CSS Content

+ +
@ Compteur de style fisheye {
+  système: cyclique;
+  symboles: ◉;
+
+ +
+


+ <h1>CSS font-family</h1>
+ <p class="serif">This is a paragraph, shown in the Times New Roman font.</p>
+ <p class="sansserif">This is a paragraph, shown in the Arial font.</p>

+
+ +

+}
+
+.liste {
+    list-style: fisheye, cercle;
+}
+ +

Hello World

+ +

HTML

+ +
<p>Hello World</p>
+ +

{{EmbedLiveSample ( 'Linux is life')}}

+ +

Linux logo

+ +

logo couleur MDN (bleu)

+ + + +

Des trucs

+ +
+

Une note 

+ +
+

Un avertissement dans une note

+ +
+

Une note dans un avertissement dans une note

+ +
+ + +
+ + +
+ + +
+ + +
+ + +
+ +
+
+
+
+
+
+
+
+
+ + + +
+

une autre note

+ +
+

Une note dans une note

+
+ +

This is an example of how to use the MDN!

+
+ + + +

π×1=1×π=2π÷π=π\ Pi \ times 1 = 1 \ times \ pi = 2 \ pi \ div \ pi = \ pi

+ +

ππππππ\ Pi \ frac {\ pi} {\ pi} \ frac {\ frac {\ pi} {\ pi}} {\ pi}

+ +

ππππππ\ Pi \ frac {\ pi} {\ pi} \ frac {\ frac {\ pi} {\ pi}} {\ pi}

+ +

limjets13e3/XX2X\ Int \ limits_ {1} ^ {3} \ frac {e ^ 3 / x} {x ^ 2} \, dx

+ +

ln(x) dx = x[ln(x) - 1]l\ Int \ limits_ {1} ^ {3} \ frac {e ^ 3 / x} {x ^ 2} \, d+x

+ +

abcdefghijklmnopqrstuvwxyz\alphabet

+ +

πest un nombre irrationnel, et cela est le rapport entre la circonférence d'un cercle à son diamètre. Il est communément approchée comme 3,14159.\ pifacts {3}

+ +

contenu

+ + + +

Test live sample

+ +

HTML Content

+ +
<p>Hello World</p>
+ +

Result

+ +

{{ EmbedLiveSample('Test live sample') }}

+ +

+ +

Focus on a text field

+ +

HTML Content

+ +
<input type="text" id="myTextField" value="Text field.">
+<p></p>
+<button type="button" onclick="focusMethod()">Click me to focus on the text field!</button> 
+ +

CSS Content

+ +
Sample CSS Content
+ +

JavaScript Content

+ +
focusMethod = function getFocus() {
+  document.getElementById("myTextField").focus();
+} 
+ +

Result

+ +

{{ EmbedLiveSample('Focus_on_a_text_field') }}

+ +

Focus on a button

+ +

HTML Content

+ +
<button type="button" id="myButton">Click Me!</button>
+<p></p>
+<button type="button" onclick="focusMethod()">Click me to focus on the button!</button> 
+ +

CSS Content

+ +
Sample CSS Content
+ +

JavaScript Content

+ +
focusMethod = function getFocus() {
+  document.getElementById("myButton").focus();
+} 
+ +

Result

+ +

{{ EmbedLiveSample('Focus_on_a_button') }}

diff --git a/files/id/tools/accessibility_inspector/index.html b/files/id/tools/accessibility_inspector/index.html new file mode 100644 index 0000000000..ded237c344 --- /dev/null +++ b/files/id/tools/accessibility_inspector/index.html @@ -0,0 +1,196 @@ +--- +title: Accessibility Inspector +slug: Tools/Accessibility_inspector +tags: + - Aksesibilitas + - Alat + - DevTools + - Inspektur Aksesibilitas + - Panduan +translation_of: Tools/Accessibility_inspector +--- +
{{ToolsSidebar}}
+ +

The Accessibility Inspector (Inspektur Akesibilitas) menyediakan sebuah sarana untuk mengakses informasi penting terbuka untuk teknologi bantu di dalam halaman ini lewat pohon aksesibilitas, memperbolehkan anda untuk cek apa yang hilang atau jika tidak butuh perhatian. Artikel ini membawamu melewati fitur utama dari Accessibility Inspector (Inspektur Aksesibilitas) dan bagaimana menggunakannya.

+ +

Sebuah panduan yang (sangat) singkat untuk aksesibilitas

+ +

Accessibility (Aksesibilitas) adalah latihan untuk membuat website anda dapat digunakan oleh sebanyak mungkin orang . Ini berarti mencoba yang terbaik dari kamu untuk tidak mengunci siapapun untuk mengakses informasi karena kecacatan yang mungkin mereka miliki, atau keadaan pribadi seperti perangkat yang mereka gunakan, kecepatan dari koneksi jaringan mereka, atau geografis lokasi mereka atau lokal. Kamu dapat mencari informasi lebih luas di dalam bagian Accessibility (Aksesibilitas)  dalam Dokumen Web MDN.

+ +

Di sini kita terutama berbicara tentang mengekspos informasi kepada orang-orang dengan cacat visual - ini dilakukan melalui accessibility APIs (API aksesibilitas) yang tersedia di dalam web browser, yang memaparkan informasi tentang peran elemen-elemen yang berbeda di halaman Anda (misalnya, apakah mereka hanya teks, atau apakah mereka tombol, tautan, elemen formulir, dll?).

+ +

Semantic DOM elements have roles assigned to them by default that hint at what their purpose is. Sometimes, however, you need to use some non-semantic markup (e.g., {{htmlelement("div")}}s) to build a complex custom control, and the control won't have a default role that reflects its purpose. In such a situation, you can use WAI-ARIA role attributes to provide your own roles.

+ +

Roles and other information exposed by browser accessibility APIs are presented in a hierarchical structure called the accessibility tree. This is a bit like the DOM tree, except that it contains a more limited set of elements and slightly different information about them.

+ +

Assistive technologies like screenreaders use this information to find out what's on a web page, tell their users what's there, and enable them to interact with the page. The Accessibility Inspector also uses this information to provide valuable accessibility debugging capabilities in the DevTools.

+ +

Accessing the Accessibility Inspector

+ +

The Accessibility Inspector is available by default since Firefox 63:

+ +

Accessibility tab in firefox devtools, turned off, with a button labeled Turn On Accessibility Features

+ +

Initially, the DevTools accessibility features are turned off (unless you've already got them turned on in another browser tab, or got the Firefox accessibility engine started already, e.g., you might be a screenreader user or tester). This is because the accessibility engine runs in the background when the accessibility features are turned on. While it’s running, it slows performance and takes up memory; therefore it interferes with the metrics from other panels such as Memory and Performance as well as overall browser performance. For this reason, you should keep it turned off when you aren't specifically using it.

+ +

You can turn the features on using the Turn On Accessibility Features button.

+ +

Once the panel content loads, you can then turn it off again using the Turn Off Accessibility Features button available in the top-left corner, unless you have the accessibility engine running previously to operate a screenreader, in which case this button will be disabled.

+ +
+

Note: If you are using the accessibility features in multiple tabs, turning them off in one tab turns them off in all tabs.

+
+ +

Features of the Accessibility panel

+ +

The enabled accessibility panel looks like so:

+ +

Accessibility tab in firefox devtools, turned on, showing two information panels plus a button labelled Turn Off Accessibility Features

+ +

On the left-hand side, there is a tree diagram representing all the items in the accessibility tree for the current page. Items with nested children have arrows that can be clicked to reveal the children, so you can move deeper into the hierarchy. Each item has two properties listed:

+ + + +

On the right-hand side, you can see further information about the currently selected item. The listed properties are as follows:

+ + + +
+

Note: The exposed information is the same across all platforms — the inspector exposes Gecko's accessibility tree, rather than information from the platform accessibility layer.

+
+ +

Keyboard controls

+ +

The Accessibility tab is fully keyboard-accessible:

+ + + + + +

You can print the contents of the accessibility tree to json by right-clicking on an entry in the Accessibility tab and selecting Print to JSON:

+ +

+ +

When you do, you will get a new tab with the selected accessibility tree loaded into the JSON viewer:

+ +

+ +

Once opened, you can save or copy the data as necessary. The JSON viewer can also show you the raw JSON data on a separate tab in the viewer.

+ +

Check for accessibility issues

+ +

You can check for accessibility issues by clicking the drop-down menu next to: Check for issues. The available menu items include:

+ + + +

When you one of the menu items, Firefox scans your document for the type of issues you selected. Depending on the size and complexity of your document, this may take a few seconds. When the scan is complete, the left side of the Accessibility Inspector panel displays only the items that have that type of issue. In the right side of the panel, the Checks subpanel lists the specific issue with the selected node. For each type of issue, there is a Learn more link to further information on MDN Web Docs about the issue.

+ +

Check for "all" issues, with "contrast" and "text labels" selected

+ +

The menu items act as toggles. Select the item to view that type of issue; select the item again to clear the display of issues of that type.

+ +

Issues with a particular item are always displayed in the Checks subpanel as you browse the tree. The Check for issues buttons are a quick way to view all and only those items that have issues.

+ + + +

When the accessibility features are turned on, there are a number of useful additional features available in the DevTools, which are detailed below:

+ +

Context menu options

+ +

An extra context menu option is added, both for the general context menu on the web page when right/Ctrl + clicking a UI feature, and the HTML pane of the page inspector when right/Ctrl + clicking a DOM element:

+ +

context menu in the browser viewport, with a highlighted option: Inspect Accessibility Properties

+ +

context menu in the DOM inspector, with a highlighted option: Show Accessibility Properties

+ +

When you choose the Inspect Accessibility Properties/Show Accessibility Properties context menu options, the Accessibility tab is immediately opened to show the corresponding accessibility tree item and its properties.

+ +
+

Note: Some DOM elements do not have accessibility properties — in that case, the Inspect Accessibility Properties/Show Accessibility Properties context menu item is grayed out.

+
+ +

Highlighting of UI items

+ +

In the Accessibility tab, when the mouse hovers over accessibility items, you can see a semi-transparent highlight appear over the UI items they relate to, if appropriate. The role and name of the item will be shown in a small information bar along with color contrast information if appropriate. This is useful for determining how the items in the accessibility tree relate to the UI items on the actual page.

+ +

In the following example, you can see that the image has been highlighted and its role, graphic, name, "Road, Asphalt, Sky, Clouds, Fall", and the color contrast ratio, 3.46, appears in the information bar above it.

+ +

+ +

Color contrast

+ +

Contrast ratio information is particularly useful when you are designing the color palette for your website because if the contrast is not sufficient, readers with visual impairments such as low vision or color blindness will be unable to read the text. See Color contrast for details about recommended contrast ratios.

+ +

For example:

+ +

A screenshot of colour contrast highlighter where text contrast if below the AA WCAG threshold.

+ +

The color contrast in the image above is 2.86, so potentially not enough contrast to make it easy to read. Notice the warning symbol that indicates that the contrast fails to meet the acceptable contrast ratio.

+ +

As of Firefox 65, viewing this information for some foreground text that has a complex background image (e.g. a gradient) gives you a range of color contrast values. For example:

+ +

A screenshot of colour contrast highlighter where for text over gradient background with contrast satisfying the AAA WCAG guidelines.

+ +

In this example, the contrast ranges from 4.72 to 5.98. The numbers are followed by AAA and a checkmark in green, indicating that the large text has a contrast ratio of 4.5:1 or more, meeting the criteria for enhanced contrast, or Level AAA.

+ +

See Color contrast for more information on color contrast.

+ +

Accessibility picker

+ +

Like the element picker button on the Page Inspector, the Accessibility tab's element picker button allows you to hover and select UI items on the current page  highlight objects in the accessibility tree.

+ +

The accessibility tab element picker looks slightly different from the Page Inspector HTML pane picker, as shown below:

+ +

highlighted dom inspector picker button, with a tooltip saying Pick an element from the page

+ +

highlighted accessibility inspector button, with a tooltip saying Pick accessible object from the page

+ +

When you "perform a pick", you see the accessibility object highlighted in the accessibility tree, and the picker is then deactivated. Note, however, that if you hold the Shift key down when "performing a pick", you can "preview" the accessibility object in the tree (and its properties in the right-hand pane), but then continue picking as many times as you like (the picker does not get cancelled) until you release the Shift key.

+ +

When the picker is activated, you can also deactivate it by pressing the picker button a second time, or pressing the Esc key.

+ +

Typical use cases

+ +

The Accessibility Inspector is very useful for spotting accessibility problems at a glance. For a start, you can investigate items that don't have a proper text equivalent — images without alt text and form elements without proper labels have a name property of null, for example.

+ +

A form input highlighted in the UI, with information about it shown in the accessibility inspector to reveal that it has no label — it has a name property of null

+ +

It is also very handy for verifying semantics — you can use the Inspect Accessibility Properties context menu option to quickly see whether an item has the correct role set on it (e.g., whether a button is really a button, or a link is really a link).

+ +

A UI element that looks like a button, with information about it shown in the accessibility inspector to reveal that it isn't a button, it is a section element. It has a name property of null

+ +

See also

+ + diff --git a/files/id/tools/debugger/index.html b/files/id/tools/debugger/index.html new file mode 100644 index 0000000000..c1f0d2c11e --- /dev/null +++ b/files/id/tools/debugger/index.html @@ -0,0 +1,49 @@ +--- +title: Debugger +slug: Tools/Debugger +translation_of: Tools/Debugger +--- +
{{ToolsSidebar}}

The JavaScript Debugger enables you to step through JavaScript code and examine or modify its state to help track down bugs.

+ +

You can use it to debug code running locally in Firefox or running remotely, for example in a Firefox OS device or Firefox on Android. See remote debugging to learn how to connect the debugger to a remote target.

+ +

{{EmbedYouTube("sK8KU8oiF8s")}}

+ +
+

User Interface Tour

+ +

To find your way around the debugger, here's a quick tour of the UI.

+ +
+

How to

+ +

To find out what you can do with the debugger, see the following how-to guides:

+ +
+ +
+ +
+

Reference

+ +
+ +
diff --git a/files/id/tools/index.html b/files/id/tools/index.html new file mode 100644 index 0000000000..1b8f7b5fa8 --- /dev/null +++ b/files/id/tools/index.html @@ -0,0 +1,189 @@ +--- +title: Alat +slug: Tools +tags: + - Mengembangkan Mozilla + - Panduan + - Pengembangan Web + - 'Pengmbang Web: Alat' +translation_of: Tools +--- +

Uji, ubah, dan debug HTML, CSS, dan JavaScript di desktop dan di ponsel.

+ + + +
+
+
+ +
+

+ +

Untuk alat dan fitur terbaru, cobalah Firefox Edisi Pengembang, Cobalah Firefox Developer Edition.

+ +

Unduh Firefox Developer Edition

+
+
+ +

Peralatan Inti

+ +
+
+

Pemeriksa Laman

+ +

The all-new Inspector panel in Firefox 57.

+ +

Lihat dan ubah konten dan tata letak laman. Visualisasikan banyak aspek laman termasuk box model, animasi dan tata letak grid.

+
+ +
+

Konsol Web

+ +

The all-new Console in Firefox 57.

+ +

Lihat pesan yang dicatat oleh laman web dan interaksi dengan laman menggunaan JavaScript.

+
+
+ +
+
+

Pen-debug   JavaScript

+ +

The all-new Firefox 57 Debugger.html

+ +

Berhenti, melangkah melalui, uji, dan modifikasi JavaScript yang berjalan dalam sebuah laman.

+
+ +
+

Monitor Jaringan

+ +

The Network panel in Firefox 57 DevTools.

+ +

Lihat permintaan jaringan yang dibuat ketika sebuah laman dimuat.

+
+
+ +
+
+

Alat Kinerja

+ +

+ +

Analisa kinerja responsif, JavaScript, dan tata letak situs Anda.

+
+ +
+

Mode Desain Responsif

+ +

Responsive Design mode in Firefox 57.

+ +

Lihat bagaimana situs atau aplikasi Anda akan terlihat dan berperilaku pada perangkat dan jenis jaringan yang berbeda.

+
+
+ +
+

Alat Lainnya

+ +

Alat pengembang ini juga dibuat ke dalam Firefox. Tidak seperti "Alat Inti" di atas, mungkin Anda tidak menggunakannya setiap hari.

+ +
+
+
Memori
+
Cari tahu objek mana yang sedang menyimpan memori yang digunakan.
+
Pemeriksa Penyimpanan
+
Memeriksa kuki, penyimpan lokal, indexedDB, dan Inspect cookies, local storage, indexedDB, dan penyimpanan sesi kini pada sebuah laman.
+
DOM Property Viewer
+
Memeriksa properti DOM laman, fungsi, dan lain-lain.
+
Toolbar Pengembang
+
Sebuah antarmuka command-line untuk alat pengembang.
+
Eyedropper
+
Memilih warna dari laman.
+
Scratchpad
+
Sebuah editor teks yang dibuat ke dalam Firefox yang  memungkinkan Anda menulis dan menjalankan JavaScript
+
Editor Gaya
+
Tinjau dan ubah gaya CSS untuk halaman saat ini.
+
Shader Editor
+
Tinjau dan edit vertex dan fragment shaders yang digunakan oleh WebGL.
+
Editor Audio Web
+
Periksa grafik dari node audio dalam kontek audio, dan modifikasi parameternya.
+
Mengambil tangkapan layar
+
Mengambil sebuah tangkapan layar dari keseluruhan laman atau dari sebuah elemen tunggal.
+
Mengukur sebagian laman
+
Mengukur area tertentu pada sebuah laman web.
+
Rulers (Penggaris)
+
Penggaris sepanjang horizontal dan vertikal pada sebuah laman web.
+
+
+ +
+

Menghubungkan Alat Pengembang

+ +

Jika Anda membuka alat pengembang menggunakan pintasan keyboard atau or item menu yang sama, mereka akan menargetkan dokumen yang telah di-host oleh tab yang sedang aktif. Tetapi Anda bisa memasang alat ke berbagai target lain, juga di dalam peramban saat ini dan di berbagai peramban atau bahkan perangkat yang berbeda.

+ +
+
+
about:debugging
+
Men-debug pengayas, tab konten, dan pekerja yang berjalan di peramban.
+
Menghubungan ke Firefox untuk Android
+
Menghubungkan alat pengembang ke sebuah instance dari Firefox yang berjalan pada sebuah perangkat Android.
+
Menghubungkan ke iframes
+
Menghubungkan alat pengembang ke sebuah iframe tertentu pada laman saat ini
+
Menghubungkan ke peramban lain
+
Menghubungkan alat pengembang ke Chrome pada Android dan Safari pada iOS.
+
+
+ +
+

Men-debug peramban

+ +

Secara default, alat pengembang dilampirkan ke laman web atau aplikasi web. Tetapi Anda bisa juga menghubungkan mereka ke peramban secara keseluruhan. Ini berguna untuk pengembangan peramban dan pengayas.

+ +
+
+
Konsol Peramban
+
Lihat pesan yang dicatat oelh peramban itu dan oleh pengaya, dan jalankan kode JavaScript di linkup peramban.
+
Kotak Perkakas Peramban
+
Menyematkan alat pengembang ke peramban itu sendiri.
+
+
+ +
+

Memperluas  devtools

+ +

Alat pengembang dirancang agar dapat diperluas. Pengaya Firefox dapat mengakses alat pengembang dan komponen yang mereka gunakan untuk memperluas alat yang ada dan menambahkan alat yang baru. Dengan protokol men-debug jarak jauh, Anda dapat menerapkan men-debug klien dan server Anda sendiri, memungkinkan Anda men-debug situs web menggunakan alat Anda sendiri atau untuk men-debug berbagai sasaran menggunakan alat Firefox.

+ +
+
+
Contoh pengaya alat pengembang
+
Gunakan contoh-contoh ini untuk memahami bagaimana untuk menerapkan pengaya alat pengembang.
+
Menambah sebuah panel baru ke alat pengembang
+
Menulis sebuah pengaya yang menambah sebuah panel baru ke Kotak perkakas.
+
Protokol Men-debug Jarak Jauh
+
Protokol digunakan untuk mengkoneksi Alat Firefox Developer Tools untuk sebuah target men-debug seperti instance dari perangkat Firefox atau Firefox OS.
+
Peubah Sumber
+
Sebuah editor kode di buat kedalam Firefox yang bisa disematkan ke pengaya Anda.
+
Antarmuka Debugger
+
Sebuah API yang memungkinkan kode JavaScript mengemati eksekusi dari kode JavaScript yang lain. Alat Pengembang Firefox menggunakan API untuk menerapakan pen-debug JavaScript.
+
Konsol Web keluaran kustom
+
Bagaimana memperluas keluaran dari Konsol Web dan Konsol Peramban.
+
+
+ +
+

Migrasi dari Firebug

+ +

Firebug akan sampai pada akhir masa pakainya (lihat Firebug tinggal di Firefox DevTools untuk lebih jelasnya mengapa), dan kita menghargai bahwa beberapa orang akan merasa migrasi ke set alat pengembang yang kurang terkenal akan menjadi menantang. Untuk memudahkan transisi dari Firebug ke alat pengembang Firefox, kami telah menulis panduan praktis — Migrasi dari Firebug.

+ +
+

Kontribusi

+ +

Jika Anda ingin untuk membantu mengembangkan alat pengembang, sumber daya ini akan membantu Anda untuk memulai.

+ +
+
+
Ikut Terlibat
+
Halaman wiki Mozilla menjelaskan bagaimana caranya untuk terlibat.
+
firefox-dev.tools
+
Sebuah alat yang membantu mencari bugs untuk dikerjakan.
+
+
diff --git a/files/id/tools/page_inspector/how_to/index.html b/files/id/tools/page_inspector/how_to/index.html new file mode 100644 index 0000000000..2f18038ec9 --- /dev/null +++ b/files/id/tools/page_inspector/how_to/index.html @@ -0,0 +1,13 @@ +--- +title: How to +slug: Tools/Page_Inspector/How_to +tags: + - NeedsTranslation + - TopicStub +translation_of: Tools/Page_Inspector/How_to +--- +
{{ToolsSidebar}}

Links for various HOW TO's can be found here. These links describe in depth the HOW TO techniques.

+ +

{{ ListSubpages () }}

+ +

 

diff --git a/files/id/tools/page_inspector/index.html b/files/id/tools/page_inspector/index.html new file mode 100644 index 0000000000..68f6b614ec --- /dev/null +++ b/files/id/tools/page_inspector/index.html @@ -0,0 +1,53 @@ +--- +title: Page Inspector +slug: Tools/Page_Inspector +tags: + - CSS + - HTML + - Tools + - Web Development +translation_of: Tools/Page_Inspector +--- +
{{ToolsSidebar}}

Gunakan peninjau halaman untuk melihat dan memodifikasi HTML dan CSS dari sebuah halaman.

+ +

Anda bisa melihat atau memeriksa halaman yang telah dimuat pada salinan lokal di firefox, atau pada remote target seperti pada perangkat Firefox OS atau firefox untuk android. Lihat remote debugging untuk mempelajari bagaimana cara menghubungkan developer tools pada sebuah remote target.

+ +
+

Mempelajari Antarmuka Pengguna

+ +

Untuk mengetahui cara menggunakan inspector/Peninjau, berikut tur singkat dari UI.

+ +
+

Paduan

+ +

Untuk mengetahui apasaja yang anda bisa lakukan dengan inspector, lihat paduan berikut:

+ +
+ +
+ +
+

Referensi

+ +
+ +
diff --git a/files/id/tools/remote_debugging/index.html b/files/id/tools/remote_debugging/index.html new file mode 100644 index 0000000000..a917c007b1 --- /dev/null +++ b/files/id/tools/remote_debugging/index.html @@ -0,0 +1,34 @@ +--- +title: Remote Debugging +slug: Tools/Remote_Debugging +tags: + - NeedsTranslation + - TopicStub +translation_of: Tools/Remote_Debugging +--- +
{{ToolsSidebar}}

You can use the Firefox developer tools on your desktop to debug code running remotely: in a different process on the same device or on a completely different device. To do this you use Firefox to attach the Toolbox to the remote process, and the Toolbox is then launched in its own window. At the moment the following tools support remote debugging:

+ + + +

Firefox for Android

+ +

Remotely debugging Firefox for Android describes how to connect to Firefox on an Android device over USB.

+ +

Firefox for Metro

+ +

Remotely debugging Firefox for Metro describes how to use desktop Firefox to debug code running in Windows 8 (Metro-style) Firefox.

+ +

Firefox OS

+ +

Using the App Manager includes instructions for connecting the Firefox developer tools to the Firefox OS simulator or to a Firefox OS device.

+ +

Thunderbird

+ +

Remotely debugging Thunderbird explains how a combination of Firefox and Thunderbird can be used to debug code running in Thunderbird.

diff --git a/files/id/tools/webide/index.html b/files/id/tools/webide/index.html new file mode 100644 index 0000000000..3cf3b7bf2b --- /dev/null +++ b/files/id/tools/webide/index.html @@ -0,0 +1,458 @@ +--- +title: WebIDE +slug: Tools/WebIDE +translation_of: Archive/WebIDE +--- +
{{ToolsSidebar}}
+

WebIDE is available from Firefox 34 onwards.

+
+ +
+

WebIDE is the replacement for the App Manager. Like the App Manager, it enables you to run and debug Firefox OS apps using the Firefox OS Simulator or a real Firefox OS device.

+ +

However, it also provides an editing environment for you to create and develop Firefox OS apps, including a tree view of all the files in your app with the ability to edit and save them, and two app templates to help you get started.

+ +

Finally, WebIDE enables you to connect the Firefox Developer Tools to a number of other browsers, including Firefox for Android, Chrome on Android, and Safari on iOS. See the Remote Debugging page for instructions on how to connect to a specific browser.

+
+ +

With WebIDE, you first set up one or more runtimes. A runtime is an environment in which you'll run and debug the app. A runtime could be a Firefox OS device connected to the desktop over USB, or it could be a Firefox OS Simulator installed on the desktop itself.

+ +

Next, you create an app, or open an existing app. If you're creating a new app you start with a template that includes the directory structure and the minimum boilerplate you need to get started, or a more complete template that shows how to use a privileged API. WebIDE shows your app's files in a tree, and you can edit and save them using a built-in source editor. Of course, you don't have to use the built-in editor: you can develop your app entirely outside WebIDE, and only use it for debugging.

+ +

Finally, you can install the app in one of the runtimes and run it. You can then open the usual suite of developer tools - the Inspector, Console, JavaScript Debugger and so on - to examine and modify the running app.

+ +

System requirements

+ +

To develop and debug apps using WebIDE, all you need is Firefox version 33 or later. To test on a real Firefox OS device, you need a device running Firefox OS 1.2 or later, and a USB cable.

+ +

You can only use WebIDE for Firefox OS if you're targeting Firefox OS 1.2 or later.

+ +

Opening WebIDE

+ +

There are three ways to open WebIDE:

+ + + +

+ +

Here's what the WebIDE looks like:The dropdown on the left labeled "Open App" lets you open existing apps or create new ones. The dropdown on the right labeled "Select Runtime" lets you select a runtime or set up a new runtime.

+ +

The buttons in the middle run, stop, and debug the app: they are only enabled when you have opened an app and selected a runtime.

+ +

From Firefox 36, you can change the font size throughout WebIDE using the standard keyboard shortcuts (use Command instead of Control on OS X):

+ + + +

Setting up runtimes

+ +

Under the "Select Runtime" dropdown, runtimes are grouped into three types:

+ + + +

The first time you click the dropdown, you might not see any runtimes here:

+ +

The rest of this section describes how you can add some runtimes.

+ +

Connecting a Firefox OS device

+ +

Before you can connect a Firefox OS device, there's some setup you have to go through:

+ + + +
+

Linux only:

+ + +
+ +
+

Windows only:

+ + +
+ +

If there are any other Android devices connected to your computer, disconnect them. Now connect the device to the computer using USB. You should see the device appear under "USB DEVICES":

+ +

+ +

If you don't see your device, see the Troubleshooting page.

+ +

Connecting to Firefox for Android

+ +

From Firefox 36 onwards Android devices connected over USB and running Firefox for Android appear as a runtime under "USB devices". See the article on connecting to Firefox for Android from WebIDE.

+ +

Before Firefox 36, you can connect to Firefox for Android without using WebIDE at all, or can use WebIDE by setting up a custom remote runtime.

+ +

Adding a Simulator

+ +

The Firefox OS Simulator is a version of the higher layers of Firefox OS that simulates a Firefox OS device, but runs on the desktop. It runs in a window the same size as a Firefox OS device, includes the Firefox OS user interface and built-in apps, and simulates many of the Firefox OS device APIs.

+ +

This means that in many cases, you don't need a real device to test and debug your app.

+ +

The Simulator is big, so it doesn't ship inside Firefox but as a Firefox add-on. If you click "Install Simulator" in the Runtimes dropdown menu, you will go to a page from which you can install Simulators for various versions of Firefox OS.

+ +

You can install as many as you like. Be patient, though: the Simulator is large and may take a few minutes to download. Once you've installed some Simulators you can close this "Extra Components" window, and the Simulators you've installed appear as options in the Runtimes dropdown menu:

+ +

To learn more about the Simulator, see its documentation page.

+ +

Custom runtimes

+ +

Remote runtime

+ +

With a custom remote runtime you can use an arbitrary hostname and port to connect to the remote device.

+ +

Under the hood, Firefox OS devices and Android devices connect to the desktop using a program called the Android Debug Bridge, or ADB. By default, WebIDE uses an add-on called the ADB Helper: this simplifies the process for you by installing ADB and setting up port forwarding so the Firefox desktop tools can exchange messages with the device.

+ +

This is convenient in most cases, but sometimes you might want to use ADB outside of WebIDE: for example, you might be running ADB directly from the command line. In that case you'll connect to the device by specifying a host and port using the adb forward command (example: adb forward tcp:6000 localfilesystem:/data/local/debugger-socket).
+
+ If you then want to use WebIDE to connect as well, you should disable the ADB Helper add-on and connect WebIDE using the Custom runtime option, entering the host and port that you passed to adb forward (example: localhost:6000).

+ +

Also, before Firefox 36, the ADB Helper does not yet support connecting to Firefox for Android, so if you want to connect WebIDE to Firefox for Android, you'll need to set up your own port forwarding and use a custom runtime. See more about connecting to Firefox for Android using ADB prior to Firefox 36.

+ +

Valence-enabled runtimes

+ +

If you have the Valence add-on installed, you'll see three additional runtimes:

+ + + +

For instructions on how to connect to these runtimes, see the relevant entry in the Remote Debugging page.

+ +

Selecting a runtime

+ +

Once you've set up a runtime you can select it using the "Select Runtime" menu.

+ + + +

Now the "play" button in the center of the WebIDE toolbar is enabled: click it to install and run the app in the selected runtime.

+ +

Runtime menu items

+ +

When a runtime is selected, the Runtimes dropdown menu has up to five extra items:

+ +
+
Runtime Info
+
Information on the current runtime
+
Permissions Table
+
A table summarising app permissions for the current runtime, indicating, for each API and each app type, whether access is allowed (✓), denied (✗), or whether the user is prompted (!)
+
+ +
+
Device Preferences
+
A table listing, and letting you edit, the preferences that are made available in the runtime via the Preferences service. These are platform-level configuration values exposing the same set of data as Firefox's about:config (but for the device). Because these preferences are highly security-sensitive, you need to disable the DevTools restricted privileges setting before you can modify them.
+
Device Settings (new in Firefox 38/Firefox OS 3)
+
A table listing, and letting you edit, the settings that can be controlled in the Firefox OS Settings app. Most things on the device which have a UI control to change (volume, alarm, etc.) are found in Device Settings. Because these settings are less sensitive than the device preferences, you can modify them without removing the restricted privileges setting. However, since this feature is new in Gecko 38 you need the WebIDE in Firefox 38 and a nightly build of Firefox OS or the Simulator.
+
Screenshot
+
A command to take a screenshot from the runtime.
+
+ +

+ +

 

+ +

Creating and opening apps

+ +

Under the "Open App" menu you get three options: create a new app, open a packaged app, and open a hosted app:

+ +

+ +

Create a new app

+ +

Select "New App..." to create a new app. You'll see a dialog offering you a choice between two templates, "Privileged Empty App" and "Privileged App".

+ +

+ +

Both templates are from Mozilla's app template collection, and provide you with the basic structure you need to get started. The "Privileged App" shows how an app can use permissions to load cross-origin content.

+ +

Once you've selected a template you'll be asked to name the app and select a directory to store the files, and then the new app is opened in the project editor.

+ +

Open a packaged app

+ +

Select "Open Packaged App..." to open a packaged app. You'll be asked to select a directory containing the app's manifest, and the app will be opened in the project editor.

+ +

Open a hosted app

+ +

Select "Open Hosted App..." to open a hosted app. You'll be asked to enter a URL pointing to the app's manifest, and the app will be opened in the project editor.

+ +

Editing apps

+ +

The project editor provides an environment for editing apps. There's a tree view on the left of all the files in the app: you can add and delete files here using a context menu. There's an editor pane on the right.

+ +

The app summary page

+ +

When you first open or create an app, the editor pane is occupied by the app summary page, which is shown below:

+ +

+ +

You can always get back to the app summary page by clicking on the root of the tree on the left.

+ +

Manifest validation

+ +

WebIDE automatically checks the manifest for certain common problems. If it finds a problem it indicates that the app is invalid and describes the problem in the app's summary:

+ +

+ +

Of course, you can edit the manifest.webapp file right in the project editor as well.

+ +

The source editor

+ +

WebIDE uses the CodeMirror source editor.

+ +

Source editor shortcuts

+ +

{{ Page ("en-US/docs/tools/Keyboard_shortcuts", "source-editor") }}

+ +

Code completion

+ +

When editing CSS and JavaScript, the editor provides autocomplete suggestions. CSS autocompletion is always enabled:

+ +

To display autocomplete suggestions in JavaScript press Control + Space:

+ +

+ +

Inline documentation

+ +

The editor also shows inline documentation for JavaScript. Press Shift + Space to see a popup containing documentation for the symbol your cursor is on:

+ +

+ +

Clicking the [docs] link in the popup will take you to the MDN page for the symbol.

+ +

Saving files

+ +

For changes to your files to take effect you need to save them. Files with unsaved changes get an asterisk next to their name in the tree view, and you can save files using the menu or Control+S (Command+S on Mac OS X).

+ +

Removing projects

+ +

To remove an app from WebIDE, go to the app summary page and click "Remove Project".

+ +

Running a custom build step

+ +
+

New in Firefox 37.

+
+ +

For some use cases you need to run a custom command before pushing your app to the device. For example, you might want to satisfy JavaScript dependencies or minify CSS, or use WebIDE to develop Gaia apps or Cordova apps, both of which require a custom build step.

+ +

From Firefox 37 you can do this by including a file called "package.json" in the root of your app. This is the same file that's used to package a node.js library, so you might already have one in the root of your project. If you don't, you can create one for this purpose.

+ +

Inside package.json, WebIDE looks for a property called "webide". The table below summarises the syntax of "webide":

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
webide   +

Object containing instructions for WebIDE.

+ +

This may contain two properties, both optional: "prepackage" and "packageDir".

+
 prepackage  +

Specifies a command-line command for WebIDE to run before pushing the app to the runtime.

+ +

This may be a string, in which case the command is just executed as-is, or may be an object which must contain "command", and may contain any of "env", "args", and "cwd".

+
  command +

The command to execute in the command shell.

+ +

For example: "echo".

+
  env +

Any environment variables to set.

+ +

This is specified as an array of strings in the form "NAME=value". For example: ["NAME=world"]

+
  args +

Any arguments to pass along with the command.

+ +

This is specified as an array of strings.

+
  cwd +

The directory from which to run the command.

+ +

This may be absolute or relative to the current directory.

+
 packageDir  +

The directory from which WebIDE should look for the app to push to the runtime.

+ +

Use this if you want the project in WebIDE to be the source from which to build a packaged app. The build step specified in prepackage would place the built app in an output directory, you will specify the output directory in packageDir, and WebIDE will install the app from that output directory rather than the project directory.

+ +

This property is optional, and if it's omitted WebIDE will package the app from the project root, just as if package.json was omitted.

+
+ +

Examples

+ +

A "package.json" to build a Gaia app:

+ +
{
+  "webide": {
+    "prepackage": {
+      "command": "make",
+      "env": ["APP=settings"],
+      "cwd": "../.."
+    },
+    "packageDir": "../../build_stage/settings/"
+  }
+}
+ +

A "package.json" for working with Cordova:

+ +
{
+  "webide": {
+    "prepackage": "cordova prepare",
+    "packageDir": "./platforms/firefoxos/www"
+  }
+}
+ +

Running and debugging apps

+ +

When you're ready to run the app, you need to select a runtime from the "Select Runtime" dropdown menu. If you don't have any available runtimes here, find out how to add some in Setting up runtimes.

+ +

The "play" button in the center of the WebIDE toolbar is now enabled: click it to install and run the app in the selected runtime:

+ +

To debug the app, click the "Pause" button and the Developer Tools Toolbox appears, connected to your app:

+ +

+ +
+

From Firefox 36 onwards, the "Pause" button is replaced with a wrench icon.

+
+ +

Exactly which tools you'll have available depends on the runtime, but you will at least have the basics: the Inspector, Console, JavaScript Debugger, Style Editor, Profiler and Scratchpad. Just as in a web page, any changes you make in the tools are visible immediately in the app, but are not persistent. Conversely, any changes you make in the editor pane can be saved straight back to disk, but are not visible without restarting the app.

+ +

Unrestricted app debugging (including certified apps, main process, etc.)

+ +

You can run the debugger against the simulator, b2g desktop, or a real device.

+ +

With the Simulator, if you click on the app dropdown menu while the runtime is selected, you can see and debug not only your app but all apps running in that runtime, including certified apps:

+ +

+ +


+ However, when connecting to a real device we have a security policy in force:

+ + + +

To remove this restriction:

+ + + +

To disable DevTools restricted privileges, connect to the runtime, and then, in the menu, go to Runtime > Runtime Info. The path then differs depending on what you are debugging against:

+ + + +

Now (or after a restart of the B2G desktop client) in WebIDE you should see all the apps on the device.

+ +
+

Note: As indicated above, to enable unrestricted privileges on a real device through WebIDE you'll need a rooted device. There is however a developer setting available in Firefox OS 2.2 onwards called Reset and enable full DevTools — when activated this will wipe all user data (for security reasons), reset the device, and enable unrestricted priviledges on any device.

+
+ +

Monitoring performance

+ +

If you're interested in the performance of your apps, there are a few ways to measure their impact on the runtime in WebIDE:

+ + + +

Troubleshooting

+ +

If you have any problems working with WebIDE, see the Troubleshooting page.

+ +

 

+ +

 

diff --git a/files/id/tools/webide/troubleshooting/index.html b/files/id/tools/webide/troubleshooting/index.html new file mode 100644 index 0000000000..d39320049b --- /dev/null +++ b/files/id/tools/webide/troubleshooting/index.html @@ -0,0 +1,117 @@ +--- +title: WebIDE +slug: Tools/WebIDE/Troubleshooting +tags: + - Indonesia +translation_of: Archive/WebIDE/Troubleshooting +--- +
{{ToolsSidebar}}

Connecting a Firefox OS device over USB

+ +

If you're trying to connect a Firefox OS device to WebIDE and it doesn't show up, here are some things you can try:

+ + + +

Connecting a Firefox OS device over Wi-Fi

+ + + +

Connecting to Firefox for Android

+ +

If you're trying to connect to a Firefox instance running on the Android OS and it doesn't show up, here are some things you can try:

+ + + +

Connecting to other browsers (Chrome, Safari)

+ +

WebIDE makes use of Valence (formerly Firefox Tools Adapter) to reach other browsers, like Chrome and Safari. 

+ +

If you are having trouble connecting to these other browsers, check the setup steps and other notes for those browsers on the Valence page.

+ +

Can't debug some apps

+ +

If you are finding that you can't debug certified apps, built-in apps, or apps already installed on a real device, then you may be coming across WebIDE's restricted privileges security policy. To find out more, see the section on Unrestricted app debugging (including certified apps, main process, etc.).

+ +

Unable to load project list

+ +

If you open WebIDE in one version of Firefox, and then downgrade to a previous Firefox version with the same profile, you may see the error "Unable to load project list" when opening WebIDE in the earlier Firefox version.

+ +

This can occur when the storage system that WebIDE uses (IndexedDB) needs to move or restructure its internal files for the newer Firefox version. The project list then becomes effectively inaccessible to older versions of Firefox.

+ +

No data has been lost, but you will need to keep using the newest version of Firefox that was used with your profile to get the project list back.

+ +

If really want to use the older version of Firefox, you can attempt to delete just the project list in the following way, but this is unsupported and could result in the further problems or additional data loss:

+ +
    +
  1. Close Firefox
  2. +
  3. Find your Firefox profile directory
  4. +
  5. Find the storage folder inside the profile directory
  6. +
  7. Under some part of this file tree, there should be files and/or directories that start with 4268914080AsptpcPerjo (a hashed name of the database)
  8. +
  9. Remove any such files and directories
  10. +
  11. Start Firefox and WebIDE again
  12. +
+ +

Enable logging

+ +

You can also enable verbose logging to gather diagnostics:

+ +
    +
  1. Open about:config, and add a new preference called extensions.adbhelper@mozilla.org.sdk.console.logLevel, with the string value all, and set extensions.adbhelper@mozilla.org.debug to true.
  2. +
  3. In the Add-ons Manager, disable and then re-enable the ADB Helper add-on.
  4. +
  5. Open the Browser Console and you'll now see console messages prefixed with adb. If the messages don't mean anything to you, ask for help.
  6. +
+ +

Get help

+ +

Go to the #devtools room on IRC and we will try to help.

diff --git a/files/id/web/api/abstractworker/index.html b/files/id/web/api/abstractworker/index.html new file mode 100644 index 0000000000..cea5a54797 --- /dev/null +++ b/files/id/web/api/abstractworker/index.html @@ -0,0 +1,125 @@ +--- +title: AbstractWorker +slug: Web/API/AbstractWorker +translation_of: Web/API/AbstractWorker +--- +

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

+ +

Antarmuka AbstractWorker dari abstrak properti Web Workers API  dan method umum untuk semua jenis worker, berupa {{domxref("Worker")}} atau {{domxref("SharedWorker")}}.

+ +

Properti

+ +

Antarmuka AbstractWorker tidak mewarisi properti apapun.

+ +

Event handlers

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
Sebuah {{ domxref("EventListener") }} yang dipanggil ketika sebuah {{domxref("ErrorEvent")}} dari tipe error bubbles melalui worker.
+
+ +

Method

+ +

Antarmuka AbstractWorker tidak menjalankan atau mewarisi method apapun.

+ +

Contoh

+ +

Catat bahwa anda tidak ingin menggunakan antarmuka AbstractWorker langsung di dalam kode anda — ketika dipanggil, {{domxref("Worker")}} dan {{domxref("SharedWorker")}} mewarisi propertinya. Pada contoh code snippet menunjukan pembuatan objek {{domxref("Worker")}} menggunakan konstruktor {{domxref("Worker.Worker", "Worker()")}} dan penggunakan dari objek:

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

Contoh lengkapnya, lihat:

+ + + +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName("HTML WHATWG", "#the-abstractworker-abstract-interface", "AbstractWorker")}}{{Spec2("HTML WHATWG")}}No change from {{SpecName("Web Workers")}}.
{{SpecName("Web Workers", "#the-abstractworker-abstract-interface", "AbstractWorker")}}{{Spec2("Web Workers")}}Initial definition.
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable()}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(4)}}{{CompatGeckoDesktop("1.9.1")}}1010.64
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Dukungan dasar4.4{{CompatGeckoMobile("1.9.1")}}1.0.11011.55.1
+
+ +

Lihat Juga

+ + + +

 

diff --git a/files/id/web/api/api_push/index.html b/files/id/web/api/api_push/index.html new file mode 100644 index 0000000000..feae8a7373 --- /dev/null +++ b/files/id/web/api/api_push/index.html @@ -0,0 +1,165 @@ +--- +title: API Push +slug: Web/API/API_Push +translation_of: Web/API/Push_API +--- +
{{DefaultAPISidebar("Push API")}}{{SeeCompatTable}}
+ +

API Push memberikan aplikasi web kemampuan menerima pesan yang didorong oleh peladen ke dalam agen pengguna, baik bila aplikasi berada di permukaan atau baru dimuat. API Push memungkinkan pengembang memberikan pemberitahuan dan pembaruan tak sinkron ke pengguna yang mengizinkan. Hal ini memberikan hasil pendekatan yang lebih baik untuk muatan baru yang terus berubah.

+ +
+

Catatan: Dokumentasi ini melingkupi spesifikasi API Push W3C. Bila Anda mencari dokumentasi untuk mekanisme berpemilik dari Firefox OS, lihat Push Sederhana.

+
+ +

Push concepts and usage

+ +

For an app to receive push messages, it has to have an active service worker. When the service worker is active, it can subscribe to push notifications using {{domxref("PushManager.subscribe()")}}.

+ +

The resulting {{domxref("PushSubscription")}} includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data.

+ +

The service worker will be started as necessary to handle incoming push messages, which are delivered to the {{domxref("ServiceWorkerGlobalScope.onpush")}} event handler. This allows apps to react to push messages being received, for example by displaying a notification (using {{domxref("ServiceWorkerRegistration.showNotification()")}}.)

+ +

Each subscription is unique to a service worker.  The endpoint for the subscription is a unique capability URL: knowledge of the endpoint is all that is necessary to send a message to your application. The endpoint URL therefore needs to be kept secret, or other applications might be able to send push messages to your application.

+ +

Activating a service worker to deliver a push message can result in increased resource usage, particularly of the battery. Different browsers have different schemes for handling this — there is currently no standard mechanism. Firefox allows a limited number (quota) of push messages to be sent to an application, although Push messages that generate notifications are exempt from this limit. The limit is refreshed each time the site is visited. In comparison, Chrome applies no limit but requires that every push message causes a notification to be displayed.

+ +
+

Note: As of Gecko 44, the allowed quota of push messages per application is not incremented when a new notification fires when another is still visible, for a period of three seconds. This handles cases where a burst of notifications is received, and not all generate a visible notification.

+
+ +
+

Note: Chrome currently requires you to set up a project on Google Cloud Messaging to send push messages, and use the associated project number and API key when sending push notifications. It also requires an app manifest with some special parameters to use this service. This restriction will hopefully be removed in the future.

+
+ +

Interfaces

+ +
+
{{domxref("PushEvent")}}
+
Represents a push action sent to the global scope of a {{domxref("ServiceWorker")}}. It contains information sent from an application to a {{domxref("PushSubscription")}}.
+
{{domxref("PushManager")}}
+
Provides a way to receive notifications from third-party servers as well as request URLs for push notifications. This interface has replaced functionality offered by the obsolete {{domxref("PushRegistrationManager")}} interface.
+
{{domxref("PushMessageData")}}
+
Provides access to push data sent by a server, and includes methods to manipulate the received data.
+
{{domxref("PushSubscription")}}
+
Provides a subcription's URL endpoint and allows unsubscription from a push service.
+
+ +

Service worker additions

+ +

The following additions to the Service Worker API have been specified in the Push API spec, to provide an entry point for using Push messages, and  to monitor and respond to push and subscription change events.

+ +
+
{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}
+
Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. This is the entry point into using Push messaging.
+
{{domxref("ServiceWorkerGlobalScope.onpush")}}
+
An event handler fired whenever a {{Event("push")}} event occurs; that is, whenever a server push message is received.
+
{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}
+
An event handler fired whenever a {{Event("pushsubscriptionchange")}} event occurs; for example, when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Push API")}}{{Spec2("Push API")}}Initial definition
+ +

Browser Compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}[1]{{CompatNo}}[2]{{CompatUnknown}}{{CompatUnknown}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatGeckoDesktop(44.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Currently available only on desktop versions of Firefox; also, push messages are only delivered when Firefox is running.

+ +

[2] This is currently not implemented. See the Microsoft Edge status information.

+ +

See also

+ + diff --git a/files/id/web/api/cachestorage/index.html b/files/id/web/api/cachestorage/index.html new file mode 100644 index 0000000000..fdcfe56217 --- /dev/null +++ b/files/id/web/api/cachestorage/index.html @@ -0,0 +1,198 @@ +--- +title: CacheStorage +slug: Web/API/CacheStorage +tags: + - API + - CacheStorage + - Experimental + - Interface + - NeedsTranslation + - Reference + - Service Workers + - ServiceWorker + - TopicStub +translation_of: Web/API/CacheStorage +--- +

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

+ +

The CacheStorage interface represents the storage for {{domxref("Cache")}} objects.

+ +

The interface:

+ + + +

Use {{domxref("CacheStorage.open()")}} to obtain a {{domxref("Cache")}} instance.

+ +

Use {{domxref("CacheStorage.match()")}} to check if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the CacheStorage object tracks.

+ +

You can access CacheStorage through the global {{domxref("WindowOrWorkerGlobalScope.caches", "caches")}} property.

+ +
Note: CacheStorage always rejects with a SecurityError on untrusted origins (i.e. those that aren't using HTTPS, although this definition will likely become more complex in the future.) When testing, you can get around this by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the Firefox Devtools options/gear menu.
+ +
Note: {{domxref("CacheStorage.match()")}} is a convenience method. Equivalent functionality to match a cache entry can be implemented by returning an array of cache names from {{domxref("CacheStorage.keys()")}}, opening each cache with {{domxref("CacheStorage.open()")}}, and matching the one you want with {{domxref("Cache.match()")}}.
+ +

Methods

+ +
+
{{domxref("CacheStorage.match()")}}
+
Checks if a given {{domxref("Request")}} is a key in any of the {{domxref("Cache")}} objects that the {{domxref("CacheStorage")}} object tracks, and returns a {{jsxref("Promise")}} that resolves to that match.
+
{{domxref("CacheStorage.has()")}}
+
Returns a {{jsxref("Promise")}} that resolves to true if a {{domxref("Cache")}} object matching the cacheName exists.
+
{{domxref("CacheStorage.open()")}}
+
Returns a {{jsxref("Promise")}} that resolves to the {{domxref("Cache")}} object matching the cacheName (a new cache is created if it doesn't already exist.)
+
{{domxref("CacheStorage.delete()")}}
+
Finds the {{domxref("Cache")}} object matching the cacheName, and if found, deletes the {{domxref("Cache")}} object and returns a {{jsxref("Promise")}} that resolves to true. If no {{domxref("Cache")}} object is found, it resolves to false.
+
{{domxref("CacheStorage.keys()")}}
+
Returns a {{jsxref("Promise")}} that will resolve with an array containing strings corresponding to all of the named {{domxref("Cache")}} objects tracked by the {{domxref("CacheStorage")}}. Use this method to iterate over a list of all the {{domxref("Cache")}} objects.
+
+ +

Examples

+ +

This code snippet is from the MDN sw-test example (see sw-test running live.) This service worker script waits for an {{domxref("InstallEvent")}} to fire, then runs {{domxref("ExtendableEvent.waitUntil","waitUntil")}} to handle the install process for the app. This consists of calling {{domxref("CacheStorage.open")}} to create a new cache, then using {{domxref("Cache.addAll")}} to add a series of assets to it.

+ +

In the second code block, we wait for a {{domxref("FetchEvent")}} to fire. We construct a custom response like so:

+ +
    +
  1. Check whether a match for the request is found in the CacheStorage. If so, serve that.
  2. +
  3. If not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using {{domxref("Cache.put")}} (cache.put(event.request, response.clone()).)
  4. +
  5. If this fails (e.g. because the network is down), return a fallback response.
  6. +
+ +

Finally, return whatever the custom response ended up being equal to, using {{domxref("FetchEvent.respondWith")}}.

+ +
self.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.addAll([
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+        '/sw-test/star-wars-logo.jpg',
+        '/sw-test/gallery/bountyHunters.jpg',
+        '/sw-test/gallery/myLittleVader.jpg',
+        '/sw-test/gallery/snowTroopers.jpg'
+      ]);
+    })
+  );
+});
+
+self.addEventListener('fetch', function(event) {
+  event.respondWith(caches.match(event.request).then(function(response) {
+    // caches.match() always resolves
+    // but in case of success response will have value
+    if (response !== undefined) {
+      return response;
+    } else {
+      return fetch(event.request).then(function (response) {
+        // response may be used only once
+        // we need to save clone to put one copy in cache
+        // and serve second one
+        let responseClone = response.clone();
+
+        caches.open('v1').then(function (cache) {
+          cache.put(event.request, responseClone);
+        });
+        return response;
+      }).catch(function () {
+        return caches.match('/sw-test/gallery/myLittleVader.jpg');
+      });
+    }
+  }));
+});
+
+ +

This snippet shows how the API can be used outside of a service worker context, and uses the await operator for much more readable code.

+ +
// Try to get data from the cache, but fall back to fetching it live.
+async function getData() {
+   const cacheVersion = 1;
+   const cacheName    = `myapp-${ cacheVersion }`;
+   const url          = 'https://jsonplaceholder.typicode.com/todos/1';
+   let cachedData     = await getCachedData( cacheName, url );
+
+   if ( cachedData ) {
+      console.log( 'Retrieved cached data' );
+      return cachedData;
+   }
+
+   console.log( 'Fetching fresh data' );
+
+   const cacheStorage = await caches.open( cacheName );
+   await cacheStorage.add( url );
+   cachedData = await getCachedData( cacheName, url );
+   await deleteOldCaches( cacheName );
+
+   return cachedData;
+}
+
+// Get data from the cache.
+async function getCachedData( cacheName, url ) {
+   const cacheStorage   = await caches.open( cacheName );
+   const cachedResponse = await cacheStorage.match( url );
+
+   if ( ! cachedResponse || ! cachedResponse.ok ) {
+      return false;
+   }
+
+   return await cachedResponse.json();
+}
+
+// Delete any old caches to respect user's disk space.
+async function deleteOldCaches( currentCache ) {
+   const keys = await caches.keys();
+
+   for ( const key of keys ) {
+      const isOurCache = 'myapp-' === key.substr( 0, 6 );
+
+      if ( currentCache === key || ! isOurCache ) {
+         continue;
+      }
+
+      caches.delete( key );
+   }
+}
+
+try {
+   const data = await getData();
+   console.log( { data } );
+} catch ( error ) {
+   console.error( { error } );
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#cachestorage', 'CacheStorage')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/id/web/api/canvas_api/index.html b/files/id/web/api/canvas_api/index.html new file mode 100644 index 0000000000..0cdd4219fe --- /dev/null +++ b/files/id/web/api/canvas_api/index.html @@ -0,0 +1,172 @@ +--- +title: Canvas API +slug: Web/API/Canvas_API +tags: + - API + - Canvas + - Gambar + - JavaScript + - Referensi +translation_of: Web/API/Canvas_API +--- +
{{CanvasSidebar}}
+ +

Ditambahkan di HTML5, elemen HTML {{HTMLElement("canvas")}} dapat digunakan untuk menggambar grafik melalui skrip di JavaScript. Sebagai contoh, dapat digunakan untuk menggambar graf, membuat komposisi foto, mencipta animasi, atau bahkan melakukan pemrosesan atau rendering video secara waktu-nyata .

+ +

Aplikasi Mozilla mendapat dukungan untuk <canvas> sejak Gecko 1.8 (i.e. Firefox 1.5). Elemen tersebut semula dikenalkan oleh Apple untuk Dashboard OS X dan Safari. Internet Explorer mendukung <canvas> sejak versi 9 dan seterusnya; untuk versi awal IE, sebuah halaman dapat secara efektif mendukung <canvas> dengan memasukkan skrip dari proyek Explorer Canvas Google. Google Chrome dan Opera 9 juga mendukung <canvas>.

+ +

Elemen <canvas> juga digunakan oleh WebGL untuk menggambar grafik hardware-accelerated 3D di halaman web.

+ +

Contoh

+ +

Ini hanya cuplikan kode sederhana yang menggunakan metode  {{domxref("CanvasRenderingContext2D.fillRect()")}}.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.fillStyle = 'green';
+ctx.fillRect(10, 10, 100, 100);
+
+ +

Edit kode di bawah dan lihat perbaruan perubahannya di kanvas secara waktu-nyata:

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Reference

+ +
+ +
+ +

The interfaces related to the WebGLRenderingContext are referenced under WebGL.

+ +

{{domxref("CanvasCaptureMediaStream")}} is related.

+ +

Petunjuk dan tutorial

+ +
+
Tutorial canvas
+
Tutorial komprehensif mengcakup penggunaan sederhana  <canvas> dan fitur lanjutannya.
+
Cuplikan kode: Canvas
+
Beberapa cuplikan kode pengembang berorientasi ekstensi yang melibatkan <canvas>.
+
Demo: ray-caster sederhana
+
Demo animasi ray-tracing menggunakan canvas.
+
Menggambar DOM objects ke canvas
+
Bagaimana menggambar konten DOM, seperti elemen HTML, pada canvas.
+
Memanipulasi video dengan canvas
+
Menggabungkan {{HTMLElement("video")}} dan {{HTMLElement("canvas")}} untuk memanipulasi data video secara real time.
+
+ +

Sumber

+ +

Generik

+ + + +

Librari

+ + + +

Spesifikasi

+ + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('HTML WHATWG', 'scripting.html#the-canvas-element', '<canvas>')}}{{Spec2('HTML WHATWG')}}
+ +

Lihat juga

+ + diff --git a/files/id/web/api/console/index.html b/files/id/web/api/console/index.html new file mode 100644 index 0000000000..05cdba529b --- /dev/null +++ b/files/id/web/api/console/index.html @@ -0,0 +1,278 @@ +--- +title: Console +slug: Web/API/Console +tags: + - API + - Debugging + - Interface + - NeedsCompatTable + - NeedsTranslation + - Reference + - TopicStub + - console + - web console +translation_of: Web/API/Console +--- +
{{APIRef("Console API")}}
+ +

The Console object provides access to the browser's debugging console (e.g., the Web Console in Firefox). The specifics of how it works vary from browser to browser, but there is a de facto set of features that are typically provided.

+ +

The Console object can be accessed from any global object, {{domxref("Window")}} on browsing scopes, {{domxref("WorkerGlobalScope")}}, and its specific variants in workers via property console. It's exposed as {{domxref("Window.console")}}, and can be referenced as simply console. For example:

+ +
console.log("Failed to open the specified link")
+ +

This page documents the {{anch("Methods")}} available on the Console object and gives a few {{anch("Usage")}} examples.

+ +

{{AvailableInWorkers}}

+ +

Methods

+ +
+
{{domxref("Console.assert()")}}
+
Log a message and stack trace to console if first argument is false.
+
{{domxref("Console.clear()")}}
+
Clear the console.
+
{{domxref("Console.count()")}}
+
Log the number of times this line has been called with the given label.
+
{{domxref("Console.debug()")}}
+
An alias for log() - starting with Chromium 58 this method is a no-op on Chromium browsers.
+
{{domxref("Console.dir()")}} {{Non-standard_inline}}
+
Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
+
{{domxref("Console.dirxml()")}} {{Non-standard_inline}}
+
+

Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not.

+
+
{{domxref("Console.error()")}}
+
Outputs an error message. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.exception()")}} {{Non-standard_inline}} {{deprecated_inline}}
+
An alias for error()
+
{{domxref("Console.group()")}}
+
Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd().
+
{{domxref("Console.groupCollapsed()")}}
+
Creates a new inline group, indenting all following output by another level; unlike group(), this starts with the inline group collapsed, requiring the use of a disclosure button to expand it. To move back out a level, call groupEnd().
+
{{domxref("Console.groupEnd()")}}
+
Exits the current inline group.
+
{{domxref("Console.info()")}}
+
Informative logging information. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.log()")}}
+
For general output of logging information. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.profile()")}} {{Non-standard_inline}}
+
Starts the browser's build-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.
+
{{domxref("Console.profileEnd()")}} {{Non-standard_inline}}
+
Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the Firefox performance tool).
+
{{domxref("Console.table()")}}
+
Displays tabular data as a table.
+
{{domxref("Console.time()")}}
+
Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
+
{{domxref("Console.timeEnd()")}}
+
Stops the specified timer and logs the elapsed time in seconds since its start.
+
{{domxref("Console.timeStamp()")}} {{Non-standard_inline}}
+
Adds a marker to the browser's Timeline or Waterfall tool.
+
{{domxref("Console.trace()")}}
+
Outputs a stack trace.
+
{{domxref("Console.warn()")}}
+
Outputs a warning message. You may use string substitution and additional arguments with this method.
+
+ + +

Usage

+ +

Outputting text to the console

+ +

The most frequently-used feature of the console is logging of text and other data. There are four categories of output you can generate, using the {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}}, and {{domxref("console.error()")}} methods. Each of these results in output that's styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you.

+ +

There are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of the objects with which to replace them.

+ +

Outputting a single object

+ +

The simplest way to use the logging methods is to output a single object:

+ +
var someObject = { str: "Some text", id: 5 };
+console.log(someObject);
+
+ +

The output looks something like this:

+ +
[09:27:13.475] ({str:"Some text", id:5})
+ +

Outputting multiple objects

+ +

You can also output multiple objects by simply listing them when calling the logging method, like this:

+ +
var car = "Dodge Charger";
+var someObject = {str:"Some text", id:5};
+console.info("My first car was a", car, ". The object is: ", someObject);
+ +

This output will look like this:

+ +
[09:28:22.711] My first car was a Dodge Charger . The object is:  ({str:"Some text", id:5})
+
+ +

Using string substitutions

+ +

Gecko 9.0 {{geckoRelease("9.0")}} introduced support for string substitutions. When passing a string to one of the console object's methods that accepts a string, you may use these substitution strings:

+ + + + + + + + + + + + + + + + + + + + + + + + +
Substitution stringDescription
%o or %OOutputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
%d or %iOutputs an integer. Number formatting is supported, for example  console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01
%sOutputs a string.
%fOutputs a floating-point value. Formatting is supported, for example  console.log("Foo %.2f", 1.1) will output the number to 2 decimal places: Foo 1.10
+ +

Each of these pulls the next argument after the format string off the parameter list. For example:

+ +
for (var i=0; i<5; i++) {
+  console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
+}
+
+ +

The output looks like this:

+ +
[13:14:13.481] Hello, Bob. You've called me 1 times.
+[13:14:13.483] Hello, Bob. You've called me 2 times.
+[13:14:13.485] Hello, Bob. You've called me 3 times.
+[13:14:13.487] Hello, Bob. You've called me 4 times.
+[13:14:13.488] Hello, Bob. You've called me 5 times.
+
+ +

Styling console output

+ +

You can use the "%c" directive to apply a CSS style to console output:

+ +
console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
+ +
The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.
+ +
 
+ +
+ +
 
+ +
+

Note: Quite a few CSS properties are supported by this styling; you should experiment and see which ones prove useful.

+
+ +
 
+ +
{{h3_gecko_minversion("Using groups in the console", "9.0")}}
+ +

You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar, but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.

+ +
Note: Collapsed groups are not supported yet in Gecko; the groupCollapsed() method is the same as group() at this time.
+ +

To exit the current group, simply call console.groupEnd(). For example, given this code:

+ +
console.log("This is the outer level");
+console.group();
+console.log("Level 2");
+console.group();
+console.log("Level 3");
+console.warn("More of level 3");
+console.groupEnd();
+console.log("Back to level 2");
+console.groupEnd();
+console.debug("Back to the outer level");
+
+ +

The output looks like this:

+ +

nesting.png

+ +
{{h3_gecko_minversion("Timers", "10.0")}}
+ +

In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the console object. To start a timer, call the console.time() method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd() method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.

+ +

For example, given this code:

+ +
console.time("answer time");
+alert("Click to continue");
+console.timeEnd("answer time");
+
+ +

will log the time needed by the user to discard the alert box:

+ +

timerresult.png

+ +

Notice that the timer's name is displayed both when the timer is started and when it's stopped.

+ +
Note: It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.
+ +

Stack traces

+ +

The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call {{domxref("console.trace()")}}. Given code like this:

+ +
function foo() {
+  function bar() {
+    console.trace();
+  }
+  bar();
+}
+
+foo();
+
+ +

The output in the console looks something like this:

+ +

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +

Notes

+ + + +

See also

+ + + +

Other implementations

+ + diff --git a/files/id/web/api/document/createelement/index.html b/files/id/web/api/document/createelement/index.html new file mode 100644 index 0000000000..0f14c4e8ce --- /dev/null +++ b/files/id/web/api/document/createelement/index.html @@ -0,0 +1,225 @@ +--- +title: Document.createElement() +slug: Web/API/Document/createElement +tags: + - API + - DOM + - Document + - Metode + - Referensi + - createElement +translation_of: Web/API/Document/createElement +--- +
{{APIRef("DOM")}}
+ +

Dalam sebuah dokumen HTML, metode document.createElement() membuat elemen HTML yang ditentukan oleh tagName, atau sebuah  {{domxref("HTMLUnknownElement")}} jika tagName tidak dikenali.

+ +
+

Catatan: Dalam sebuah dokumen XUL , ini membuat elemen XUL yang ditentukan. Pada dokumen lain, ini membuat sebuah elemen dengan sebuah namespace URI yang null.

+
+ +

Sintaks

+ +
var element = document.createElement(tagName[, options]);
+
+ +

Parameter

+ +
+
tagName
+
Sebuah string yang menentukan tipe dari elemen yang akan dibuat. {{domxref("Node.nodeName", "nodeName")}} dari elemen dibuat dengan nilai tagName. Jangan menggunakan nama yang memenuhi syarat (seperti "html:a") dengan metode ini. Ketika dipanggil pada sebuah dokumen HTML, createElement() mengubah tagName menjadi lower case sebelum membuat elemen. Pada Firefox, Opera, dan Chrome, createElement(null) bekerja seperti createElement("null").
+
options{{optional_inline}}
+
Sebuah objek opsional ElementCreationOptions berisi sebuah properti tunggal bernama is, yang nilainya adalah nama tag untuk sebuah elemen khusus yang sebelumnya didefinisikan menggunakan customElements.define(). Lihat {{anch("Web component example")}} untuk lebih jelasnya.
+
+ +

Return value

+ +

Element baru.

+ +

Contoh

+ +

Contoh dasar

+ +

Ini membuat sebuah <div> baru dan memasukannya sebelum elemen dengan ID "div1".

+ +

HTML

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>||Bekerja dengan elemen||</title>
+</head>
+<body>
+  <div id="div1">Teks di atas telah dibuat secara dinamis.</div>
+</body>
+</html>
+
+ +

JavaScript

+ +
document.body.onload = addElement;
+
+function addElement () {
+  // membuat sebuah elemen div baru
+  var newDiv = document.createElement("div");
+  // dan memberikannya sebuah konten
+  var newContent = document.createTextNode("Hi there and greetings!");
+  // menambahkan teks terebut ke div yang baru dibuat
+  newDiv.appendChild(newContent);
+
+  // menambah elemen yang baru dibuat berserta isinya ke dalam DOM
+  var currentDiv = document.getElementById("div1");
+  document.body.insertBefore(newDiv, currentDiv);
+}
+ +

{{EmbedLiveSample("Basic_example", 500, 50)}}

+ +

Contoh komponen web

+ +

Contoh cuplikan berikut diambil dari contoh dari expanding-list-web-component kami (lihat juga secara langsung). Dalam kasus ini, elemen khusus kami memperluas {{domxref("HTMLUListElement")}}, yang mewakili elemen {{htmlelement("ul")}}.

+ +
// Membuat sebuah kelas untuk elemen
+class ExpandingList extends HTMLUListElement {
+  constructor() {
+    // Selalu memanggil super dulu di konstruktor
+    super();
+
+    // definisi konstruktor dihilangkan untuk singkatnya
+    ...
+  }
+}
+
+// Mendefinisi elemen baru
+customElements.define('expanding-list', ExpandingList, { extends: "ul" });
+ +

Jika kita ingin untuk membuat sebuah instance dari elemen ini secara terprogram, kita akan menggunakan sebuah panggilan di sepanjang baris berikut:

+ +
let expandingList = document.createElement('ul', { is : 'expanding-list' })
+ +

Elemen baru akan diberikan sebuah atribut is yang nilainya adalah nama tag elemen khusus.

+ +
+

Catatan: Untuk kompabilitas ke belakang untuk versi sebelumnya dari Spesifikasi Elemen khusus, beberapa peramban (browser) akan memungkinkan Anda untuk melewatkan sebuah string di sini bukan pada sebuah objek, yang mana nilai string  adalah nama tag elemen khusus.

+
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('DOM WHATWG', "#dom-document-createelement", "Document.createElement")}}{{Spec2('DOM WHATWG')}} 
+ +

Kompabilitas peramban

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FiturChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1][2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
argumen options{{CompatVersionUnknown}}[3]{{CompatUnknown}}{{CompatGeckoDesktop(50)}}[4][5]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FiturAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
argumen options{{CompatVersionUnknown}}{{CompatVersionUnknown}}[3]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}[3]
+
+ +

[1] Dimulai dengan Gecko 22.0 {{geckoRelease("22.0")}} createElement() tidak lagi menggunakan antarmuka {{domxref("HTMLSpanElement")}} ketika argumennya adalah "bgsounds", "multicol", atau "image".  Sebagai gantinya, HTMLUnknownElement digunakan untuk "bgsound" dan "multicol" dan {{domxref("HTMLElement")}} HTMLElement digunakan untuk "image".

+ +

[2] Implementasi Gecko dari createElement tidak sesuai dengan spesifikasi DOM untuk dokumen XUL dan XHTML: localName dan namespaceURI tidak diatur ke null pada elemen yang dibuat. Lihat {{ Bug(280692) }} untuk lebih jelasnya.

+ +

[3] Pada versi sebelumnya dari spesifikasi, argumen ini hanyalah sebuah string yang nilainyaadalah nama tag elemen khusus. Misalnya bisa saja document.createElement("button", "custom-button") daripada document.createElement("button", {is: "custom-button"}). Demi kompabilitas ke belakang, Chrome menerima kedua bentuk tersebut, meskipun bentuk string sudah usang.

+ +

[4] Liat [3] di atas: seperti Chrome, Firefox menerima string, bukan sebuah objek di sini, tetapi hanya dari versi 51 dan seterusnya. Pada versi 50, options harus sebuah objek.

+ +

[5] Untuk eksperimen dengan elemen khusus di Firefox, Anda harus mengatur preferensi dom.webcomponents.enabled dan dom.webcomponents.customelements.enabled menjadi true.

+ +

Catatan Quantum CSS

+ + + +

Lihat juga

+ + diff --git a/files/id/web/api/document/index.html b/files/id/web/api/document/index.html new file mode 100644 index 0000000000..08e82db4cc --- /dev/null +++ b/files/id/web/api/document/index.html @@ -0,0 +1,576 @@ +--- +title: Document +slug: Web/API/Document +tags: + - API + - DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/Document +--- +
{{APIRef}}
+ +
 
+ +

The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree. The DOM tree includes elements such as {{HTMLElement("body")}} and {{HTMLElement("table")}}, among many others. It provides functionality which is global to the document, such as obtaining the page's URL and creating new elements in the document.

+ +

{{inheritanceDiagram}}

+ +

The Document interface describes the common properties and methods for any kind of document. Depending on the document's type (e.g. HTML, XML, SVG, …), a larger API is available: HTML documents, served with the text/html content type, also implement the {{domxref("HTMLDocument")}} interface, wherease SVG documents implement the {{domxref("SVGDocument")}} interface.

+ +

Properties

+ +

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

+ +
+
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
+
Provides access to all elements with an id. This is a legacy, non-standard interface and you should use the {{domxref("document.getElementById()")}} method instead.
+
{{domxref("Document.async")}} {{Deprecated_inline}}
+
Used with {{domxref("Document.load")}} to indicate an asynchronous request.
+
{{domxref("Document.characterSet")}} {{readonlyinline}}
+
Returns the character set being used by the document.
+
{{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}
+
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
+
{{domxref("Document.compatMode")}} {{readonlyinline}} {{experimental_inline}}
+
Indicates whether the document is rendered in quirks or strict mode.
+
{{domxref("Document.contentType")}} {{readonlyinline}} {{experimental_inline}}
+
Returns the Content-Type from the MIME Header of the current document.
+
{{domxref("Document.doctype")}} {{readonlyinline}}
+
Returns the Document Type Definition (DTD) of the current document.
+
{{domxref("Document.documentElement")}} {{readonlyinline}}
+
Returns the {{domxref("Element")}} that is a direct child of the document. For HTML documents, this is normally the HTML element.
+
{{domxref("Document.documentURI")}} {{readonlyinline}}
+
Returns the document location as a string.
+
{{domxref("Document.domConfig")}} {{Deprecated_inline}}
+
Should return a {{domxref("DOMConfiguration")}} object.
+
{{domxref("Document.fullscreen")}} {{obsolete_inline}}
+
true when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.
+
{{domxref("Document.hidden")}} {{readonlyinline}}
+
+
{{domxref("Document.implementation")}} {{readonlyinline}}
+
Returns the DOM implementation associated with the current document.
+
{{domxref("Document.inputEncoding")}} {{readonlyinline}} {{Deprecated_inline}}
+
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
+
{{domxref("Document.lastStyleSheetSet")}} {{readonlyinline}}
+
Returns the name of the style sheet set that was last enabled. Has the value null until the style sheet is changed by setting the value of {{domxref("document.selectedStyleSheetSet","selectedStyleSheetSet")}}.
+
{{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}} {{gecko_minversion_inline("8.0")}}
+
Returns a {{jsxref("Boolean")}} that is true only if this document is synthetic, such as a standalone image, video, audio file, or the like.
+
{{domxref("Document.mozFullScreenElement")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
The element that's currently in full screen mode for this document.
+
{{domxref("Document.mozFullScreenEnabled")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
true if calling {{domxref("Element.mozRequestFullscreen()")}} would succeed in the curent document.
+
{{domxref("Document.pointerLockElement")}} {{readonlyinline}} {{experimental_inline}}
+
Returns the element set as the target for mouse events while the pointer is locked. null if lock is pending, pointer is unlocked, or if the target is in another document.
+
{{domxref("Document.preferredStyleSheetSet")}} {{readonlyinline}}
+
Returns the preferred style sheet set as specified by the page author.
+
{{domxref("Document.scrollingElement")}} {{experimental_inline}} {{readonlyinline}}
+
Returns a reference to the {{domxref("Element")}} that scrolls the document.
+
{{domxref("Document.selectedStyleSheetSet")}}
+
Returns which style sheet set is currently in use.
+
{{domxref("Document.styleSheets")}} {{readonlyinline}}
+
Returns a list of the style sheet objects on the current document.
+
{{domxref("Document.styleSheetSets")}} {{readonlyinline}}
+
Returns a list of the style sheet sets available on the document.
+
{{domxref("Document.timeline")}} {{readonlyinline}}
+
+
{{domxref("Document.undoManager")}} {{readonlyinline}} {{experimental_inline}}
+
+
{{domxref("Document.URL")}} {{readonlyinline}}
+
Returns ...
+
{{domxref("Document.visibilityState")}} {{readonlyinline}}
+
+
{{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}
+
Returns the encoding as determined by the XML declaration.
+
{{domxref("Document.xmlStandalone")}} {{obsolete_inline("10.0")}}
+
Returns true if the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), else false.
+
{{domxref("Document.xmlVersion")}} {{obsolete_inline("10.0")}}
+
Returns the version number as specified in the XML declaration or "1.0" if the declaration is absent.
+
+ +

The Document interface is extended with the {{domxref("ParentNode")}} interface:

+ +

{{page("/en-US/docs/Web/API/ParentNode","Properties")}}

+ +

Extension for HTML document

+ +

The Document interface for HTML documents inherits from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents.

+ +
+
{{domxref("Document.activeElement")}} {{readonlyinline}}
+
Returns the currently focused element.
+
{{domxref("Document.alinkColor")}} {{Deprecated_inline}}
+
Returns or sets the color of active links in the document body.
+
{{domxref("Document.anchors")}}
+
Returns a list of all of the anchors in the document.
+
{{domxref("Document.applets")}} {{Deprecated_inline}}
+
Returns an ordered list of the applets within a document.
+
{{domxref("Document.bgColor")}} {{Deprecated_inline}}
+
Gets/sets the background color of the current document.
+
{{domxref("Document.body")}}
+
Returns the {{HTMLElement("body")}} element of the current document.
+
{{domxref("Document.cookie")}}
+
Returns a semicolon-separated list of the cookies for that document or sets a single cookie.
+
{{domxref("Document.defaultView")}} {{readonlyinline}}
+
Returns a reference to the window object.
+
{{domxref("Document.designMode")}}
+
Gets/sets the ability to edit the whole document.
+
{{domxref("Document.dir")}} {{readonlyinline}}
+
Gets/sets directionality (rtl/ltr) of the document.
+
{{domxref("Document.domain")}} {{readonlyinline}}
+
Returns the domain of the current document.
+
{{domxref("Document.embeds")}} {{readonlyinline}}
+
Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.
+
{{domxref("document.fgColor")}} {{Deprecated_inline}}
+
Gets/sets the foreground color, or text color, of the current document.
+
{{domxref("Document.forms")}} {{readonlyinline}}
+
Returns a list of the {{HTMLElement("form")}} elements within the current document.
+
{{domxref("Document.head")}} {{readonlyinline}}
+
Returns the {{HTMLElement("head")}} element of the current document.
+
{{domxref("Document.height")}} {{non-standard_inline}} {{obsolete_inline}}
+
Gets/sets the height of the current document.
+
{{domxref("Document.images")}} {{readonlyinline}}
+
Returns a list of the images in the current document.
+
{{domxref("Document.lastModified")}} {{readonlyinline}}
+
Returns the date on which the document was last modified.
+
{{domxref("Document.linkColor")}} {{Deprecated_inline}}
+
Gets/sets the color of hyperlinks in the document.
+
{{domxref("Document.links")}} {{readonlyinline}}
+
Returns a list of all the hyperlinks in the document.
+
{{domxref("Document.location")}} {{readonlyinline}}
+
Returns the URI of the current document.
+
{{domxref("Document.plugins")}} {{readonlyinline}}
+
Returns a list of the available plugins.
+
{{domxref("Document.readyState")}} {{readonlyinline}}  {{gecko_minversion_inline("1.9.2")}}
+
Returns loading status of the document.
+
{{domxref("Document.referrer")}} {{readonlyinline}}
+
Returns the URI of the page that linked to this page.
+
{{domxref("Document.scripts")}} {{readonlyinline}}
+
Returns all the {{HTMLElement("script")}} elements on the document.
+
{{domxref("Document.title")}}
+
Sets or gets title of the current document.
+
{{domxref("Document.URL")}} {{readonlyInline}}
+
Returns the document location as a string.
+
{{domxref("Document.vlinkColor")}} {{Deprecated_inline}}
+
Gets/sets the color of visited hyperlinks.
+
{{domxref("Document.width")}} {{non-standard_inline}} {{obsolete_inline}}
+
Returns the width of the current document.
+
+ +

Event handlers

+ +
+
{{domxref("GlobalEventHandlers.onabort")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("abort")}} event is raised.
+
{{domxref("Document.onafterscriptexecute")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("afterscriptexecute")}} event.
+
{{domxref("Document.onbeforescriptexecute")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("beforescriptexecute")}} event.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("blur")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncancel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cancel")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncanplay")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplay")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncanplaythrough")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplaythrough")}} event is raised.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("change")}} event is raised.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("click")}} event is raised.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("close")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("contextmenu")}} event is raised.
+
{{domxref("Document.oncopy")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("copy")}} event.
+
{{domxref("GlobalEventHandlers.oncuechange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cuechange")}} event is raised.
+
{{domxref("Document.oncut")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("cut")}} event.
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dblclick")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondrag")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drag")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragend")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragend")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragenter")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragexit")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragexit")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragover")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondrop")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drop")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondurationchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("durationchange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onemptied")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("emptied")}} event is raised.
+
{{domxref("GlobalEventHandlers.onended")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ended")}} event is raised.
+
{{domxref("GlobalEventHandlers.onerror")}}
+
Is an {{domxref("OnErrorEventHandler")}} representing the code to be called when the {{event("error")}} event is raised.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("focus")}} event is raised.
+
{{domxref("Document.onfullscreenchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.
+
{{domxref("Document.onfullscreenerror")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenerror")}} event is raised.
+
{{domxref("GlobalEventHandlers.oninput")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("input")}} event is raised.
+
{{domxref("GlobalEventHandlers.oninvalid")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("invalid")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keydown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keypress")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keyup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onload")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("load")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadeddata")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadeddata")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadedmetadata")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadedmetadata")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousedown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseenter")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousemove")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseout")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseover")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousewheel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousewheel")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpause")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pause")}} event is raised.
+
{{domxref("Document.onpaste")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("paste")}} event.
+
{{domxref("GlobalEventHandlers.onplay")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("play")}} event is raised.
+
{{domxref("GlobalEventHandlers.onplaying")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("playing")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerdown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerdown")}} event is raised.
+
{{domxref("Document.onpointerlockchange")}} {{experimental_inline}}
+
Represents the event handling code for the {{event("pointerlockchange")}} event.
+
{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}
+
Represetnts the event handling code for the {{event("pointerlockerror")}} event.
+
{{domxref("GlobalEventHandlers.onpointermove")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointermove")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointercancel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointercancel")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerover")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerout")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerout")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerevent")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerlockchange")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerlockchange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerlockerror")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerlockerror")}} event is raised.
+
{{domxref("GlobalEventHandlers.onprogress")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("progress")}} event is raised.
+
{{domxref("GlobalEventHandlers.onratechange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ratechange")}} event is raised.
+
{{domxref("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}
+
Represents the event handling code for the {{event("readystatechange")}} event.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("reset")}} event is raised.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("scroll")}} event is raised.
+
{{domxref("GlobalEventHandlers.onseeked")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("seeked")}} event is raised.
+
{{domxref("GlobalEventHandlers.onseeking")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("seeking")}} event is raised.
+
{{domxref("GlobalEventHandlers.onselect")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("select")}} event is raised.
+
{{domxref("GlobalEventHandlers.onselectstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectstart")}} event is raised.
+
{{domxref("Document.onselectionchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onshow")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("show")}} event is raised.
+
{{domxref("GlobalEventHandlers.onsort")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("sort")}} event is raised.
+
{{domxref("GlobalEventHandlers.onstalled")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("stalled")}} event is raised.
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("submit")}} event is raised.
+
{{domxref("GlobalEventHandlers.onsuspend")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("suspend")}} event is raised.
+
{{domxref("GlobalEventHandlers.ontimeupdate")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("timeupdate")}} event is raised.
+
{{domxref("GlobalEventHandlers.onvolumechange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("volumechange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onwaiting")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("waiting")}} event is raised.
+
{{domxref("Document.onwheel")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("wheel")}} event.
+
+ +

Methods

+ +

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

+ +
+
{{domxref("Document.adoptNode()")}}
+
Adopt node from an external document.
+
{{domxref("Document.captureEvents()")}} {{Deprecated_inline}}
+
See {{domxref("Window.captureEvents")}}.
+
{{domxref("Document.caretPositionFromPoint()")}}{{experimental_inline}}
+
Gets the {{domxref("CaretPosition")}} at or near the specified coordinates.
+
{{domxref("Document.caretRangeFromPoint()")}}{{non-standard_inline}}
+
Gets a {{Domxref("Range")}} object for the document fragment under the specified coordinates.
+
{{domxref("Document.createAttribute()")}}
+
Creates a new {{domxref("Attr")}} object and returns it.
+
{{domxref("Document.createAttributeNS()")}}
+
Creates a new attribute node in a given namespace and returns it.
+
{{domxref("Document.createCDATASection()")}}
+
Creates a new CDATA node and returns it.
+
{{domxref("Document.createComment()")}}
+
Creates a new comment node and returns it.
+
{{domxref("Document.createDocumentFragment()")}}
+
Creates a new document fragment.
+
{{domxref("Document.createElement()")}}
+
Creates a new element with the given tag name.
+
{{domxref("Document.createElementNS()")}}
+
Creates a new element with the given tag name and namespace URI.
+
{{domxref("Document.createEntityReference()")}} {{obsolete_inline}}
+
Creates a new entity reference object and returns it.
+
{{domxref("Document.createEvent()")}}
+
Creates an event object.
+
{{domxref("Document.createNodeIterator()")}}
+
Creates a {{domxref("NodeIterator")}} object.
+
{{domxref("Document.createProcessingInstruction()")}}
+
Creates a new {{domxref("ProcessingInstruction")}} object.
+
{{domxref("Document.createRange()")}}
+
Creates a {{domxref("Range")}} object.
+
{{domxref("Document.createTextNode()")}}
+
Creates a text node.
+
{{domxref("Document.createTouch()")}}
+
Creates a {{domxref("Touch")}} object.
+
{{domxref("Document.createTouchList()")}}
+
Creates a {{domxref("TouchList")}} object.
+
{{domxref("Document.createTreeWalker()")}}
+
Creates a {{domxref("TreeWalker")}} object.
+
{{domxref("Document.elementFromPoint()")}}{{experimental_inline}}
+
Returns the topmost element at the specified coordinates. 
+
{{domxref("Document.elementsFromPoint()")}}{{experimental_inline}}
+
Returns an array of all elements at the specified coordinates.
+
{{domxref("Document.enableStyleSheetsForSet()")}}
+
Enables the style sheets for the specified style sheet set.
+
{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
+
Release the pointer lock.
+
{{domxref("Document.getAnimations()")}} {{experimental_inline}}
+
Returns an array of all {{domxref("Animation")}} objects currently in effect whose target elements are descendants of the document.
+
{{domxref("Document.getElementsByClassName()")}}
+
Returns a list of elements with the given class name.
+
{{domxref("Document.getElementsByTagName()")}}
+
Returns a list of elements with the given tag name.
+
{{domxref("Document.getElementsByTagNameNS()")}}
+
Returns a list of elements with the given tag name and namespace.
+
{{domxref("Document.importNode()")}}
+
Returns a clone of a node from an external document.
+
{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}
+
Replaces entities, normalizes text nodes, etc.
+
{{domxref("Document.registerElement()")}} {{experimental_inline}}
+
Registers a web component.
+
{{domxref("Document.releaseCapture()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Releases the current mouse capture if it's on an element in this document.
+
{{domxref("Document.releaseEvents()")}} {{non-standard_inline}} {{Deprecated_inline}}
+
See {{domxref("Window.releaseEvents()")}}.
+
{{domxref("Document.routeEvent()")}} {{non-standard_inline}} {{obsolete_inline(24)}}
+
See {{domxref("Window.routeEvent()")}}.
+
{{domxref("Document.mozSetImageElement()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Allows you to change the element being used as the background image for a specified element ID.
+
+ +

The Document interface is extended with the {{domxref("ParentNode")}} interface:

+ +
+
{{domxref("document.getElementById","document.getElementById(String id)")}}
+
Returns an object reference to the identified element.
+
{{domxref("document.querySelector","document.querySelector(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
+
Returns the first Element node within the document, in document order, that matches the specified selectors.
+
{{domxref("document.querySelectorAll","document.querySelectorAll(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
+
Returns a list of all the Element nodes within the document that match the specified selectors.
+
+ +

The Document interface is extended with the {{domxref("XPathEvaluator")}} interface:

+ +
+
{{domxref("document.createExpression","document.createExpression(String expression, XPathNSResolver resolver)")}}
+
Compiles an XPathExpression which can then be used for (repeated) evaluations.
+
{{domxref("document.createNSResolver","document.createNSResolver(Node resolver)")}}
+
Creates an {{domxref("XPathNSResolver")}} object.
+
{{domxref("document.evaluate","document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}
+
Evaluates an XPath expression.
+
+ +

Extension for HTML documents

+ +

The Document interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents:

+ +
+
{{domxref("document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}
+
In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
+
{{domxref("document.close()")}}
+
Closes a document stream for writing.
+
{{domxref("document.execCommand","document.execCommand(String command[, Boolean showUI[, String value]])")}}
+
On an editable document, executes a formating command.
+
{{domxref("document.getElementsByName","document.getElementsByName(String name)")}}
+
Returns a list of elements with the given name.
+
{{domxref("document.getSelection()")}}
+
Returns a {{domxref("Selection")}} object related to text selected in the document.
+
{{domxref("document.hasFocus()")}}
+
Returns true if the focus is currently located anywhere inside the specified document.
+
{{domxref("document.open()")}}
+
Opens a document stream for writing.
+
{{domxref("document.queryCommandEnabled","document.queryCommandEnabled(String command)")}}
+
Returns true if the formating command can be executed on the current range.
+
{{domxref("document.queryCommandIndeterm","document.queryCommandIndeterm(String command)")}}
+
Returns true if the formating command is in an indeterminate state on the current range.
+
{{domxref("document.queryCommandState","document.queryCommandState(String command)")}}
+
Returns true if the formating command has been executed on the current range.
+
{{domxref("document.queryCommandSupported","document.queryCommandSupported(String command)")}}
+
Returns true if the formating command is supported on the current range.
+
{{domxref("document.queryCommandValue","document.queryCommandValue(String command)")}}
+
Returns the current value of the current range for a formating command.
+
{{domxref("document.write","document.write(String text)")}}
+
Writes text in a document.
+
{{domxref("document.writeln","document.writeln(String text)")}}
+
Writes a line of text in a document.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Selection API', '', 'Extend Document and GlobalEventHandlers')}}{{Spec2('Selection API')}}Adds onselectstart and onselectionchange.
{{SpecName('DOM1','#i-Document','Document')}}{{Spec2('DOM1')}}Initial definition for the interface
{{SpecName('DOM2 Core','#i-Document','Document')}}{{Spec2('DOM2 Core')}}Supersede DOM 1
{{SpecName('DOM3 Core','#i-Document','Document')}}{{Spec2('DOM3 Core')}}Supersede DOM 2
{{SpecName('DOM WHATWG','#interface-document','Document')}}{{Spec2('DOM WHATWG')}}Intend to supersede DOM 3
{{SpecName('HTML WHATWG','dom.html#the-document-object','Document')}}{{Spec2('HTML WHATWG')}}Turn the {{domxref("HTMLDocument")}} interface into a Document extension.
{{SpecName('DOM3 XPath','xpath.html#XPathEvaluator','XPathEvaluator')}}{{Spec2('DOM3 XPath')}}Define the {{domxref("XPathEvaluator")}} interface which extend document.
{{SpecName('HTML Editing','#dom-document-getselection','Document')}}{{Spec2('HTML Editing')}}Extend the Document interface
{{SpecName('CSSOM View','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM View')}}Extend the Document interface
{{SpecName('CSSOM','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM')}}Extend the Document interface
{{SpecName('Pointer Lock','#extensions-to-the-document-interface','Document')}}{{Spec2('Pointer Lock')}}Extend the Document interface
+ +

Browser compatibility notes

+ +

Firefox notes

+ +

Mozilla defines a set of non-standard properties made only for XUL content:

+ +
+
{{domxref("document.currentScript")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Returns the {{HTMLElement("script")}} element that is currently executing.
+
{{domxref("document.documentURIObject")}} {{gecko_minversion_inline("1.9")}}
+
(Mozilla add-ons only!) Returns the {{Interface("nsIURI")}} object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).
+
{{domxref("document.popupNode")}}
+
Returns the node upon which a popup was invoked.
+
{{domxref("document.tooltipNode")}}
+
Returns the node which is the target of the current tooltip.
+
+ +

Mozilla also define some non-standard methods:

+ +
+
{{domxref("document.execCommandShowHelp")}} {{obsolete_inline("14.0")}}
+
This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+
{{domxref("document.getBoxObjectFor")}} {{obsolete_inline}}
+
Use the {{domxref("Element.getBoundingClientRect()")}} method instead.
+
{{domxref("document.loadOverlay")}} {{Fx_minversion_inline("1.5")}}
+
Loads a XUL overlay dynamically. This only works in XUL documents.
+
{{domxref("document.queryCommandText")}} {{obsolete_inline("14.0")}}
+
This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+
+ +

Internet Explorer notes

+ +

Microsoft defines some non-standard properties:

+ +
+
{{domxref("document.fileSize")}}* {{non-standard_inline}} {{obsolete_inline}}
+
Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See MSDN.
+
Internet Explorer does not support all methods from the Node interface in the Document interface:
+
+ +
+
{{domxref("document.contains")}}
+
As a work-around, document.body.contains() can be used.
+
+ +

 

diff --git a/files/id/web/api/document/links/index.html b/files/id/web/api/document/links/index.html new file mode 100644 index 0000000000..4a2d6a5a1b --- /dev/null +++ b/files/id/web/api/document/links/index.html @@ -0,0 +1,101 @@ +--- +title: Document.links +slug: Web/API/Document/links +tags: + - API + - Document + - Property + - Reference +translation_of: Web/API/Document/links +--- +

{{ APIRef("DOM") }}

+ +

Properti links mengembalikan sebuah collection dari semua elemen {{HTMLElement("area")}} dan elemen {{HTMLElement("a")}} pada sebuah dokumen dengan sebuah nilai pada atribut href .

+ +

Sintaks

+ +
nodeList = document.links
+
+ +

Contoh

+ +
var links = document.links;
+for(var i = 0; i < links.length; i++) {
+  var linkHref = document.createTextNode(links[i].href);
+  var lineBreak = document.createElement("br");
+  document.body.appendChild(linkHref);
+  document.body.appendChild(lineBreak);
+}
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('HTML WHATWG', '#dom-document-links', 'Document.links')}}{{ Spec2('HTML WHATWG') }} 
{{SpecName("DOM2 HTML", "html.html#ID-7068919", "document.links")}}{{Spec2("DOM2 HTML")}}Initial definition
+ +

Kompabilitas browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
diff --git a/files/id/web/api/document/write/index.html b/files/id/web/api/document/write/index.html new file mode 100644 index 0000000000..ac3912c415 --- /dev/null +++ b/files/id/web/api/document/write/index.html @@ -0,0 +1,77 @@ +--- +title: Document.write() +slug: Web/API/Document/write +tags: + - API + - DOM + - Method + - Reference +translation_of: Web/API/Document/write +--- +
{{ ApiRef("DOM") }}
+ +

Menuliskan teks string ke sebuah dokumen stream yang dibuka dengan document.open().

+ +
Catatan: ketika document.write menulis ke dokumen stream, memanggil document.write pada sebuah dokumen tertutup (termuat), dokumen secara otomatis memanggil document.open, yang akan menghapus dokumen.
+ +

Sintaks

+ +
document.write(markup);
+
+ +

markup merupakan sebuah string yang berisi teks untuk ditulis ke dalam dokumen.

+ +

Contoh

+ +
<html>
+
+<head>
+<title>write example</title>
+
+<script>
+
+function newContent()
+{
+alert("load new content");
+document.open();
+document.write("<h1>Out with the old - in with the new!</h1>");
+document.close();
+}
+
+</script>
+</head>
+
+<body onload="newContent();">
+<p>Some original document content.</p>
+</body>
+</html>
+
+ +

Catatan

+ +

Menulis ke sebuah dokumen yang telah dimuat tanpa memanggil document.open() akan secara otomatis melakukan panggilan document.open. Setelah selesai menulis, disarankan untuk memanggil document.close(), untuk meminta browser untuk menyelesaikan memuat halaman. Teks yang anda tulis akan di parse ke dalam stuktur model dokumen tersebut. Pada contoh diatas, elemen h1 menjadi sebuah node pada document.

+ +

Jika pemanggilan document.write() merpakan embeded pada inline tag html <script> tag, maka tidak akan memanggil document.open(). Sebagai contoh:

+ +
<script>
+  document.write("<h1>Main title</h1>")
+</script>
+
+ +
Catatan: document.write an document.writeln tidak berfungsi di dokumen XHTML ( anda akan mendapat peringatan "Operation is not supported" [NS_ERROR_DOM_NOT_SUPPORTED_ERR] error pada konsole). Ini terjadi ketika membuka sebuah file lokal dengan ekstensi file .xhtml atau dokumen lain yang disajikan dengan MIME type application/xhtml+xml . Informasi lengkap tersedia di W3C XHTML FAQ.
+ +
Catatan: document.write pada script deferred atau asynchronous akan diabaikan, dan anda mendapatkan peringatan error "A call to document.write() from an asynchronously-loaded external script was ignored" pada konsole.
+ +

Spesifikasi

+ + + +

Lihat juga

+ + diff --git a/files/id/web/api/event/currenttarget/index.html b/files/id/web/api/event/currenttarget/index.html new file mode 100644 index 0000000000..f44c5d54a9 --- /dev/null +++ b/files/id/web/api/event/currenttarget/index.html @@ -0,0 +1,127 @@ +--- +title: Event.currentTarget +slug: Web/API/Event/currentTarget +tags: + - API + - DOM + - Gecko + - events +translation_of: Web/API/Event/currentTarget +--- +

{{APIRef("DOM")}}

+ +

Mengidentifikasi event untuk target saat ini, seperti ketika event melalui DOM. Event tersebut selalu mengacu kepada lemen yang terikat dengan event handler, sebagai lawan dari event.target yang mana mengidentifikasi elemen ketika event tersebut terjadi.

+ +

Contoh

+ +

event.currentTarget sangat menarik untuk digunakan ketika menyatukan event handler yang sama ke beberapa element.

+ +
function hide(e){
+  e.currentTarget.style.visibility = "hidden";
+  console.log(e.currentTarget);
+  // Ketika fungsi digunakan seperti event handler: this === e.currentTarget
+}
+
+var ps = document.getElementsByTagName('p');
+
+for(var i = 0; i < ps.length; i++){
+  // console: print the clicked <p> element
+  ps[i].addEventListener('click', hide, false);
+}
+// console: print <body>
+document.body.addEventListener('click', hide, false);
+
+// click dan paragraph akan menghilang
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName("DOM WHATWG", "#dom-event-currenttarget", "Event.currentTarget")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM4", "#dom-event-currenttarget", "Event.currentTarget")}}{{Spec2("DOM4")}} 
{{SpecName("DOM3 Events", "#dfn-current-event-target", "current event target")}}{{Spec2("DOM3 Events")}} 
{{SpecName("DOM2 Events", "#Events-Event-currentTarget", "Event.currentTarget")}}{{Spec2("DOM2 Events")}}Definisi awal
+ +

Kesesuaian browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}10.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}10.0
+
+ +

[1] Dalam Internet Explorer 6 sampai 8, event modelnya berbeda. Event listener(s) nya terikat dengan metode non-standard {{domxref("EventTarget.attachEvent")}}. Dalam model ini, tidak ada yang setara dengan event.currentTarget dan this adalah objek global. Satu solusin untuk meniru fitur event.currentTarget adalah dengan cara membungkus handler anda di dalam fungsi memanggil handler tersebut menggunakan Function.prototype.call dengan elemen sebagai argumen awal. Dengan cara ini, this akan menampilkan hasil yang diharapkan.

+ +

Lihat juga

+ +

Perbandingan dari Event Targets

diff --git a/files/id/web/api/event/index.html b/files/id/web/api/event/index.html new file mode 100644 index 0000000000..952082247b --- /dev/null +++ b/files/id/web/api/event/index.html @@ -0,0 +1,149 @@ +--- +title: Event +slug: Web/API/Event +tags: + - API + - DOM + - Event + - Interface + - Reference +translation_of: Web/API/Event +--- +

{{APIRef("DOM")}}

+ +

Antarmuka Event mewakili setiap event pada DOM. mengandung properti umum dan method ke setiap event.

+ +

Banyak sekali antarmuka lain yang menginplementasikan antarmuka Event, baik secara langsung atau dengan mengimplementsikan antarmuka lain dimana diantaranya:

+ +
+ +
+ +

Konstruktor

+ +
+
{{domxref("Event.Event", "Event()")}}
+
Membuat sebuah object Event
+
+ +

Properti

+ +

Antarmuka ini tidak mewarisi properti manapun.

+ +
+
{{domxref("Event.bubbles")}} {{readonlyinline}}
+
Sebuah boolean yang menunjukan apakah event bubbles melalui DOM atau tidak.
+
{{domxref("Event.cancelBubble")}} {{non-standard_inline}}
+
Alternatif non-standar untuk {{domxref("Event.stopPropagation()")}}.
+
{{domxref("Event.cancelable")}} {{readonlyinline}}
+
Sebuah boolean yang menunjukan apakah event bisa dibatalkan.
+
{{domxref("Event.currentTarget")}} {{readonlyinline}}
+
Sebuah referensi untuk target terdaftar saat ini untuk event.
+
{{domxref("Event.defaultPrevented")}} {{readonlyinline}}
+
Menunjukan apakah {{domxref("event.preventDefault()")}} telah dipanggil pada event atau belum.
+
{{domxref("Event.eventPhase")}} {{readonlyinline}}
+
Menunjukan fase aliran event yang sedang diproses.
+
{{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
Eksplisit target dari event (Mozilla-specific).
+
{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
Target dari event, sebelum penargetan ulang lain (Mozilla-specific).
+
{{domxref("Event.returnValue")}} {{non-standard_inline}}
+
Alternatif nonstandard untuk {{domxref("Event.preventDefault()")}} dan {{domxref("Event.defaultPrevented")}}. (spesifik Internet Explorer lama)
+
{{domxref("Event.srcElement")}} {{non-standard_inline}}
+
Alias nonstandard untuk {{domxref("Event.target")}}. (spesifik Internet Explorer lama)
+
{{domxref("Event.target")}} {{readonlyinline}}
+
Sebuah referensi untuk target dimana event pertama kali dikirimkan.
+
{{domxref("Event.timeStamp")}} {{readonlyinline}}
+
Waktu ketika event dibuat.
+
{{domxref("Event.type")}} {{readonlyinline}}
+
Nama dari event (case-insensitive).
+
{{domxref("Event.isTrusted")}} {{readonlyinline}}
+
Menunjukan apakah event di terima browser atau tidak (mis. ketika user klik) atau dengan sebuah script (menggunakan sebuah method event buatan, seperti event.initEvent)
+
+ +

Method

+ +

Antarmuka ini tidak mewarisi method manapun.

+ +
+
{{domxref("Event.initEvent()")}} {{deprecated_inline}}
+
Menginisialisasi nilai dari Event yang dibuat. Jika event telah dikirimkan, method ini tidak akan digunakan.
+
{{domxref("Event.preventBubble()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Mencegah event agar tidak menggelegak. Usang, gunakan {{domxref("event.stopPropagation")}} sebagai gantinya.
+
{{domxref("Event.preventCapture()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Usang, gunakan {{domxref("event.stopPropagation")}} sebagai gantinya.
+
{{domxref("Event.preventDefault()")}}
+
Membatalkan event event (jika cancelable).
+
{{domxref("Event.stopImmediatePropagation()")}}
+
Khusus untuk event ini, tidak ada listener lain yang akan dipanggil. Baik yang ada pada elemen yang sama, maupunyang ada pada elemen yang akan di lalui nantinya (pada fase capture, misalnya)
+
{{domxref("Event.stopPropagation()")}}
+
Menghentikan penyebaran events lebih jauh pada DOM.
+
{{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
+
Non-standard. Mengembailkan nilai dari {{domxref("Event.defaultPrevented")}}. Gunakan {{domxref("Event.defaultPrevented")}} sebagai gantinya.
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/api/event/target/index.html b/files/id/web/api/event/target/index.html new file mode 100644 index 0000000000..52397c0827 --- /dev/null +++ b/files/id/web/api/event/target/index.html @@ -0,0 +1,90 @@ +--- +title: Event.target +slug: Web/API/Event/target +translation_of: Web/API/Event/target +--- +
{{ApiRef("DOM")}}
+ +

The target property of the {{domxref("Event")}} interface is a reference to the object onto which the event was dispatched. It is different from {{domxref("Event.currentTarget")}} when the event handler is called during the bubbling or capturing phase of the event.

+ +

Syntax

+ +
var theTarget = event.target;
+ +

Value

+ +

{{domxref("EventTarget")}}

+ +

Example

+ +

Properti event.target dapat digunakan untuk mengimplementasikan event delegation.

+ +
// Membuat sebuah list
+var ul = document.createElement('ul');
+document.body.appendChild(ul);
+
+var li1 = document.createElement('li');
+var li2 = document.createElement('li');
+ul.appendChild(li1);
+ul.appendChild(li2);
+
+function hide(e){
+  // e.target refers to the clicked <li> element
+  // This is different than e.currentTarget which would refer to the parent <ul> in this context
+  e.target.style.visibility = 'hidden';
+}
+
+// Attach the listener to the list
+// It will fire when each <li> is clicked
+ul.addEventListener('click', hide, false);
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-event-target", "Event.target")}}{{Spec2("DOM WHATWG")}}
{{SpecName("DOM4", "#dom-event-target", "Event.target")}}{{Spec2("DOM4")}}
{{SpecName("DOM2 Events", "#Events-Event-target", "Event.target")}}{{Spec2("DOM2 Events")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Event.target")}}

+ +

Compatibility notes

+ +

On IE 6-8 the event model is different. Event listeners are attached with the non-standard {{domxref('EventTarget.attachEvent()')}} method. In this model, the event object has a {{domxref('Event.srcElement')}} property, instead of the target property, and it has the same semantics as Event.target.

+ +
function hide(e) {
+  // Support IE6-8
+  var target = e.target || e.srcElement;
+  target.style.visibility = 'hidden';
+}
+
+ +

See also

+ + diff --git a/files/id/web/api/fetch_api/index.html b/files/id/web/api/fetch_api/index.html new file mode 100644 index 0000000000..ad64ee4558 --- /dev/null +++ b/files/id/web/api/fetch_api/index.html @@ -0,0 +1,88 @@ +--- +title: Fetch API +slug: Web/API/Fetch_API +translation_of: Web/API/Fetch_API +--- +
{{DefaultAPISidebar("Fetch API")}}
+ +

Fetch Data API menyediakan antarmuka untuk pemanggilan sumber daya data(termasuk di seluruh jaringan). Ini akan terasa familiar bagi siapa saja yang telah menggunakan {{DOMxRef("XMLHttpRequest")}}, tetapi untuk API yang terbaru menyediakan serangkaian fitur yang lebih kuat dan fleksibel.

+ +

Konsep dan Penggunaan

+ +

"Fetch" / pengambilan resource data menyediakan definisi umum yaitu objek{{DOMxRef("Request")}} dan {{DOMxRef("Response")}} atau permintaan dan tanggapan(dan hal-hal lain yang kaitannya dengan permintaan jaringan/"HTTP"). Ini akan memungkinkan "request" dan "response" tersebut untuk digunakan di mana pun mereka dibutuhkan di waktu selanjutnya, apakah itu untuk pekerja layanan/service workers(biasanya PWA), Cache API dan hal-hal serupa lainnya yang menangani atau mengubah permintaan dan tanggapan, ataupun juga segala jenis kasus penggunaan yang mungkin mengharuskan Anda untuk menghasilkan response/tanggapan Anda sendiri secara terprogram (baca aja:scr otomatis).

+ +

Ini juga memberikan definisi untuk konsep yang berhubungan dengan request dan response seperti halnya : CORS dan sumber semantik header HTTP, yang menggantikan definisi mereka yang terpisah di topik lain (bukan disini bahasannya/beda topik).

+ +

Untuk membuat permintaan dan mengambil sumber daya data, bisa menggunakan metode {{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}} ini. Metode ini diimplementasikan dalam beberapa antarmuka aplikasi, khususnya pada {{DOMxRef("Window")}} dan {{DOMxRef("WorkerGlobalScope")}}Ini membuatnya tersedia dalam hampir semua konteks yang mana anda mungkin menginginkan untuk mengambil sumber data / resource nya.

+ +

Metode fetch() mengambil satu argumen yang wajib disertakan, path(sbg gambaran kalau di html : tag a dg atribut href) ke sumber data yang anda inginkan untuk mengambilnya. Hal ini mampu untuk mengembalikan hasil/return {{DOMxRef("Promise")}} yang memutuskan ke {{DOMxRef("Response")}} kepada permintaan itu sendiri, apakah hal tersebut berhasil atau tidak pada saat terjadi response/tanggapan sumber data. Anda juga bisa secara opsional mengirimkan objek pilihan initsebagai argumen keduanya (lihat {{DOMxRef("Request")}}).

+ +

Setelah {{DOMxRef("Response")}} telah dipanggil, ada sejumlah metode yang tersedia untuk menentukan apa saja konten tubuh(pikirkan pada elemen html) dan bagaimana penanganannya (lihat {{DOMxRef("Body")}}).

+ +

Anda juga bisa membuat permintaan dan response secara langsung menggunakan {{DOMxRef("Request.Request", "Request()")}}dan konstruktor {{DOMxRef("Response.Response", "Response()")}}, namun Anda tidak bisa melakukan ini secara langsung. Malahan, ini lebih cenderung sebagai hasil dari aksi yang dilakukan oleh API yang lainnya (misalnya, {{DOMxRef("FetchEvent.respondWith()")}} dari service workers (kalo loe yang main teknologinya PWA pasti tau coy)).

+ +
+

Catatan : Cari tahu lebih lanjut mengenai penggunaan fitur Fetch API di cara menggunakan fetch , dan pelajari konsepnya di konsep dasar fetch .

+
+ +

Batalkan fetch

+ +

Web browser sudah mulai menambahkan dukungan eksperimental untuk antarmuka {{DOMxRef("AbortController")}} dan {{DOMxRef("AbortSignal")}}(alias API Abort), yang memungkinkan operasi seperti Fetch dan XHR untuk dibatalkan apabila mereka belum selesai secara sempurna dipanggil. Lihat halaman antarmuka untuk detail lebih lanjut.

+ +

Browsers have started to add experimental support for the {{DOMxRef("AbortController")}} and {{DOMxRef("AbortSignal")}} interfaces (aka The Abort API), which allow operation

+ +

 

+ +

Antarmuka metode Fetch

+ +
+
WindowOrWorkerGlobalScope.fetch()
+
Metode fetch() yang digunakan untuk mengambil sumber data.
+
Headers
+
Merupakan header respons / permintaan, memungkinkan Anda untuk menanyakannya(query) dan mengambil tindakan yang berbeda dimana ini tergantung pada hasilnya.
+
Request
+
Merupakan permintaan sumber data.
+
Response
+
Merupakan respons terhadap permintaan.
+
+ +

Fetch mixin

+ +
+
{{DOMxRef("Body")}}
+
Menyediakan metode yang berkaitan dengan konten pada respons / permintaan, memungkinkan Anda untuk menyatakan jenis kontennya dan bagaimana penanganannya.
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpesifikasiStatusKeterangan
{{SpecName("Fetch")}}{{Spec2("Fetch")}}Definisi awal
+ +

Kompatibilitas Browser

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

Lihat juga untuk 

+ + diff --git a/files/id/web/api/index.html b/files/id/web/api/index.html new file mode 100644 index 0000000000..bbbaf07d0a --- /dev/null +++ b/files/id/web/api/index.html @@ -0,0 +1,12 @@ +--- +title: Referensi API Web +slug: Web/API +tags: + - API + - Develop + - Web API +translation_of: Web/API +--- +

Saat menulis kode untuk Web menggunakan JavaScript, ada banyak API yang tersedia. Berikut adalah daftar semua antarmuka (atau dengan kata lain, tipe objek) yang dapat digunakan ketika mengembangkan aplikasi atau situs web.

+ +
{{APIListAlpha}}
diff --git a/files/id/web/api/mobile_connection_api/index.html b/files/id/web/api/mobile_connection_api/index.html new file mode 100644 index 0000000000..7b5462e2ef --- /dev/null +++ b/files/id/web/api/mobile_connection_api/index.html @@ -0,0 +1,149 @@ +--- +title: Mobile Connection +slug: Web/API/Mobile_Connection_API +translation_of: Archive/B2G_OS/API/Mobile_Connection_API +--- +

{{ draft }}

+

{{ non-standard_header() }}

+

{{ B2GOnlyHeader2('certified') }}

+

Summary

+

This API has 2 purposes:

+ +

As this API can access functionalities that can have an impact on the mobile plan subscribed by the user (some of the functionalities can cost money to use or can damage the ICC), it is restricted to certified applications only.

+

The main entry point for this API is the {{domxref("window.navigator.mozMobileConnection","navigator.mozMobileConnection")}} property which is an instance of the {{domxref("MozMobileConnection")}} interface.

+

State of mobile connection

+

The state of the mobile connection is divided in two: on the one hand the voice connection, on the other hand the data connection. The data related to each type of connection are accessible through the {{domxref("MozMobileConnection.voice")}} and {{domxref("MozMobileConnection.data")}} properties which both return a {{domxref("MozMobileConnectionInfo")}} object.

+

Those objects give access to all information related to the quality of the network (signal strength, quality of the signal, position of the network's cells, restricted usage, roaming, etc.), and related to the carrier operating the network.

+
var cnx = navigator.mozMobileConnection;
+
+console.log("The voice operator is " + cnx.voice.network.longName);
+
+if (cnx.voice.connected) {
+  console.log("The signal has a strength of " + (+cnx.voice.relSignalStrength) + "%");
+} else {
+  console.log("The state of the connection is: " + cnx.voice.state);
+}
+
+

ICC Functionalities

+

The functionalities available for the ICC can be divided into two categories: the management of the ICC itself and the use of the integrated command available within the STK (SIM Application Toolkit).

+

Basic actions

+

The {{domxref("MozMobileConnection")}} provides a set of methods to deal with common behaviors on ICCs.

+
+

Note: All original methods from the MozMobileConnection interface are fully asynchronous. They all return a {{domxref("DOMRequest")}} object which has an onsuccess and onerror event handler to handle the success or failure of the method call.

+
+

Card lock

+

As long as a card is locked, a user is unable to use it to reach its mobile network. It's possible to manage the card lock with the {{domxref("MozMobileConnection.getCardLock","getCardLock()")}}, {{domxref("MozMobileConnection.setCardLock","setCardLock()")}}, and {{domxref("MozMobileConnection.unlockCardLock","unlockCardLock()")}} methods.

+

If {{domxref("MozMobileConnection.getCardLock","getCardLock()")}} allows to get some detailed information about the lock, it's also possible to have quick info about the lock through {{domxref("MozMobileConnection.cardState")}} which returns a string representing the current state of the lock.

+
+

Note: Even if the state change requests are successfully handled, it does not mean that the operations are necessarily successful. For that reason, any change in the card state is tracked independently through events:

+ +
+
var cnx = navigator.mozMobileConnection;
+
+function unlockCard() {
+  var unlockOptions = {
+    lockType: "pin",
+    pin     : prompt("Please, enter your PIN")
+  }
+
+  var unlock = cnx.unlockCardLock(unlockOptions);
+
+  unlock.onsuccess = function () {
+    console.log("The card has successfully handled the PIN number.");
+
+    if (this.result.success === false) {
+      if (this.result.retryCount > 0) {
+        console.log("But you mistyped your PIN, you have " + this.result.retryCount + " tries left.");
+      } else {
+        console.log("But your card is hard locked, you need to contact your carrier to get a special unlocking code.");
+      }
+    }
+  }
+
+  unlock.onerror = function () {
+    console.log("Hu! Something goes very wrong!")
+  }
+}
+
+cnx.addEventListener('icccardlockerror', function () {
+  // In case of error, ask the user for his PIN again
+  unlockCard();
+});
+
+cnx.addEventListener('cardsatechange', function () {
+  // In case the card state change and required to be unlocked
+  if (cnx.cardState === 'pinRequired') {
+    unlockCard();
+  }
+}
+
+// First call to unlockCard if required
+if (cnx.cardState === 'pinRequired') {
+  unlockCard();
+}
+
+

MMI Messages

+

MMI messages are human understandable code that, once typed with a phone keyboard, allow to trigger specific action from the RIL or get response from the network through a USSD request. A common example is typing a short code to get the IMEI phone number.

+

Such messages are sent using the {{domxref("MozMobileConnection.sendMMI()")}} method (and can be canceled with {{domxref("MozMobileConnection.cancelMMI","cancelMMI()")}}). Even if it will return a {{domxref("DOMRequest")}} object, the response to such messages are handled in two ways:

+ +
var cnx = navigator.mozMobileConnection;
+
+cnx.addEventHandler('ussdreceived', function (evt) {
+  console.log('Network message: ' + evt.data.message);
+});
+
+var MMIRequest = cnx.sendMMI(prompt('Provide a valid MMI'));
+
+MMIRequest.onerror = function() {
+  console.log("Mmmh... Something goes wrong.");
+}
+
+

Call forwarding options

+

Call forwarding options allow to define how a call can or cannot be forwarded to another phone number.

+

Those options are handled with the {{domxref("MozMobileConnection.getCallForwardingOption","getCallForwardingOption()")}} and {{domxref("MozMobileConnection.setCallForwardingOption","setCallForwardingOption()")}} methods.

+
var options = {
+  action      : MozMobileCFInfo.CALL_FORWARD_ACTION_ENABLE,
+  reason      : MozMobileCFInfo.CALL_FORWARD_REASON_UNCONDITIONAL,
+  serviceClass: MozMobileConnectionInfo.ICC_SERVICE_CLASS_VOICE,
+  number      : prompt('To which phone number would you wish to forward the calls?'),
+  timeSeconds : 5
+};
+
+var setOption = navigator.mozMobileConnection.setCallForwardingOption(options);
+
+setOption.onsuccess = function () {
+  console.log('Options successfully set');
+}
+
+setOption.onerror = function () {
+  console.log('Unable to set options: ' + this.error.name);
+}
+
+

STK commands

+

The STK commands depend on many factors (carriers, chips model, etc.) but can always be accessed through the {{domxref("MozMobileConnection.icc")}} property which returns a {{domxref("MozIccManager")}} object.

+
+

Warning: It's recommended to use the STK command only if you already know exactly what you are doing, as a misusage can damage the chip and make it unusable.

+
+

Specification

+

Not part of any specification.

+

See also

+ diff --git a/files/id/web/api/navigator/index.html b/files/id/web/api/navigator/index.html new file mode 100644 index 0000000000..9d40d2eee4 --- /dev/null +++ b/files/id/web/api/navigator/index.html @@ -0,0 +1,149 @@ +--- +title: Navigator +slug: Web/API/Navigator +tags: + - API + - HTML DOM + - HTML-DOM + - Interface + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - Web Performance +translation_of: Web/API/Navigator +--- +

{{ apiref() }}

+ +

Antarmuka Navigator mewakili negara dan identitas pengguna. Memungkinkan script untuk melakukan query dan mendaftarkan diri untuk melakukan suatu aktivitas.

+ +

Objek Navigator dapat dipanggil menggunakan properti {{domxref("Window.navigator")}}.

+ +

Properti

+ +

Bukan turunan dari properti manapun, namun menginplementasikan yang didefinisikan di  {{domxref("NavigatorID")}}, {{domxref("NavigatorLanguage")}}, {{domxref("NavigatorOnLine")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorStorageUtils")}}, {{domxref("NavigatorCookies")}}, {{domxref("NavigatorConcurrentHardware")}}, {{domxref("NavigatorPlugins")}}, dan {{domxref("NavigatorUserMedia")}}.

+ +

Standard

+ +
+
{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}
+
Mengembalikan sebuah array yang berisi setiap objek {{domxref("VRDisplay")}} yang menyajikan ({{domxref("VRDisplay.ispresenting")}} adalah true).
+
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}
+
Mengembalikan internal nama "code" browser. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.
+
{{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}
+
Mengembalikan  {{domxref("DOMString")}} dengan nama official dari browser. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.
+
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}
+
Mengembalikan versi browser sebagai {{domxref("DOMString")}}. Jangan mengandalkan properti ini untuk mengembalikan nilai yang benar.
+
{{domxref("Navigator.battery")}} {{readonlyInline}}
+
Mengembalikan objek {{domxref("BatteryManager")}} yang memberikan informasi tentang status isi baterai.
+
{{domxref("Navigator.connection")}} {{readonlyInline}}{{experimental_inline}}
+
Menyediakan sebuah objek {{domxref("NetworkInformation")}} yang berisi informasi tentang koneksi jaringan pada perangkat.
+
{{domxref("Navigator.geolocation")}} {{readonlyInline}}
+
Mengembalikan objek {{domxref("Geolocation")}} yang memungkinkan untuk mengakses lokasi perangkat.
+
{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}
+
Mengembalikan jumlah inti logical processor yag tersedia.
+
{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("Boolean")}} flag indicating whether the host browser is Java-enabled or not.
+
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
+
Mengembalikan {{domxref("DOMString")}} berdasarkan bahasa yang digunakan, biasanya bahasa UI pada browser. Nilai null akan dikembalikan jika tidak diketahui.
+
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
+
Mengembalikan sebuah array dari {{domxref("DOMString")}} berdasarkan bahasa yang diketahui pengguna, berdasarkan pengaturan.
+
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
+
Mengembalikan daftar {{domxref("MimeTypeArray")}} dari tipe MIME yang didukung oleh browser.
+
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+
Mengembalikan sebuah {{domxref("Boolean")}} yang menunjukan apakah browser dalam keadaan online.
+
{{domxref("Navigator.oscpu")}}
+
Mengembalikan sebuah string berdasarkan sistem operasi.
+
{{domxref("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}
+
Mengembalikan objek {{domxref("Permissions")}} yang dapat digunakan untuk query dan membaharui status izin dari APIs yang di cakup di Permissions API.
+
{{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.
+
{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.
+
{{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}
+
Always returns 'Gecko', on any browser. This property is kept only for compatibility purpose.
+
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
+
Returns the user agent string for the current browser.
+
{{domxref("Navigator.serviceWorker")}} {{readonlyInline}}
+
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
+
+ +

Non-standard

+ +
+

Firefox OS devices adds more non-standard properties. You can consult them on the Firefox OS Navigator extensions article.

+
+ +

{{domxref("Navigator.buildID")}} {{non-standard_inline}}

+ +
+
Returns the build identifier of the browser (e.g., "2006090803").
+
{{domxref("Navigator.cookieEnabled")}} {{non-standard_inline}}
+
Returns a boolean indicating whether cookies are enabled in the browser or not.
+
{{domxref("Navigator.credentials")}} {{non-standard_inline}}
+
Returns the {{domxref("CredentialsContainer")}} interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. 
+
{{domxref("Navigator.doNotTrack")}} {{non-standard_inline}}
+
Reports the value of the user's do-not-track preference. When this value is "yes", your web site or application should not track the user.
+
{{domxref("Navigator.id")}} {{non-standard_inline}}
+
Returns the {{domxref("window.navigator.id", "id")}} object which you can use to add support for BrowserID to your web site.
+
{{domxref("Navigator.mediaDevices")}} {{non-standard_inline}}
+
Returns a reference to the {{domxref("MediaDevices")}} interface.
+
{{domxref("Navigator.mozNotification")}} {{deprecated_inline("22")}} {{non-standard_inline}}
+ {{domxref("Navigator.webkitNotification")}}
+
Returns a {{domxref("navigator.mozNotification", "notification")}} object you can use to deliver notifications to the user from your web application.
+
{{domxref("Navigator.mozSocial")}} {{non-standard_inline}}
+
The Object, returned by the navigator.mozSocial property, is available within the social media provider's panel to provide functionality it may need.
+
{{domxref("Navigator.presentation")}} {{non-standard_inline}}
+
Returns a reference to the {{domxref("Presentation")}} API.
+
{{domxref("Navigator.productSub")}} {{non-standard_inline}}
+
Returns the build number of the current browser (e.g., "20060909").
+
{{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}
+
Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
+
{{domxref("Navigator.standalone")}} {{non-standard_inline}}
+
Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.
+
{{domxref("Navigator.vendor")}} {{non-standard_inline}}
+
Returns the vendor name of the current browser (e.g., "Netscape6").
+
{{domxref("Navigator.vendorSub")}} {{non-standard_inline}}
+
Returns the vendor version number (e.g. "6.1").
+
{{domxref("Navigator.webkitPointer")}} {{non-standard_inline}}
+
Returns a PointerLock object for the Mouse Lock API.
+
+ +

Methods

+ +

Doesn't inherit any method, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorUserMedia")}}, and {{domxref("NavigatorStorageUtils")}}.

+ +

Standard

+ +
+
{{domxref("Navigator.getVRDisplays()")}} {{experimental_inline}}
+
Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer.
+
{{domxref("Navigator.getUserMedia", "NavigatorUserMedia.getUserMedia()")}}
+
After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.
+
{{domxref("Navigator.registerContentHandler()")}}
+
Allows web sites to register themselves as a possible handler for a given MIME type.
+
{{domxref("Navigator.registerProtocolHandler()")}}
+
Allows web sites to register themselves as a possible handler for a given protocol.
+
{{domxref("Navigator.requestMediaKeySystemAccess()")}} {{experimental_inline}}
+
Returns a {{jsxref("Promise")}} for a MediaKeySystemAccess object.
+
{{domxref("Navigator.sendBeacon()")}}{{experimental_inline}}
+
Used to asynchronously transfer small HTTP data from the User Agent to a web server.
+
{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline("1.7.8")}} {{obsolete_inline("9.0")}} {{experimental_inline}}
+
Returns false. JavaScript taint/untaint functions removed in JavaScript 1.2.
+
{{domxref("Navigator.vibrate()")}} {{gecko_minversion_inline("11.0")}}
+
Causes vibration on devices with support for it. Does nothing if vibration support isn't available.
+
+ +

Non-standard

+ +
+

Firefox OS devices adds more non-standard methods. You can consult them on the Firefox OS Navigator extensions article.

+
+ +

{{domxref("Navigator.mozIsLocallyAvailable()")}} {{non-standard_inline}}

+ +
+
Lets code check to see if the document at a given URI is available without using the network.
+
{{domxref("Navigator.mozPay()")}} {{non-standard_inline}}
+
Allows in-app payment.
+
diff --git a/files/id/web/api/navigator/mediadevices/index.html b/files/id/web/api/navigator/mediadevices/index.html new file mode 100644 index 0000000000..b51d697dd9 --- /dev/null +++ b/files/id/web/api/navigator/mediadevices/index.html @@ -0,0 +1,47 @@ +--- +title: Navigator.mediaDevices +slug: Web/API/Navigator/mediaDevices +translation_of: Web/API/Navigator/mediaDevices +--- +
{{APIRef("Media Capture and Streams")}}
+ +

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

+ +

Syntax

+ +
var mediaDevices = navigator.mediaDevices;
+
+ +

Return value

+ +

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

+ +

Spesifikasi

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

Browser compatibility

+ + + +

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

+ +

Lihat juga

+ + diff --git a/files/id/web/api/navigator/serviceworker/index.html b/files/id/web/api/navigator/serviceworker/index.html new file mode 100644 index 0000000000..2599ecf9a2 --- /dev/null +++ b/files/id/web/api/navigator/serviceworker/index.html @@ -0,0 +1,101 @@ +--- +title: Navigator.serviceWorker +slug: Web/API/Navigator/serviceWorker +tags: + - API + - Reference + - Service Worker +translation_of: Web/API/Navigator/serviceWorker +--- +

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

+ +

Navigator.serviceWorker adalah properti yang hanya bisa dibaca, mengembalikan objek {{domxref("ServiceWorkerContainer")}} untuk dokumen terkait, yang memberikan akses untuk registrasi, penghapusan, upgrade, dan berkomunikasi dengan {{domxref("ServiceWorker")}}.

+ +

Sintaks

+ +
var workerContainerInstance = navigator.serviceWorker;
+
+ +

Nilai

+ +

{{domxref("ServiceWorkerContainer")}}.

+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('Service Workers', '#navigator-service-worker', 'navigator.serviceWorker')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FiturAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatUnknown}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
+ +

[1] Service workers (dan Push) telah di non-aktifkan di Firefox 45 Extended Support Release (ESR.)

+ +

Lihat Juga

+ + diff --git a/files/id/web/api/service_worker_api/index.html b/files/id/web/api/service_worker_api/index.html new file mode 100644 index 0000000000..345f183563 --- /dev/null +++ b/files/id/web/api/service_worker_api/index.html @@ -0,0 +1,283 @@ +--- +title: Service Worker API +slug: Web/API/Service_Worker_API +tags: + - API + - Landing + - NeedsTranslation + - Offline + - Overview + - Reference + - Service Workers + - TopicStub + - Workers +translation_of: Web/API/Service_Worker_API +--- +
+

{{ServiceWorkerSidebar}}

+ +

{{ SeeCompatTable() }}

+ +

Service workers essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.

+
+ +

Service worker concepts and usage

+ +

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)

+ +

A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is not blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and localStorage can't be used inside a service worker.

+ +

Service workers only run over HTTPS, for security reasons. Having modified network requests wide open to man in the middle attacks would be really bad.

+ +
+

Note: Service Workers win over previous attempts in this area such as AppCache because they don't make assumptions about what you are trying to do and then break when those assumptions are not exactly right; you have granular control over everything.

+
+ +
+

Note: Service workers make heavy use of promises, as generally they will wait for responses to come through, after which they will respond with a success or failure action. The promises architecture is ideal for this.

+
+ +

Registration

+ +

A service worker is first registered using the {{domxref("ServiceWorkerContainer.register()")}} method. If successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for URLs accessed by the user inside the whole origin, or inside a subset specified by you.

+ +

Download, install and activate

+ +

At this point, your service worker will observe the following lifecycle:

+ +
    +
  1. Download
  2. +
  3. Install
  4. +
  5. Activate
  6. +
+ +

The service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.

+ +

After that it is downloaded every 24 hours or so. It *may* be downloaded more frequently, but it must be downloaded every 24h to prevent bad scripts from being annoying for too long.

+ +

Installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site.

+ +

If this is the first time a service worker has been made available, installation is attempted, then after a successful installation it is activated.

+ +

If there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the worker in waiting. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates (becoming the active worker).

+ +

You can listen out for the {{domxref("InstallEvent")}}; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage API, and placing assets inside it that you'll want for running your app offline.

+ +

There is also an activate event. The point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker.

+ +

Your service worker can respond to requests using the {{domxref("FetchEvent")}} event. You can modify the response to these requests in any way you want, using the {{domxref("FetchEvent.respondWith") }} method.

+ +
+

Note: Because oninstall/onactivate could take a while to complete, the service worker spec provides a waitUntil method that, when called oninstall or onactivate, passes a promise. Functional events are not dispatched to the service worker until the promise successfully resolves.

+
+ +

For a complete tutorial to show how to build up your first basic example, read Using Service Workers.

+ +

Other use case ideas

+ +

Service workers are also intended to be used for such things as:

+ + + +

In the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example:

+ + + +

Interfaces

+ +
+
{{domxref("Cache") }}
+
Represents the storage for {{domxref("Request")}} / {{domxref("Response")}} object pairs that are cached as part of the {{domxref("ServiceWorker")}} life cycle.
+
{{domxref("CacheStorage") }}
+
Represents the storage for {{domxref("Cache")}} objects. It provides a master directory of all the named caches that a {{domxref("ServiceWorker")}} can access and maintains a mapping of string names to corresponding {{domxref("Cache")}} objects.
+
{{domxref("Client") }}
+
Represents the scope of a service worker client. A service worker client is either a document in a browser context or a {{domxref("SharedWorker")}}, which is controlled by an active worker.
+
{{domxref("Clients") }}
+
Represents a container for a list of {{domxref("Client")}} objects; the main way to access the active service worker clients at the current origin.
+
{{domxref("ExtendableEvent") }}
+
Extends the lifetime of the install and activate events dispatched on the {{domxref("ServiceWorkerGlobalScope")}} as part of the service worker lifecycle. This ensures that any functional events (like {{domxref("FetchEvent")}}) are not dispatched to the {{domxref("ServiceWorker")}} until it upgrades database schemas, deletes outdated cache entries, etc.
+
{{domxref("ExtendableMessageEvent") }}
+
The event object of a {{event("message_(ServiceWorker)","message")}} event fired on a service worker (when a channel message is received on the {{domxref("ServiceWorkerGlobalScope")}} from another context) — extends the lifetime of such events.
+
{{domxref("FetchEvent") }}
+
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onfetch")}} handler, FetchEvent represents a fetch action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. It contains information about the request and resulting response, and provides the {{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}} method, which allows us to provide an arbitrary response back to the controlled page.
+
{{domxref("InstallEvent") }}
+
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}} handler, the InstallEvent interface represents an install action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. As a child of {{domxref("ExtendableEvent")}}, it ensures that functional events such as {{domxref("FetchEvent")}} are not dispatched during installation. 
+
{{domxref("Navigator.serviceWorker") }}
+
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
+
{{domxref("NotificationEvent") }}
+
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} handler, the NotificationEvent interface represents a notification click event that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}.
+
{{domxref("ServiceWorker") }}
+
Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same ServiceWorker object.
+
{{domxref("ServiceWorkerContainer") }}
+
Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.
+
{{domxref("ServiceWorkerGlobalScope") }}
+
Represents the global execution context of a service worker.
+
{{domxref("ServiceWorkerMessageEvent")}}
+
Contains information about an event sent to a {{domxref("ServiceWorkerContainer")}} target. 
+
{{domxref("ServiceWorkerRegistration") }}
+
Represents a service worker registration.
+
{{domxref("SyncEvent")}} {{non-standard_inline}}
+
+

The SyncEvent interface represents a sync action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a ServiceWorker. 

+
+
{{domxref("SyncManager")}} {{non-standard_inline}}
+
Provides an interface for registering and listing sync registrations.
+
{{domxref("WindowClient") }}
+
Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of {{domxref("Client")}} object, with some additional methods and properties available.
+
+ +

Specifications

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

Browser compatibility

+ +
{{ CompatibilityTable() }}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}24{{ CompatNo() }}
install/activate events{{ CompatChrome(40.0) }}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
+ respondWith()
{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache +

{{CompatChrome(42.0)}}

+
{{ CompatGeckoDesktop("39.0") }}[1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support {{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
 install/activate events{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
+ respondWith()
{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache{{ CompatNo() }}{{CompatChrome(40.0)}}{{ CompatGeckoMobile("39.0") }}{{ CompatVersionUnknown }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

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

+ +

See also

+ + diff --git a/files/id/web/api/service_worker_api/using_service_workers/index.html b/files/id/web/api/service_worker_api/using_service_workers/index.html new file mode 100644 index 0000000000..b88643f6ed --- /dev/null +++ b/files/id/web/api/service_worker_api/using_service_workers/index.html @@ -0,0 +1,539 @@ +--- +title: Menggunakan Service Workers +slug: Web/API/Service_Worker_API/Using_Service_Workers +tags: + - Paduan + - ServiceWorker + - dasar +translation_of: Web/API/Service_Worker_API/Using_Service_Workers +--- +

{{ServiceWorkerSidebar}}

+ +

{{ SeeCompatTable() }}

+ +
+

Artikel ini memberikan informasi mengenai cara memulai dan menggunakan Service Workers, Termasuk arsitektur dasar, mendaftarkan service worker, penginstalan dan proses aktivasi service worker, memperbaharui service worker, kontrol cache dan custom response, Semuanya dalam konteks aplikasi sederhana dengan fungsi offline. 

+
+ +

Premis Service Workers

+ +

Salah satu masalah utama yang dialami pengguna web selama bertahun - tahun adalah hilangnya konektivitas. Bahkan aplikasi terbaik didunia sekalipun akan memberikan pengalaman pengguna yang buruk jika tidak bisa di muat atau di download. Berbagai upaya menciptakan teknologi telah dilakukan untuk memecahkan masalah tersebut, Agar halaman Offline dapat digunakan, dan beberapa masalah telah diselesaikan.Tapi masalah utamanya masih belum ada mekanisame kontrol yang terbaik untuk semua permintaan aset cache dan kostum jaringan.
+
+ Pada upaya sebelumnya — AppCache — dilihat sebagai ide yang bagus karena disana anda juga bisa menentukan aset untuk dicache dengan mudah. Namun, itu membuat asumsi tentang ketika anda mencoba dan kemudian pecah dengan mengerikan ketika aplikasi anda tidak mengikuti asumsi premis. Baca artikel Jake Archibald's Application Cache is a Douchebag untuk lebih detail.

+ +
+

Catatan: Pada firefox 44, ketika AppCache digunakan untuk menyediakan layanan offline untuk suatu halaman, pesan peringatan sekarang akan ditampilkan di console menyarankan pengembang untuk menggunakan Service workers  ({{bug("1204581")}}.)

+
+ +

Service worker seharusnya telah memecahkan masalah ini. Syntax pada service worker lebih kompleks di bandingkan AppCache, tapi kesamaanya adalah anda bisa menggunkan javascript untuk mengontrol AppCache anda secara tersirat dengan derajat grunality yang lebih bagus, memungkinkan anda untuk menangani masalah ini dan banyak lagi. Dengan menggunakan Service worker anda bisa mengatur aplikasi untuk menggunakan aset utama, sehingga memberikan pengalaman utama bahkan saat offline, sebelum mendapatkan lebih banyak data dari jaringan (biasa disebut sebagai Offline First). Ini sudah tersedia dengan aplikasi asli, yang merupakan salah satu alasan utama aplikasi asli sering dipilih lebih dari aplikasi web.

+ +

Persiapan bermain dengan service worker

+ +

Banyak fitur service worker saat ini telah di aktifkan secara default pada browser versi terbaru yang mendukung. Tapi jika anda menemui kode demo tidak bekerja pada versi browser anda, mungkin anda perlu mengaktifkan preferensi:

+ + + +

Anda perlu menyajikan kode dengan menggunakan HTTPS — Service Workers dibatasi dengan hanya dapat di jalankan pada HTTPS untuk alasan keamanan. Github merupakan salah satu tempat yang di sarankan untuk bereksperimen, karena mendukung HTTPS.

+ +

Arsitektur dasar

+ +

Dengan service workers, langkah - langkah umum berikut perlu diamati untuk konfigurasi dasar:

+ +
    +
  1. URL service worker diambil di daftarkan melalui {{domxref("serviceWorkerContainer.register()")}}.
  2. +
  3. Jika sukses, service worker dijalankan di {{domxref("ServiceWorkerGlobalScope") }}; pada dasarnya ini merupakan hal yang sepesial dari konteks worker, menjalankan tread script utama untuk pengeksekusian, tanpa dukungan akses DOM.
  4. +
  5. Sekarang service worker telah siap untuk memproses event.
  6. +
  7. Instalasai service worker dicoba ketika service worker mengontrol halaman yang diakses setelah dan sebelumnya. Even Install akan selalu di kirim pertama kali ke service workerr ( ini bisa digunakan untuk memulai proses untuk mengumpulkan IndexedDB, dan mencache aset situs). Sama halnya seperti prosedur penginstalan asli atau aplikasi firefox OS — memungkinkan semuanya tersedia untuk digunakan secara offline.
  8. +
  9. Ketika handler oninstall selesai, service worker ditetapkan untuk diinstall.
  10. +
  11. Selanjutnya adalah aktivasi. Ketika service worker terinstall, selanjutnya akan menerima event activate. Penggunaan utama dari onactivate adalah untuk membersihkan sumberdaya yang digunakan pada versi sebelumnya.
  12. +
  13. Service Worker sekarang dapat mengontrol halaman, tapi hanya yang di buka setelah register() telah sukses. misal dokumen mulai aktif dengan atau tanpa Service Worker dan menjaganya selama masih digunakan. Jadi dokumen harus di muat ulang agar benar - benar terkontrol.
  14. +
+ +

+ +

Grafik dibawah menunjukan ringkasan dari event yang tersedia pada service worker:

+ +

install, activate, message, fetch, sync, push

+ +

Promis

+ +

Promis adalah mekanisme yang sebagian besar digunakan untuk menjalankan operasi secara asinkron, dengan bergantung pada pencapaian satu dan lainnya. Ini merupakan pusat dari cara kerja service workers.
+
+ Promis bisa digunakan untuk melakukan banyak hal, tapi untuk saat ini, yang perlu anda tahu adalah jika sesuatu yang mengembalikan promise, anda bisa menambahkan.then() di akhir dan menambahkan callback di dalamnya untuk mengetahui apakah berhasil, gagal da lainnya., atau anda bisa menambahkan .catch() di akhir jika anda ingin menambahkan calback status gagal.

+ +

Mari bandingkan kesamaan struktur callback tradisional synchronous dan promise asynchronous.

+ +

sync

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

async

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

Pada contoh pertama, kita perlu mengunggu myFunction() untuk dijalankan dan mengembalikan nilai sebelum kode lain bisa dijalankan. Pada contoh kedua, myFunction() mengembalikan promise untuk nilai, kemudian semua kode dapat di bawa untuk dapat dijalankan. Ketika promise diselesaikan, kode didalamnya bisa dijalankan secara asynchronously.
+
+ Sebagai contoh nyata — jika kita ingin memuat gambar secara dinamic, tapi kita ingin memastikan bahwa gambar tersebut di muat terlebih dahulu sebelum di tampilkan? Hal standar ini yang ingin dilakukan, tapi ini akan sedikit sulit. Kita bisa mengunakan .onload untuk hanya menampilkan gambar setelah di muat, tapi bagaimana dengan event yang memulai sebelum kita memulai melacaknya ? kita bisa mencoba melakukannya dengan menggunakan.complete, tapi ini tetap tidak foolproof, dan bagaimana dengan lebih dari satu gambar? Dan, ummm, ini tetap synchronous, Jadi di blok di tread utama.
+
+ Gantinya, kita bisa membuat promis kita sendiri untuk mengatasi kasus seperi ini. (Lihat contoh Promises test untuk kode sumber, atau Lihat cara kerja secara live.)

+ +

{{note("Implementasi service worker akan mengutamakan menggunakan caching dan onfetch daripada XMLHttpRequest API. Fitur tersebut tidak di gunakan disini jadi anda hanya fokus pada penggunaan Promises.")}}

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

Kita mengembalikan promis baru menggunakan konstruktor Promise(), di mana menggunakan argumen sebagai fungsi callback dengan parameter resolve dan reject. DImanapung di fungsi, kita perlu mendefinisikan apa yang terjadi untuk promise yang diselesaikan secara sukses atau ditolak — pada kasus ini mengembalikan status 200 OK atau tidak — dan kemudian memanggil  resolve ketika sukses, atau reject jika gagal. Semua konten dari fungsi ini adalah perangkat dasar XHR, jadi kita tidak perlu khawatir untuk saat ini.

+ +

Ketika memanggil fungsi imgLoad(), kita memanggilnya dengan menggunakan url gambar yang akan dimuat, seperti yang kita harapkan, namun kodenya sedikit berbeda:

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

Pada akhir pemanggilan fungsi, kita menggabungkan promise method then(), dimana terdiri dari dua fungsi — yang pertama akan di eksekusi ketika promise berhasil di selesaikan, dan yang kedua akan dipanggil ketika promise di tolak. Pada penyelesaian kasus, kita menampilkan gambar di dalam myImage dan menambahkannya ke body (dengan argumen request.response yang berada di dalam method resolve); pada kasus ditolak kita mengembalikan error di console.

+ +

Semua terjadi secara asynchronously.

+ +
+

Catatan: Anda juga bisa menggabungkan panggilan promise secara bersamaan, Misal:
+ myPromise().then(success, failure).then(success).catch(failure);

+
+ +
+

Catatan: Anda bisa mendapatkan lebih banyak informasi tentang promise dengan membaca tulisan Jake Archibald’s excellent JavaScript Promises: there and back again.

+
+ +

Demo service workers

+ +

Sebagai demonstrasi hanya sekedar dasar pendaftaran dan penginstalan service worker, kita membuat sebuah demo sederhana dengan nama sw-test, berupa galeri gambar Star wars Lego. Mengunakan fungsi dengan promise untuk membaca data gambar dari sebuah objek JSON dan memuat gambar menggunakan Ajax, Sebelum menamilkan gambar pada halaman. Kita akan semuanya tetap simple dan statis untuk saat ini. Di sini pendaftaran, instalasi, dan akativasi sebuah service worker, dan ketika semua spec di dukung oleh browsers maka semua file yang diperukan akan dicache untuk di muat secara offline!

+ +


+
+
+ Anda bisa melihat source code di GitHub, dan Melihat contoh secara live. The one bit we’ll call out here is the promise (see app.js lines 17-42), which is a modified version of what you read about above, in the Promises test demo. It is different in the following ways:

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

Enter Service workers

+ +

Now let’s get on to service workers!

+ +

Mendaftarkan worker

+ +

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

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

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

+ +
+

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

+
+ +
+

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

+
+ +

Kenapa service worker saya gagal didaftarkan?

+ +

Hal tersebut bisa terjadi karena alasan berikut:

+ +
    +
  1. Anda tidak menjalankan aplikasi dari HTTPS.
  2. +
  3. Path dari file service worker anda tidak ditulis dengan benar — seharusnya di tulis relatif terhadap origin, bukan root dari direktori aplikasi anda. Pada contoh, worker berada di https://mdn.github.io/sw-test/sw.js, dan root aplikasi di https://mdn.github.io/sw-test/. Namun path harus ditulis /sw-test/sw.js, bukan /sw.js.
  4. +
  5. The service worker being pointed to is on a different origin to that of your app. This is also not allowed.
  6. +
+ +

+ +

Also note:

+ + + +

Install dan activasi: mengumpulkan cache

+ +

Setelah service worker anda terdaftar, browser akan menginstall dan mengaktifkan service worker untuk halaman/situs anda.
+
+ Event instal dijalankan ketika install selesai dengan sukses. Event install biasanya digunakan oleh browser untuk mengumpulkan cache offline dari aset yang akan digunakan untuk menjalankan aplikasi anda secara offline. Untuk melakukannya, kita menggunakan Storage API dari Service Worker — {{domxref("cache")}} —  global pada service worker yang memungkinkan kita menympan aset yang diterima dari response, dan di sandikan berdasarkan request. API ini sama halnya dengan cache pada browser umumnya, tapi lebih spesifik ke domain. Ini persis hinga anda tidak menginginkan — anda punya kontrol penuh.

+ +
+

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

+
+ +

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

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

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

+
+ +
+

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

+
+ +

Custom responses to requests

+ +

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

+ +

+ +

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

+ +

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

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

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

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

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

+ +

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

+ +
    +
  1. +

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

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

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

    + +
    new Response('
    + +

    Hello from your friendly neighbourhood service worker!

    + ', { headers: { 'Content-Type': 'text/html' } })
  4. +
  5. +

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

    + +
    fetch(event.request)
    +
  6. +
  7. +

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

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

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

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

Recovering failed requests

+ +

So caches.match(event.request) is great when there is a match in the service worker cache, but what about cases when there isn’t a match? If we didn’t provide any kind of failure handling, our promise would reject and we would just come up against a network error when a match isn’t found.

+ +

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

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

If the promise rejects, the catch() function returns the default network request for the resource instead, meaning that those who have network available can just load the resource from the server.

+ +

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

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

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

+ +

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

+ +

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

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

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

+ +

Updated code pattern suggestion

+ +

This uses more standard promise chaining and returns the response to the document without having to wait for caches.open() to resolve:

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

Membaharui service worker

+ +

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

+ +

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

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

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

+ +

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

+ +

Deleting old caches

+ +

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

+ +

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

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

Dev tools

+ +

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

+ +

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

+ + + +

Spesifikasi

+ + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('Service Workers', '')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("33.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Dukungan dasar{{CompatNo}}{{CompatChrome(40.0)}}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}{{CompatNo}}{{ CompatVersionUnknown() }}{{CompatNo}}
+
+ +

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

+ +

Lihat juga

+ + diff --git a/files/id/web/api/serviceworker/index.html b/files/id/web/api/serviceworker/index.html new file mode 100644 index 0000000000..26787c6031 --- /dev/null +++ b/files/id/web/api/serviceworker/index.html @@ -0,0 +1,157 @@ +--- +title: ServiceWorker +slug: Web/API/ServiceWorker +tags: + - API + - Draft + - Offline + - Referensi + - ServiceWorker +translation_of: Web/API/ServiceWorker +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

Antarmuka ServiceWorker dari ServiceWorker API menyediakan referensi kepada service worker. Konteks multi browsing (mis. halaman, pekerja, dll.) dapat dikaitkan dengan service worker yang sama, masing - masing melalui objek ServiceWorker tersendiri.

+ +

Objek ServiceWorker tersedia di properti {{domxref("ServiceWorkerRegistration.active")}} , dan properti {{domxref("ServiceWorkerContainer.controller")}}  — ini adalah service worker yang aktif dan mengontrol halaman (service worker telah sukses terdaftar, dan halaman yang di kontrol telah di muat kembali.)

+ +

Antarmuka ServiceWorker terbagi sebagai rangkaian siklus event — install dan activate — dan fungsional event termasuk fetch. Objek ServiceWorker memiliki keterkaitan {{domxref("ServiceWorker.state")}}, berdasarkan siklusnya.

+ +

Properti

+ +

Antarmuka ServiceWorker mewarisi properti dari induknya, {{domxref("Worker")}}.

+ +
+
{{domxref("ServiceWorker.scriptURL")}} {{readonlyinline}}
+
Mengembalikan serialisasi script URL ServiceWorker didefinisikan sebagai bagian dari {{domxref("ServiceWorkerRegistration")}}. URL harus dari origin yang sama dengan dokumen yang mendaftarkan ServiceWorker.
+
{{domxref("ServiceWorker.state")}} {{readonlyinline}}
+
Mengembalikan status keadaan service worker. Akan mengembalikan salah satu dari nilai berikut: installing, installed, activating, activated, atau redundant.
+
+ +

Event handlers

+ +
+
{{domxref("ServiceWorker.onstatechange")}} {{readonlyinline}}
+
Properti {{domxref("EventListener")}} dipanggil setiap kali event type statechange di jalankan; Pada dasarnya dijalankan setiap ada perubahan pada {{domxref("ServiceWorker.state")}}.
+
+ +

Method

+ +

Antarmuka ServiceWorker mewarisi method dari induknya, {{domxref("Worker")}}, dengan pengecualian {{domxref("Worker.terminate")}} — tidak harus dapat diakses dari service workers.

+ +

Contoh

+ +

Ini adalah potongan kode dari service worker registration-events sample (live demo). Kode memperhatikan setiap perubahan di {{domxref("ServiceWorker.state")}} dan mengembalikan nilainya.

+ +
if ('serviceWorker' in navigator) {
+    navigator.serviceWorker.register('service-worker.js', {
+        scope: './'
+    }).then(function (registration) {
+        var serviceWorker;
+        if (registration.installing) {
+            serviceWorker = registration.installing;
+            document.querySelector('#kind').textContent = 'Menginstall';
+        } else if (registration.waiting) {
+            serviceWorker = registration.waiting;
+            document.querySelector('#kind').textContent = 'Mengunggu';
+        } else if (registration.active) {
+            serviceWorker = registration.active;
+            document.querySelector('#kind').textContent = 'Aktif';
+        }
+        if (serviceWorker) {
+            // logState(serviceWorker.state);
+            serviceWorker.addEventListener('statechange', function (e) {
+                // logState(e.target.state);
+            });
+        }
+    }).catch (function (error) {
+        // Terjadi kesalahan saat mendaftarkan. File service-worker.js
+        // mungkin tidak tersedia atau terdapat sintaks yang error.
+    });
+} else {
+    // Browser ini tidak mendukung service worker.
+}
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('Service Workers', '#service-worker-obj', 'ServiceWorker')}}{{Spec2('Service Workers')}}Definisi inisial
+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Dukungan dasar{{CompatChrome(40.0)}}{{CompatGeckoDesktop("44.0")}}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FiturAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("44.0")}}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
+
+ +

[1] Service workers (dan Push) telah di nonaktifkan di Firefox 45 Extended Support Release (ESR.)

+ +

See also

+ + diff --git a/files/id/web/api/serviceworkercontainer/index.html b/files/id/web/api/serviceworkercontainer/index.html new file mode 100644 index 0000000000..ab3f71a543 --- /dev/null +++ b/files/id/web/api/serviceworkercontainer/index.html @@ -0,0 +1,132 @@ +--- +title: ServiceWorkerContainer +slug: Web/API/ServiceWorkerContainer +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - Service worker API + - ServiceWorkerContainer + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerContainer +--- +

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

+ +

The ServiceWorkerContainer interface of the Service Worker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.

+ +

Most importantly, it exposes the {{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} method used to register service workers, and the {{domxref("ServiceWorkerContainer.controller")}} property used to determine whether or not the current page is actively controlled.

+ +

Properties

+ +
+
{{domxref("ServiceWorkerContainer.controller")}} {{readonlyinline}}
+
Returns a {{domxref("ServiceWorker")}} object if its state is activated (the same object returned by {{domxref("ServiceWorkerRegistration.active")}}). This property returns null during a force-refresh request (Shift + refresh) or if there is no active worker.
+
+ +
+
{{domxref("ServiceWorkerContainer.ready")}} {{readonlyinline}}
+
Provides a way of delaying code execution until a service worker is active. It returns a {{jsxref("Promise")}} that will never reject, and which waits indefinitely until the {{domxref("ServiceWorkerRegistration")}} associated with the current page has an {{domxref("ServiceWorkerRegistration.active")}} worker. Once that condition is met, it resolves with the {{domxref("ServiceWorkerRegistration")}}.
+
+ +

Events

+ +
+
controllerchange
+
Occurs when the document's associated {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active","active")}} worker.
+ Also available via the {{domxref("ServiceWorkerContainer.oncontrollerchange")}} property.
+
error
+
Fired whenever an error occurs in the associated service workers.
+ Also available via the {{domxref("ServiceWorkerContainer.onerror")}} property.
+
message
+
Occurs when incoming messages are received by the {{domxref("ServiceWorkerContainer")}} object (e.g. via a {{domxref("MessagePort.postMessage()")}} call.)
+ Also available via the {{domxref("ServiceWorkerContainer.onmessage")}} property.
+
+ +

Methods

+ +
+
{{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} 
+
Creates or updates a {{domxref("ServiceWorkerRegistration")}} for the given scriptURL.
+
{{domxref("ServiceWorkerContainer.getRegistration()")}}
+
Gets a {{domxref("ServiceWorkerRegistration")}} object whose scope matches the provided document URL.  The method returns a {{jsxref("Promise")}} that resolves to a {{domxref("ServiceWorkerRegistration")}} or undefined
+
{{domxref("ServiceWorkerContainer.getRegistrations()")}}
+
Returns all {{domxref("ServiceWorkerRegistration")}} objects associated with a ServiceWorkerContainer in an array.  The method returns a {{jsxref("Promise")}} that resolves to an array of {{domxref("ServiceWorkerRegistration")}}. 
+
{{domxref("ServiceWorkerContainer.startMessages()")}}
+
explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via {{domxref("Client.postMessage()")}}). This can be used to react to sent messages earlier, even before that page's content has finished loading.
+
+ +

Examples

+ +

The example below first checks to see if the browser supports service workers. If supported, the code registers the service worker and determines if the page is actively controlled by the service worker. If it isn't, it prompts the user to reload the page so the service worker can take control. The code also reports any registration failures.

+ +
if ('serviceWorker' in navigator) {
+  // Register a service worker hosted at the root of the
+  // site using the default scope.
+  navigator.serviceWorker.register('/sw.js').then(function(registration) {
+    console.log('Service worker registration succeeded:', registration);
+
+    // At this point, you can optionally do something
+    // with registration. See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
+  }).catch(function(error) {
+    console.log('Service worker registration failed:', error);
+  });
+
+  // Independent of the registration, let's also display
+  // information about whether the current page is controlled
+  // by an existing service worker, and when that
+  // controller changes.
+
+  // First, do a one-off check if there's currently a
+  // service worker in control.
+  if (navigator.serviceWorker.controller) {
+    console.log('This page is currently controlled by:', navigator.serviceWorker.controller);
+  }
+
+  // Then, register a handler to detect when a new or
+  // updated service worker takes control.
+  navigator.serviceWorker.oncontrollerchange = function() {
+    console.log('This page is now controlled by:', navigator.serviceWorker.controller);
+  };
+} else {
+  console.log('Service workers are not supported.');
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#serviceworkercontainer', 'ServiceWorkerContainer')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/id/web/api/serviceworkerregistration/index.html b/files/id/web/api/serviceworkerregistration/index.html new file mode 100644 index 0000000000..6ce1b3c033 --- /dev/null +++ b/files/id/web/api/serviceworkerregistration/index.html @@ -0,0 +1,245 @@ +--- +title: ServiceWorkerRegistration +slug: Web/API/ServiceWorkerRegistration +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - ServiceWorkerRegistration + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerRegistration +--- +
+
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+
+ +

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

+ +

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

+ +
+

Note: This feature is available in Web Workers.

+
+ +

Properties

+ +

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

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

Event handlers

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

Methods

+ +

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

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

Examples

+ +

This code snippet is from the service worker registration-events sample (live demo). The code checks to see if the browser supports service workers and if there's currently a service worker handling requests on this page for the current navigation.

+ +

Any new service workers are registered; if there's an existing service worker, the code overrides its default scope so that the registration applies to the current directory and everything underneath it. The example also reports any registration failures.

+ +
if ('serviceWorker' in navigator) {
+  document.querySelector('#availability').innerText = 'are';
+  document.querySelector('#controlled').innerText = navigator.serviceWorker.controller ? 'is' : 'is not';
+  navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(function(registration) {
+    document.querySelector('#register').textContent = 'succeeded';
+  }).catch(function(error) {
+    document.querySelector('#register').textContent = 'failed: ' + error;
+  });
+} else {
+  document.querySelector('#availability').innerText = 'are not';
+}
+ +

Specifications

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

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Available in web workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("44.0")}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
getNotifications(), showNotification(){{CompatVersionUnknown}}{{CompatGeckoDesktop("46.0")}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
sync property{{CompatChrome(49.0)}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
Available in web workers{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("44.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
getNotifications(), showNotification(){{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("46.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
sync property{{CompatNo}}{{CompatNo}}     {{CompatChrome(49.0)}}
+
+ +

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

+ +

See also

+ + diff --git a/files/id/web/api/serviceworkerregistration/pushmanager/index.html b/files/id/web/api/serviceworkerregistration/pushmanager/index.html new file mode 100644 index 0000000000..57f61c1375 --- /dev/null +++ b/files/id/web/api/serviceworkerregistration/pushmanager/index.html @@ -0,0 +1,130 @@ +--- +title: ServiceWorkerRegistration.pushManager +slug: Web/API/ServiceWorkerRegistration/pushManager +tags: + - API + - Property + - Push + - PushManager + - ServiceWorker +translation_of: Web/API/ServiceWorkerRegistration/pushManager +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

Properti pushManager dari interface {{domxref("ServiceWorkerRegistration")}}  Mengembalikan sebuah referensi ke Interface {{domxref("PushManager")}} untuk mengatur push subscriptions; termasuk dukungan untuk berlangganan, mendapatkan langganan yang aktif, dan mengakses izin status push.

+ +

Sintaks

+ +
myPushManager = ServiceWorker.pushManager
+
+ +

Value

+ +

Objek {{domxref("PushManager")}}.

+ +

Contoh

+ +
this.onpush = function(event) {
+  console.log(event.data);
+  // Dari sini kita bisa menyimpan data ke IndexedDB, mengirimnya ke setiap
+  // jendela yang terbuka, menampilkan notifikasi, dsb.
+}
+
+navigator.serviceWorker.register('serviceworker.js').then(
+  function(serviceWorkerRegistration) {
+    serviceWorkerRegistration.pushManager.subscribe().then(
+      function(pushSubscription) {
+        console.log(pushSubscription.subscriptionId);
+        console.log(pushSubscription.endpoint);
+        // Detail langganan push dibutuhkan aplikasi
+        // server kini tersedia, dan dapat di kirimkan menggunakan,
+        // XMLHttpRequest misalnya.
+      }, function(error) {
+        // Pada saat pengembangan menampilkan log ke konsole sangatlah membantu
+        // Di lingkungan produksi juga dapat bermanfaat untuk mengirimkan
+        // informasi error kembali ke aplikasi server.
+        console.log(error);
+      }
+    );
+  });
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Push API', '#pushmanager-interface', 'PushManager')}}{{Spec2('Push API')}}Initial definition.
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
+
+ +

[1] Service workers (dan Push) telah dinonaktifkan di Firefox 45 Extended Support Release (ESR.)

+ +

Lihat Juga

+ + diff --git a/files/id/web/api/speechsynthesis/index.html b/files/id/web/api/speechsynthesis/index.html new file mode 100644 index 0000000000..78a50f3f47 --- /dev/null +++ b/files/id/web/api/speechsynthesis/index.html @@ -0,0 +1,151 @@ +--- +title: SpeechSynthesis +slug: Web/API/SpeechSynthesis +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - Reference + - SpeechSynthesis + - TopicStub + - Web Speech API + - speech + - synthesis +translation_of: Web/API/SpeechSynthesis +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

The SpeechSynthesis interface of the Web Speech API is the controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides.

+ +

Properties

+ +

SpeechSynthesis also inherits properties from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.paused")}} {{readonlyinline}}
+
A {{domxref("Boolean")}} that returns true if the SpeechSynthesis object is in a paused state.
+
{{domxref("SpeechSynthesis.pending")}} {{readonlyinline}}
+
A {{domxref("Boolean")}} that returns true if the utterance queue contains as-yet-unspoken utterances.
+
{{domxref("SpeechSynthesis.speaking")}} {{readonlyinline}}
+
A {{domxref("Boolean")}} that returns true if an utterance is currently in the process of being spoken — even if SpeechSynthesis is in a paused state.
+
+ +
+
+ +

Methods

+ +

SpeechSynthesis also inherits methods from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.cancel()")}}
+
Removes all utterances from the utterance queue.
+
{{domxref("SpeechSynthesis.getVoices()")}}
+
Returns a list of {{domxref("SpeechSynthesisVoice")}} objects representing all the available voices on the current device.
+
{{domxref("SpeechSynthesis.pause()")}}
+
Puts the SpeechSynthesis object into a paused state.
+
{{domxref("SpeechSynthesis.resume()")}}
+
Puts the SpeechSynthesis object into a non-paused state: resumes it if it was already paused.
+
{{domxref("SpeechSynthesis.speak()")}}
+
Adds an {{domxref("SpeechSynthesisUtterance", "utterance")}} to the utterance queue; it will be spoken when any other utterances queued before it have been spoken.
+
+ +

Events

+ +

Listen to this event using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
voiceschanged
+
Fired when the list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed.
+ Also available via the onvoiceschanged property.
+
+ +

Examples

+ +

In our basic Speech synthesiser demo, we first grab a reference to the SpeechSynthesis controller using window.speechSynthesis. After defining some necessary variables, we retrieve a list of the voices available using {{domxref("SpeechSynthesis.getVoices()")}} and populate a select menu with them so the user can choose what voice they want.

+ +

Inside the inputForm.onsubmit handler, we stop the form submitting with preventDefault(),  create a new {{domxref("SpeechSynthesisUtterance")}} instance containing the text from the text {{htmlelement("input")}}, set the utterance's voice to the voice selected in the {{htmlelement("select")}} element, and start the utterance speaking via the {{domxref("SpeechSynthesis.speak()")}} method.

+ +
var synth = window.speechSynthesis;
+
+var inputForm = document.querySelector('form');
+var inputTxt = document.querySelector('.txt');
+var voiceSelect = document.querySelector('select');
+
+var pitch = document.querySelector('#pitch');
+var pitchValue = document.querySelector('.pitch-value');
+var rate = document.querySelector('#rate');
+var rateValue = document.querySelector('.rate-value');
+
+var voices = [];
+
+function populateVoiceList() {
+  voices = synth.getVoices();
+
+  for(i = 0; i < voices.length ; i++) {
+    var option = document.createElement('option');
+    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
+
+    if(voices[i].default) {
+      option.textContent += ' -- DEFAULT';
+    }
+
+    option.setAttribute('data-lang', voices[i].lang);
+    option.setAttribute('data-name', voices[i].name);
+    voiceSelect.appendChild(option);
+  }
+}
+
+populateVoiceList();
+if (speechSynthesis.onvoiceschanged !== undefined) {
+  speechSynthesis.onvoiceschanged = populateVoiceList;
+}
+
+inputForm.onsubmit = function(event) {
+  event.preventDefault();
+
+  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
+  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
+  for(i = 0; i < voices.length ; i++) {
+    if(voices[i].name === selectedOption) {
+      utterThis.voice = voices[i];
+    }
+  }
+  utterThis.pitch = pitch.value;
+  utterThis.rate = rate.value;
+  synth.speak(utterThis);
+
+  inputTxt.blur();
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#tts-section', 'SpeechSynthesis')}}{{Spec2('Web Speech API')}} 
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/id/web/api/speechsynthesis/onvoiceschanged/index.html b/files/id/web/api/speechsynthesis/onvoiceschanged/index.html new file mode 100644 index 0000000000..3a5a3f799c --- /dev/null +++ b/files/id/web/api/speechsynthesis/onvoiceschanged/index.html @@ -0,0 +1,74 @@ +--- +title: Kk +slug: Web/API/SpeechSynthesis/onvoiceschanged +translation_of: Web/API/SpeechSynthesis/onvoiceschanged +--- +
{{APIRef("Web Speech API")}}{{SeeCompatTable}}
+ +

The onvoiceschanged property of the {{domxref("SpeechSynthesis")}} interface represents an event handler that will run when the list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed (when the voiceschanged event fires.)

+ +

This may occur when speech synthesis is being done on the server-side and the voices list is being determined asynchronously, or when client-side voices are installed/uninstalled while a speech synthesis application is running.

+ +

Syntax

+ +
speechSynthesisInstance.onvoiceschanged = function() { ... };
+
+ +

Examples

+ +

This could be used to populate a list of voices that the user can choose between when the event fires (see our Speak easy synthesis demo.) Note that Firefox doesn't support it at present, and will just return a list of voices when {{domxref("SpeechSynthesis.getVoices()")}} is fired. With Chrome however, you have to wait for the event to fire before populating the list, hence the bottom if statement seen below.

+ +
var voices = [];
+
+function populateVoiceList() {
+  voices = synth.getVoices();
+
+  for(i = 0; i < voices.length ; i++) {
+    var option = document.createElement('option');
+    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
+
+    if(voices[i].default) {
+      option.textContent += ' -- DEFAULT';
+    }
+
+    option.setAttribute('data-lang', voices[i].lang);
+    option.setAttribute('data-name', voices[i].name);
+    voiceSelect.appendChild(option);
+  }
+}
+
+populateVoiceList();
+if (speechSynthesis.onvoiceschanged !== undefined) {
+  speechSynthesis.onvoiceschanged = populateVoiceList;
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#dom-speechsynthesis-onvoiceschanged', 'onvoiceschanged')}}{{Spec2('Web Speech API')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.SpeechSynthesis.onvoiceschanged")}}

+
+ +

See also

+ + diff --git a/files/id/web/api/storage/index.html b/files/id/web/api/storage/index.html new file mode 100644 index 0000000000..2231fe2bd8 --- /dev/null +++ b/files/id/web/api/storage/index.html @@ -0,0 +1,100 @@ +--- +title: Storage +slug: Web/API/Storage +translation_of: Web/API/Storage +--- +
{{APIRef("Web Storage API")}}
+ +

The Storage interface of the Web Storage API provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items.

+ +

To manipulate, for instance, the session storage for a domain, a call to {{domxref("Window.sessionStorage")}} is made; whereas for local storage the call is made to {{domxref("Window.localStorage")}}.

+ +

Properties

+ +
+
{{domxref("Storage.length")}} {{readonlyInline}}
+
Returns an integer representing the number of data items stored in the Storage object.
+
+ +

Methods

+ +
+
{{domxref("Storage.key()")}}
+
When passed a number n, this method will return the name of the nth key in the storage.
+
+ +
+
{{domxref("Storage.getItem()")}}
+
When passed a key name, will return that key's value.
+
{{domxref("Storage.setItem()")}}
+
When passed a key name and value, will add that key to the storage, or update that key's value if it already exists.
+
{{domxref("Storage.removeItem()")}}
+
When passed a key name, will remove that key from the storage.
+
{{domxref("Storage.clear()")}}
+
When invoked, will empty all keys out of the storage.
+
+ +

Examples

+ +

Here we access a Storage object by calling localStorage. We first test whether the local storage contains data items using !localStorage.getItem('bgcolor'). If it does, we run a function called setStyles() that grabs the data items using {{domxref("Storage.getItem()")}} and uses those values to update page styles. If it doesn't, we run another function, populateStorage(), which uses {{domxref("Storage.setItem()")}} to set the item values, then runs setStyles().

+ +
if(!localStorage.getItem('bgcolor')) {
+  populateStorage();
+}
+setStyles();
+
+function populateStorage() {
+  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
+  localStorage.setItem('font', document.getElementById('font').value);
+  localStorage.setItem('image', document.getElementById('image').value);
+}
+
+function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  document.getElementById('bgcolor').value = currentColor;
+  document.getElementById('font').value = currentFont;
+  document.getElementById('image').value = currentImage;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +
+

Note: To see this running as a complete working example, see our Web Storage Demo.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#the-storage-interface', 'Storage')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/id/web/api/webgl_api/index.html b/files/id/web/api/webgl_api/index.html new file mode 100644 index 0000000000..3450359705 --- /dev/null +++ b/files/id/web/api/webgl_api/index.html @@ -0,0 +1,235 @@ +--- +title: WebGL +slug: Web/API/WebGL_API +tags: + - Referensi + - WebGL +translation_of: Web/API/WebGL_API +--- +
{{WebGLSidebar}}
+ +
+

WebGL (Web Graphics Library) merupakan JavaScript API untuk merender grafik interaktif dalam bentuk 3D dan 2D pada setiap web browser yang kompitable tanpa menggunakan plug-in. WebGL juga memperkenalkan sebuah API yang berkaitan erat dengan OpenGL ES 2.0 yang dapat digunakan di elemen {{HTMLElement("canvas")}} HTML5.

+
+ +

Dukungan WebGL telah tersedia di Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+ dan Internet Explorer 11+; namum, perangkat pengguna juga harus memiliki perangkat keras yang mendukung fitur ini.

+ +

Elemen {{HTMLElement("canvas")}} juga digunakan oleh Canvas 2D untuk menggambar grafik 2D pada halaman web.

+ +

Referensi

+ +

Standar Antarmuka

+ +
+ +
+ +

Ekstensi

+ +
+ +
+ +

Event

+ + + +

Tipe dan konstanta

+ + + +

Paduan dan tutorial

+ + + +

Tutorial lanjutan

+ + + +

Sumber

+ + + +

Pustaka

+ + + +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('WebGL')}}{{Spec2('WebGL')}}Initial definition. Based on OpenGL ES 2.0
{{SpecName('WebGL2')}}{{Spec2('WebGL2')}}Builds on top of WebGL1. Based on OpenGL ES 3.0.
{{SpecName('OpenGL ES 2.0')}}{{Spec2('OpenGL ES 2.0')}} 
{{SpecName('OpenGL ES 3.0')}}{{Spec2('OpenGL ES 3.0')}} 
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2.0")}}91112[1]5.1[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)Chrome for AndroidIE MobileOpera MobileSafari Mobile
Basic support425[1]{{CompatNo}}12[1]8.1
+
+ +

[1]  Implementasi dari fitur ini adalah eksperimental.

+ +

Catatan kompabilitas

+ +

Selain browser, GPU sendiri juga dibutuhkan untuk mendukung fitur ini. Contohnya, S3 Texture Compression (S3TC) hanya tersedia di tablet berbasis Tegra. Hampir setiap browser membuat konteks WebGL tersedia dari nama konteks webgl, tapi untuk yang lebih lama juga memerlukan experimental-webgl. Selain itu , nantinya WebGL 2 sepenuhnya kompitable dengan yang sebelumnya dan akan memiliki nama konteks webgl2.

+ +

Catatan Gecko

+ +

Pengujian dan debungging WebGL

+ +

Dimulai dari Gecko 10.0 {{geckoRelease("10.0")}}, disana tersedia dua pengaturan yang memungkinkan anda mengontrol kemampuan WebGL untuk keperluan percobaan:

+ +
+
webgl.min_capability_mode
+
Properti Boolean yang, jika true, mengaktifkan mode kemampuan minimum. Pada mode ini, WebGL hanya diatur untuk mendukung fitur pengaturan minimum dan kemampuan yang dibutuhkan oleh spesifikasi WebGL. Memungkinkan anda untuk memastikan bahwa kode WebGL anda akan bekerja untuk setiap perangkat atau browser, tergantung dari kemampuan mereka. Nilai defaultnya adalah false.
+
webgl.disable_extensions
+
Properti Boolean yang, jika true, menonaktifkan semua ekstensi WebGL. Nilai defaultnya false.
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/api/webrtc_api/index.html b/files/id/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..6d9aa7392c --- /dev/null +++ b/files/id/web/api/webrtc_api/index.html @@ -0,0 +1,185 @@ +--- +title: WebRTC API +slug: Web/API/WebRTC_API +translation_of: Web/API/WebRTC_API +--- +
{{APIRef("WebRTC")}}
+ +

WebRTC (Web Real-Time Communications) merupakan teknologi yang memungkinkan situs dan aplikasi berbasis web menangkap dan mengirimkan audio atau video, serta bertukar data antar peramban web tanpa memerlukan adanya perantara. Kumpulan standar di dalam WebRTC membuat pertukaran data dan telekonferensi secara peer-to-peer dapat terjadi tanpa perlu memasang plugins atau aplikasi pihak ketiga.

+ +

WebRTC terdiri dari berbagai API dan protokol yang saling terkait sehingga dapat bekerja sebagaimana mestinya. Dokumentasi ini akan membantu anda untuk memahami dasar-dasar WebRTC, bagaimana mengatur dan menggunakan sambungan data dan media, serta hal lainnya.

+ +

Konsep dan cara penggunaan WebRTC

+ +

WebRTC memiliki beberapa fungsi, begitu halnya juga dengan Media Capture and Streams ({{domxref("MediaDevices")}}) API. Keduanya menghadirkan kemampuan multimedia di dalam web, misalnya audio dan video conferencing, pertukaran file, identity management, serta interaksi pada jaringan telepon dengan cara mengirimkan sinyal {{Glossary("DTMF")}}. Sambungan antar peer dapat terbentuk tanpa plugins tambahan, dan sering kali dapat terbentuk tanpa memerlukan server perantara.

+ +

Sambungan antar peer dibuat menggunakan - dan direpresentasikan oleh - {{domxref("RTCPeerConnection")}}. Ketika sebuah sambungan telah terbentuk dan terbuka, stream media ({{domxref("MediaStream")}}) atau channel data ({{domxref("RTCDataChannel")}}) dapat ditambahkan ke dalam sambungan peer.

+ +

Stream media terdiri dari beberapa track media, yang direpresentasikan oleh sebuah objek {{domxref("MediaStreamTrack")}}, yang berisi salah satu tipe media, yaitu audio, video, dan teks (misalnya subtitle atau nama judul). Umumnya stream terdiri dari setidaknya satu track audio bahkan juga satu track video, dan dapat digunakan untuk mengirim dan menerima media secara live atau dapat berupa rekaman media (misalnya streaming film).

+ +

Anda juga dapat menggunakan sambungan antar peer untuk bertukar sembarang data biner menggunakan {{domxref("RTCDataChannel")}}. Sambungan ini dapat digunakan untuk informasi back-channel, metadatagamingfile transfer, bahkan sebagai jalur utama pertukaran data.

+ +

artikel ini memerlukan informasi yang lebih lanjut serta tautan untuk panduan dan tutorial yang relevan

+ +

WebRTC interfaces

+ +

Because WebRTC provides interfaces that work together to accomplish a variety of tasks, we have divided up the interfaces in the list below by category. Please see the sidebar for an alphabetical list.

+ +

Connection setup and management

+ +

These interfaces are used to set up, open, and manage WebRTC connections.

+ +
+
{{domxref("RTCPeerConnection")}}
+
Represents a WebRTC connection between the local computer and a remote peer. It is used to handle efficient streaming of data between the two peers.
+
{{domxref("RTCDataChannel")}}
+
Represents a bi-directional data channel between two peers of a connection.
+
{{domxref("RTCDataChannelEvent")}}
+
Represents events that occur while attaching a {{domxref("RTCDataChannel")}} to a {{domxref("RTCPeerConnection")}}. The only event sent with this interface is {{event("datachannel")}}.
+
{{domxref("RTCSessionDescription")}}
+
Represents the parameters of a session. Each RTCSessionDescription consists of a description type indicating which part of the offer/answer negotiation process it describes and of the SDP descriptor of the session.
+
{{domxref("RTCStatsReport")}}
+
Provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by calling {{domxref("RTCPeerConnection.getStats()")}}.
+
{{domxref("RTCIceCandidate")}}
+
Represents a candidate internet connectivity establishment (ICE) server for establishing an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCIceTransport")}}
+
Represents information about an internet connectivity establishment (ICE) transport.
+
{{domxref("RTCPeerConnectionIceEvent")}}
+
Represents events that occurs in relation to ICE candidates with the target, usually an {{domxref("RTCPeerConnection")}}. Only one event is of this type: {{event("icecandidate")}}.
+
{{domxref("RTCRtpSender")}}
+
Manages the encoding and transmission of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCRtpReceiver")}}
+
Manages the reception and decoding of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCTrackEvent")}}
+
Indicates that a new incoming {{domxref("MediaStreamTrack")}} was created and an associated {{domxref("RTCRtpReceiver")}} object was added to the {{domxref("RTCPeerConnection")}} object.
+
+ +

Identity and security

+ +

The WebRTC API includes a number of interfaces to manage security and identity.

+ +
+
{{domxref("RTCIdentityProvider")}}
+
Enables a user agent is able to request that an identity assertion be generated or validated.
+
{{domxref("RTCIdentityAssertion")}}
+
Represents the identity of the a remote peer of the current connection. If no peer has yet been set and verified this interface returns null. Once set it can't be changed.
+
{{domxref("RTCIdentityProviderRegistrar")}}
+
Registers an  identity provider (idP).
+
{{domxref("RTCIdentityEvent")}}
+
Represents an identity assertion generated by an identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. The only event sent with this type is {{event("identityresult")}}.
+
{{domxref("RTCIdentityErrorEvent")}}
+
Represents an error associated with the identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. Two events are sent with this type: {{event("idpassertionerror")}} and {{event("idpvalidationerror")}}.
+
{{domxref("RTCCertificate")}}
+
Represents a certificate that an {{domxref("RTCPeerConnection")}} uses to authenticate.
+
+ +

Telephony

+ +

These interfaces are related to interactivity with public-switched telephone networks (PTSNs).

+ +
+
{{domxref("RTCDTMFSender")}}
+
Manages the encoding and transmission of dual-tone multi-frequency (DTMF) signaling for an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCDTMFToneChangeEvent")}}
+
Indicates an occurrence of a of dual-tone multi-frequency (DTMF). This event does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated).
+
+ +

Guides

+ +
+
Introduction to WebRTC protocols
+
This article introduces the protocols on top of which the WebRTC API is built.
+
WebRTC connectivity
+
A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.
+
Lifetime of a WebRTC session
+
WebRTC lets you build peer-to-peer communication of arbitrary data, audio, or video—or any combination thereof—into a browser application. In this article, we'll look at the lifetime of a WebRTC session, from establishing the connection all the way through closing the connection when it's no longer needed.
+
Signaling and two-way video calling
+
A tutorial and example which turbs a WebSocket-based chat system created for a previous example and adds support for opening video calls among participants. The chat server's WebSocket connection is used for WebRTC signaling.
+
Using WebRTC data channels
+
This guide covers how you can use a peer connection and an associated {{domxref("RTCDataChannel")}} to exchange arbitrary data between two peers.
+
Using DTMF with WebRTC
+
WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the {{domxref("RTCDTMFSender")}} interface. This guide shows how to do so.
+
+ +

Tutorials

+ +
+
Improving compatibility using WebRTC adapter.js
+
The WebRTC organization provides on GitHub the WebRTC adapter to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.
+
Taking still photos with WebRTC
+
This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it.
+
A simple RTCDataChannel sample
+
The {{domxref("RTCDataChannel")}} interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the WebSocket API, so that the same programming model can be used for each.
+
+ +

Resources

+ +

Protocols

+ +

WebRTC-proper protocols

+ + + + + + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}The initial definition of the API of WebRTC.
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}}The initial definition of the object conveying the stream of media content.
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}}The initial definition on how to obtain stream of content from DOM Elements
+ +

In additions to these specifications defining the API needed to use WebRTC, there are several protocols, listed under resources.

+ + + + diff --git a/files/id/web/api/window/getselection/index.html b/files/id/web/api/window/getselection/index.html new file mode 100644 index 0000000000..274aa85b2d --- /dev/null +++ b/files/id/web/api/window/getselection/index.html @@ -0,0 +1,100 @@ +--- +title: Window.getSelection() +slug: Web/API/Window/getSelection +tags: + - API + - API Pilihan + - DOM + - Metode + - Pilihan + - Refrensi + - Window +translation_of: Web/API/Window/getSelection +--- +
{{ ApiRef() }}
+ +

Window.getSelection() adalah metode {{domxref("Selection")}} yang menggambarkan teks yang ditandai oleh pengguna atau posisi sekarang.

+ +

Syntak

+ +
selection = window.getSelection();
+ +

Hasil Output

+ +

Objek {{domxref("Selection")}}

+ +

Ketika berganti ke string, lebih baik menggunakan string kosong ("") atau menggunakan {{domxref("Selection.toString()")}}, hasil output adalah teks yang dipilih.

+ +

Ketika memanggil sebuah {{htmlelement("iframe")}} ini tidak akan ditampilkan (misalnya display: none telah diatur) Firefox akan menampilkan null, sedangkan browser lain akan menampilkan objek {{domxref("Selection")}} dengan {{domxref("Selection.type")}} yang diatur ke None.

+ +

Contoh

+ +
function foo() {
+    var selObj = window.getSelection();
+    alert(selObj);
+    var selRange = selObj.getRangeAt(0);
+    // do stuff with the range
+}
+ +

Catatan

+ +

Representasi dari objek Selection

+ +

Dalam JavaScript, ketika sebuah objek dimasukan ke function yang membutuhkan string (seperti {{ Domxref("window.alert()") }} atau {{ Domxref("document.write()") }}), objek metode {{jsxref("Object.toString", "toString()")}} akan dipanggil dan hasilnya akan dikembalikan ke function tersebut. Ini akan membuat objek dapat tampil sebagai string ketika digunakan oleh function lainnya ketika ini adalah objek dan metode yang benar.

+ +

Pada contoh berikut, selObj.toString() akan otomatis dipanggil ketika melewati {{domxref("window.alert()")}}. Bagaimanapun, mencoba menggunakan properti atau metode JavaScript String seperti length atau substr secara langsung pada objek {{domxref ("Selection")}} akan menghasilkan kesalahan jika tidak memiliki properti atau metode dan dapat mengembalikan hasil yang tidak terduga jika itu benar. Untuk menggunakan objek Selection sebagai string, panggil metode toString () secara langsung:

+ +
var selectedText = selObj.toString();
+ + + +

Objek terhubung

+ +

Kamu bisa memanggil {{domxref("Document.getSelection()")}}, yang mana ini bekerja seperti Window.getSelection().

+ +

Perlu diingat, bahwa saat ini getSelection() tidak bekerja pada elemen {{htmlelement("textarea")}} and {{htmlelement("input")}} di Firefox. Properti {{domxref("HTMLInputElement.setSelectionRange()")}} atau selectionStart dan selectionEnd yang dapat menangani hal ini.

+ +

Perhatikan juga perbedaan atara selection dan focus. {{domxref("Document.activeElement")}} menampilkan elemen yang sedang difokus.

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Selection API", "#extensions-to-window-interface", "Window.getSelection()")}}{{Spec2("Selection API")}}New spec.
{{SpecName("HTML Editing", "#dom-window-getselection", "Window.getSelection()")}}{{Spec2("HTML Editing")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Window.getSelection")}}

+ +

See also

+ + diff --git a/files/id/web/api/window/index.html b/files/id/web/api/window/index.html new file mode 100644 index 0000000000..79736ccf64 --- /dev/null +++ b/files/id/web/api/window/index.html @@ -0,0 +1,479 @@ +--- +title: Window +slug: Web/API/Window +tags: + - API + - DOM + - Interface + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - Window +translation_of: Web/API/Window +--- +

{{APIRef}}

+ +

The window object represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the {{Domxref("document.defaultView")}} property.

+ +

This section provides a brief reference for all of the methods, properties, and events available through the DOM window object. The window object implements the Window interface, which in turn inherits from the AbstractView interface. Some additional global functions, namespaces, objects, interfaces, and constructors, not typically associated with the window, but available on it, are listed in the JavaScript Reference and DOM Reference.

+ +

In a tabbed browser, such as Firefox, each tab contains its own window object (and if you're writing an extension, the browser window itself is a separate window too - see Working with windows in chrome code for more information). That is, the window object is not shared between tabs in the same window. Some methods, namely {{Domxref("window.resizeTo")}} and {{Domxref("window.resizeBy")}} apply to the whole window and not to the specific tab the window object belongs to. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.

+ +

{{InheritanceDiagram}}

+ +

Properties

+ +

This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from the {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("WindowEventHandlers")}} mixins.

+ +

Note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below.

+ +
+
{{domxref("Window.applicationCache")}}  {{readOnlyInline}} {{gecko_minversion_inline("1.9")}}
+
An {{domxref("OfflineResourceList")}} object providing access to the offline resources for the window.
+
{{domxref("Window.closed")}} {{Non-standard_inline}}{{readOnlyInline}}
+
This property indicates whether the current window is closed or not.
+
{{domxref("Window.console")}} {{ReadOnlyInline}}
+
Returns a reference to the console object which provides access to the browser's debugging console.
+
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}
+
Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore.
+
{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
Returns the XUL controller objects for the current chrome window.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
Returns the browser crypto object.
+
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
+
Gets/sets the status bar text for the given window.
+
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}}{{ReadOnlyInline}}
+
Returns the ratio between physical pixels and device independent pixels in the current display.
+
{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{ReadOnlyInline}}
+
Gets the arguments passed to the window (if it's a dialog box) at the time {{domxref("window.showModalDialog()")}} was called. This is an {{Interface("nsIArray")}}.
+
{{domxref("Window.directories")}} {{obsolete_inline}}
+
Synonym of {{domxref("window.personalbar")}}
+
{{domxref("Window.document")}} {{ReadOnlyInline}}
+
Returns a reference to the document that the window contains.
+
{{domxref("Window.frameElement")}} {{readOnlyInline}}
+
Returns the element in which the window is embedded, or null if the window is not embedded.
+
{{domxref("Window.frames")}} {{readOnlyInline}}
+
Returns an array of the subframes in the current window.
+
{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}
+
This property indicates whether the window is displayed in full screen or not.
+
{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}
+
Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.
+ Was: Multiple storage objects that are used for storing data across multiple pages.
+
{{domxref("Window.history")}} {{ReadOnlyInline}}
+
Returns a reference to the history object.
+
{{domxref("Window.innerHeight")}} {{readOnlyInline}}
+
Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
+
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
+
Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
+
{{domxref("Window.isSecureContext")}} {{readOnlyInline}}
+
Indicates whether a context is capable of using features that require secure contexts.
+
{{domxref("Window.length")}} {{readOnlyInline}}
+
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
+
{{domxref("Window.location")}}
+
Gets/sets the location, or current URL, of the window object.
+
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
+
Returns the locationbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}
+
Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
+
Returns the menubar object, whose visibility can be toggled in the window.
+
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
+
Returns the message manager object for this window.
+
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}}{{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}
+
The time in milliseconds since epoch at which the current animation cycle began.
+
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}}{{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
+
Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
+
Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozPaintCount")}} {{non-standard_inline}}{{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}
+
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.
+
{{domxref("Window.name")}}
+
Gets/sets the name of the window.
+
{{domxref("Window.navigator")}} {{readOnlyInline}}
+
Returns a reference to the navigator object.
+
{{domxref("Window.opener")}}
+
Returns a reference to the window that opened this current window.
+
{{domxref("Window.orientation")}}{{non-standard_inline}}{{deprecated_inline}}{{readOnlyInline}}
+
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.
+
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
+
Gets the height of the outside of the browser window.
+
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
+
Gets the width of the outside of the browser window.
+
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
+
An alias for {{domxref("window.scrollX")}}.
+
{{domxref("Window.scrollY","Window.pageYOffset")}}{{readOnlyInline}}
+
An alias for {{domxref("window.scrollY")}}
+
{{domxref("Window.sessionStorage")}} {{readOnlyInline}}
+
Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.parent")}} {{readOnlyInline}}
+
Returns a reference to the parent of the current window or subframe.
+
{{domxref("Window.performance")}} {{readOnlyInline}}
+
Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.
+
{{domxref("Window.personalbar")}} {{readOnlyInline}}
+
Returns the personalbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}
+
Formerly provided access to install and remove PKCS11 modules.
+
{{domxref("Window.returnValue")}} {{Fx_minversion_inline(3)}}
+
The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.
+
{{domxref("Window.screen")}} {{readOnlyInline}}
+
Returns a reference to the screen object associated with the window.
+ +
{{domxref("Window.screenX")}} {{readOnlyInline}}
+
Returns the horizontal distance of the left border of the user's browser from the left side of the screen.
+
{{domxref("Window.screenY")}} {{readOnlyInline}}
+
Returns the vertical distance of the top border of the user's browser from the top side of the screen.
+
{{domxref("Window.scrollbars")}} {{readOnlyInline}}
+
Returns the scrollbars object, whose visibility can be toggled in the window.
+
{{domxref("Window.scrollMaxX")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.
+
{{domxref("Window.scrollMaxY")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).
+
{{domxref("Window.scrollX")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled horizontally.
+
{{domxref("Window.scrollY")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled vertically.
+
{{domxref("Window.self")}} {{ReadOnlyInline}}
+
Returns an object reference to the window object itself.
+
{{domxref("Window.sessionStorage")}} {{Fx_minversion_inline("2.0")}}
+
Returns a storage object for storing data within a single page session.
+
{{domxref("Window.sidebar")}} {{non-standard_inline}}{{ReadOnlyInline}}
+
Returns a reference to the window object of the sidebar.
+
{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}
+
Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using Web Speech API speech synthesis functionality.
+
{{domxref("Window.status")}}
+
Gets/sets the text in the statusbar at the bottom of the browser.
+
{{domxref("Window.statusbar")}} {{readOnlyInline}}
+
Returns the statusbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.toolbar")}} {{readOnlyInline}}
+
Returns the toolbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.top")}} {{readOnlyInline}}
+
Returns a reference to the topmost window in the window hierarchy. This property is read only.
+
{{domxref("Window.visualViewport")}} {{readOnlyInline}}
+
Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.
+
{{domxref("Window.window")}} {{ReadOnlyInline}}
+
Returns a reference to the current window.
+
window[0], window[1], etc.
+
Returns a reference to the window object in the frames. See {{domxref("Window.frames")}} for more details.
+
+ +

Properties implemented from elsewhere

+ +
+
{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}
+
Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.
+
{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}
+
Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.
+
{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}
+
Returns a boolean indicating whether the current context is secure (true) or not (false).
+
{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}
+
Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)
+
+ +

Methods

+ +

This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("EventTarget")}}.

+ +
+
{{domxref("Window.alert()")}}
+
Displays an alert dialog.
+ +
{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Moves back one in the window history.
+
{{domxref("Window.blur()")}}
+
Sets focus away from the window.
+
{{domxref("Window.cancelAnimationFrame()")}} {{experimental_inline}}
+
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}.
+
{{domxref("Window.cancelIdleCallback()")}} {{experimental_inline}}
+
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}.
+
{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}
+
Registers the window to capture all events of the specified type.
+
{{domxref("Window.clearImmediate()")}}
+
Cancels the repeated execution set using setImmediate.
+
{{domxref("Window.close()")}}
+
Closes the current window.
+
{{domxref("Window.confirm()")}}
+
Displays a dialog with a message that the user needs to respond to.
+
{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.dispatchEvent()")}}
+
Used to trigger an event.
+
{{domxref("Window.dump()")}} {{Non-standard_inline}}
+
Writes a message to the console.
+
{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.find()")}}
+
Searches for a given string in a window.
+
{{domxref("Window.focus()")}}
+
Sets focus on the current window.
+
{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Moves the window one document forward in the history.
+
{{domxref("Window.getAttention()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Flashes the application icon.
+
{{domxref("Window.getAttentionWithCycleCount()")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.getComputedStyle()")}}
+
Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.
+
{{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_inline}}
+
Gets default computed style for the specified element, ignoring author stylesheets.
+
{{domxref("Window.getSelection()")}}
+
Returns the selection object representing the selected item(s).
+
{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Returns the browser to the home page.
+
{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}
+
Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.
+
{{domxref("Window.maximize()")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.minimize()")}} (top-level XUL windows only)
+
Minimizes the window.
+
{{domxref("Window.moveBy()")}}
+
Moves the current window by a specified amount.
+
{{domxref("Window.moveTo()")}}
+
Moves the window to the specified coordinates.
+
{{domxref("Window.open()")}}
+
Opens a new window.
+
{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Opens a new dialog window.
+
{{domxref("Window.postMessage()")}} {{Fx_minversion_inline(3)}}
+
Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.
+
{{domxref("Window.print()")}}
+
Opens the Print Dialog to print the current document.
+
{{domxref("Window.prompt()")}}
+
Returns the text entered by the user in a prompt dialog.
+
{{domxref("Window.releaseEvents()")}} {{Non-standard_inline}} {{Deprecated_inline}}
+
Releases the window from trapping events of a specific type.
+
{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}
+
Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.
+
{{domxref("Window.requestIdleCallback()")}}  {{experimental_inline}}
+
Enables the scheduling of tasks during a browser's idle periods.
+
{{domxref("Window.resizeBy()")}}
+
Resizes the current window by a certain amount.
+
{{domxref("Window.resizeTo()")}}
+
Dynamically resizes window.
+
{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.scroll()")}}
+
Scrolls the window to a particular place in the document.
+
{{domxref("Window.scrollBy()")}}
+
Scrolls the document in the window by the given amount.
+
{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}
+
Scrolls the document by the given number of lines.
+
{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}
+
Scrolls the current document by the specified number of pages.
+
{{domxref("Window.scrollTo()")}}
+
Scrolls to a particular set of coordinates in the document.
+
{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)
+
Changes the cursor for the current window
+
{{domxref("Window.setImmediate()")}}
+
Executes a function after the browser has finished other heavy tasks
+
{{domxref("Window.setResizable()")}} {{Non-standard_inline}}
+
Toggles a user's ability to resize a window.
+
{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}
+
Sizes the window according to its content.
+
{{domxref("Window.stop()")}}
+
This method stops window loading.
+
{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}
+
Updates the state of commands of the current chrome window (UI).
+
+ +

Methods implemented from elsewhere

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
Register an event handler to a specific event type on the window.
+
{{domxref("WindowOrWorkerGlobalScope.atob()")}}
+
Decodes a string of data which has been encoded using base-64 encoding.
+
{{domxref("WindowOrWorkerGlobalScope.btoa()")}}
+
Creates a base-64 encoded ASCII string from a string of binary data.
+
{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
+
Cancels the repeated execution set using {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.
+
{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}
+
Cancels the delayed execution set using {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.
+
{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}
+
Accepts a variety of different image sources, and returns a {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh.
+
{{domxref("WindowOrWorkerGlobalScope.fetch()")}}
+
Starts the process of fetching a resource from the network.
+
{{domxref("EventTarget.removeEventListener")}}
+
Removes an event listener from the window.
+
{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
+
Schedules a function to execute every time a given number of milliseconds elapses.
+
{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
+
Schedules a function to execute in a given amount of time.
+
+ +

Obsolete methods

+ +
+
{{domxref("Window.showModalDialog()")}} {{obsolete_inline}}
+
Displays a modal dialog. This method was removed completely in Chrome 43, and Firefox 55.
+
+ +

Event handlers

+ +

These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.

+ +

This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowEventHandlers")}}.

+ +
+

Note: Starting in {{Gecko("9.0")}}, you can now use the syntax if ("onabort" in window) to determine whether or not a given event handler property exists. This is because event handler interfaces have been updated to be proper web IDL interfaces. See DOM event handlers for details.

+
+ +
+
{{domxref("GlobalEventHandlers.onabort")}}
+
Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress
+
{{domxref("WindowEventHandlers.onafterprint")}}
+
Called when the print dialog box is closed. See {{event("afterprint")}} event.
+
{{domxref("WindowEventHandlers.onbeforeprint")}}
+
Called when the print dialog box is opened. See {{event("beforeprint")}} event.
+
{{domxref("Window.onbeforeinstallprompt")}}
+
An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
An event handler property for before-unload events on the window.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
Called after the window loses focus, such as due to a popup.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
An event handler property for change events on the window.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Called after the ANY mouse button is pressed & released
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Called when a double click is made with ANY mouse button.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Called after the window is closed
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Called when the RIGHT mouse button is pressed
+
{{domxref("Window.ondevicelight")}}
+
An event handler property for any ambient light levels changes
+
{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}
+
Called if accelerometer detects a change (For mobile devices)
+
{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}
+
Called when the orientation is changed (For mobile devices)
+
{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only
+
An event handler property for any device orientation changes.
+
{{domxref("Window.ondeviceproximity")}}
+
An event handler property for device proximity event
+
{{domxref("GlobalEventHandlers.onerror")}}
+
Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Called after the window receives or regains focus. See {{event("focus")}} events.
+
{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}
+
An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.
+
{{domxref("Window.onappinstalled")}}
+
Called when the page is installed as a webapp. See {{event('appinstalled')}} event.
+
{{domxref("Window.ongamepadconnected")}}
+
Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).
+
{{domxref("Window.ongamepaddisconnected")}}
+
Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).
+
{{domxref("Window.oninput")}}
+
Called when the value of an <input> element changes
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
Called when you begin pressing ANY key. See {{event("keydown")}} event.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
Called when you finish releasing ANY key. See {{event("keyup")}} event.
+
{{domxref("WindowEventHandlers.onlanguagechange")}}
+
An event handler property for {{event("languagechange")}} events on the window.
+
{{domxref("GlobalEventHandlers.onload")}}
+
Called after all resources and the DOM are fully loaded. WILL NOT get called when the page is loaded from cache, such as with back button.
+
{{domxref("WindowEventHandlers.onmessage")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
Called when ANY mouse button is pressed.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
Called continously when the mouse is moved inside the window.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
Called when the pointer leaves the window.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
Called when the pointer enters the window
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
Called when ANY mouse button is released
+
{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}
+
An event handler property for the MozBeforePaint event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.
+
{{domxref("WindowEventHandlers.onoffline")}}
+
Called when network connection is lost. See {{event("offline")}} event.
+
{{domxref("WindowEventHandlers.ononline")}}
+
Called when network connection is established. See {{event("online")}} event.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.
+
{{domxref("WindowEventHandlers.onpageshow")}}
+
Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.
+
{{domxref("Window.onpaint")}}
+
An event handler property for paint events on the window.
+
{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
+
Called when a back putton is pressed.
+
{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}
+
An event handler for handled {{jsxref("Promise")}} rejection events.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
Called when a form is reset
+
{{domxref("GlobalEventHandlers.onresize")}}
+
Called continuously as you are resizing the window.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked
+
{{domxref("GlobalEventHandlers.onwheel")}}
+
Called when the mouse wheel is rotated around any axis
+
{{domxref("GlobalEventHandlers.onselect")}}
+
Called after text in an input field is selected
+
{{domxref("GlobalEventHandlers.onselectionchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{domxref("WindowEventHandlers.onstorage")}}
+
Called when there is a change in session storage or local storage. See {{event("storage")}} event
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
Called when a form is submitted
+
{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}
+
An event handler for unhandled {{jsxref("Promise")}} rejection events.
+
{{domxref("WindowEventHandlers.onunload")}}
+
Called when the user navigates away from the page.
+
{{domxref("Window.onuserproximity")}}
+
An event handler property for user proximity events.
+
{{domxref("Window.onvrdisplayconnect")}}
+
Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).
+
{{domxref("Window.onvrdisplaydisconnect")}}
+
Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).
+
{{domxref("Window.onvrdisplayactivate")}}
+
Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
+
{{domxref("Window.onvrdisplaydeactivate")}}
+
Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
+
{{domxref("Window.onvrdisplayblur")}}
+
Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
+
{{domxref("Window.onvrdisplayfocus")}}
+
Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).
+
{{domxref("Window.onvrdisplaypresentchange")}}
+
represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).
+
+ +

Constructors

+ +

See also the DOM Interfaces.

+ +
+
{{domxref("DOMParser")}}
+
DOMParser can parse XML or HTML source stored in a string into a DOM DocumentDOMParser is specified in DOM Parsing and Serialization.
+
{{domxref("Window.GeckoActiveXObject")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Image")}}
+
Used for creating an {{domxref("HTMLImageElement")}}.
+
{{domxref("Option")}}
+
Used for creating an {{domxref("HTMLOptionElement")}}
+
{{domxref("Window.QueryInterface")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XMLSerializer")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Worker")}}
+
Used for creating a Web worker
+
{{domxref("Window.XPCNativeWrapper")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XPCSafeJSObjectWrapper")}}
+
{{todo("NeedsContents")}}
+
+ +

Interfaces

+ +

See DOM Reference

+ +

See also

+ + diff --git a/files/id/web/api/window/window/index.html b/files/id/web/api/window/window/index.html new file mode 100644 index 0000000000..a40d33059f --- /dev/null +++ b/files/id/web/api/window/window/index.html @@ -0,0 +1,63 @@ +--- +title: Window.window +slug: Web/API/Window/window +translation_of: Web/API/Window/window +--- +
{{APIRef}}
+ +

Summary

+ +

Properti window dalam obyek window mengarah pada obyek window itu sendiri. Jadi ekspresi berikut mengembalikan obyek window yang sama:

+ +
window.window
+window.window.window
+window.window.window.window
+  ...
+
+ +

Pada halaman web, obyek window merupakan obyek global. Ini berarti:

+ +
    +
  1. variabel global pada skrip adalah properti dari window: + +
    var global = {data: 0};
    +alert(global === window.global); // displays "true"
    +
    +
  2. +
  3. kamu dapat mengakses properti bawaan dari window tanpa perlu menulis prefix window.: +
    setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout.
    +alert(window === window.window); // displays "true"
    +
    +
  4. +
+ +

Tujuan adanya properti window yang mengarah pada obyek itu sendiri adalah mempermudah dalam mengarah pada obyek global. Jika tidak, kamu harus melakukannya secara manual var window = this; dibagian awal skrip.

+ +

Alasan lain, ada beberapa hal yang tidak dapat kamu tulis, contohnya, "{{domxref("window.open","window.open('http://google.com/')")}}". kamu harus menulis "open('http://google.com/')".

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-window', 'Window.window')}}{{Spec2('HTML WHATWG')}}No difference from the latest snapshot {{SpecName("HTML5.1")}}
{{SpecName('HTML5.1', 'browsers.html#dom-window', 'Window.window')}}{{Spec2('HTML5.1')}}No difference from the {{SpecName("HTML5 W3C")}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-window', 'Window.window')}}{{Spec2('HTML5 W3C')}}First snapshot containing the definition of Window.window.
diff --git a/files/id/web/api/xmlhttprequest/index.html b/files/id/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..87f02b9550 --- /dev/null +++ b/files/id/web/api/xmlhttprequest/index.html @@ -0,0 +1,200 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - API + - Communication + - HTTP + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web + - XHR + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest +--- +
{{DefaultAPISidebar("XMLHttpRequest")}}
+ +

Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in {{Glossary("AJAX")}} programming.

+ +

{{InheritanceDiagram(650, 150)}}

+ +

Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML.

+ +

If your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the {{domxref("EventSource")}} interface. For full-duplex communication, WebSockets may be a better choice.

+ +

Constructor

+ +
+
{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}
+
The constructor initializes an XMLHttpRequest. It must be called before any other method calls.
+
+ +

Properties

+ +

This interface also inherits properties of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}.

+ +
+
{{domxref("XMLHttpRequest.onreadystatechange")}}
+
An {{domxref("EventHandler")}} that is called whenever the readyState attribute changes.
+
{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}
+
Returns an unsigned short, the state of the request.
+
{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}
+
Returns an {{jsxref("ArrayBuffer")}}, {{domxref("Blob")}}, {{domxref("Document")}}, JavaScript object, or a {{domxref("DOMString")}}, depending on the value of {{domxref("XMLHttpRequest.responseType")}}, that contains the response entity body.
+
{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}
+
Returns a {{domxref("DOMString")}} that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.
+
{{domxref("XMLHttpRequest.responseType")}}
+
Is an enumerated value that defines the response type.
+
{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}
+
Returns the serialized URL of the response or the empty string if the URL is null.
+
{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}
+
Returns a {{domxref("Document")}} containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.
+
{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}
+
Returns an unsigned short with the status of the response of the request.
+
{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}
+
Returns a {{domxref("DOMString")}} containing the response string returned by the HTTP server. Unlike {{domxref("XMLHttpRequest.status")}}, this includes the entire text of the response message ("200 OK", for example).
+
+ +
+

Note: According to the HTTP/2 specification (8.1.2.4 Response Pseudo-Header Fields), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.

+
+ +
+
{{domxref("XMLHttpRequest.timeout")}}
+
Is an unsigned long representing the number of milliseconds a request can take before automatically being terminated.
+
{{domxref("XMLHttpRequestEventTarget.ontimeout")}}
+
Is an {{domxref("EventHandler")}} that is called whenever the request times out. {{gecko_minversion_inline("12.0")}}
+
{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}
+
Is an {{domxref("XMLHttpRequestUpload")}}, representing the upload process.
+
{{domxref("XMLHttpRequest.withCredentials")}}
+
Is a {{domxref("Boolean")}} that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers.
+
+ +

Non-standard properties

+ +
+
{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}
+
Is a {{Interface("nsIChannel")}}. The channel used by the object when performing the request.
+
{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}
+
Is a boolean. If true, the request will be sent without cookie and authentication headers.
+
{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}
+
Is a boolean. If true, the same origin policy will not be enforced on the request.
+
{{domxref("XMLHttpRequest.mozBackgroundRequest")}}
+
Is a boolean. It indicates whether or not the object represents a background service request.
+
{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}
+
{{jsxref("ArrayBuffer")}}. The response to the request, as a JavaScript typed array.
+
{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}
+
This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or responseText from progress events instead.
+
+ +

Event handlers

+ +

onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers.

+ +

Since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.). See Using XMLHttpRequest.

+ +

More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard {{domxref("EventTarget.addEventListener", "addEventListener()")}} APIs in addition to setting on* properties to a handler function.

+ +

Methods

+ +
+
{{domxref("XMLHttpRequest.abort()")}}
+
Aborts the request if it has already been sent.
+
{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}
+
Returns all the response headers, separated by {{Glossary("CRLF")}}, as a string, or null if no response has been received.
+
{{domxref("XMLHttpRequest.getResponseHeader()")}}
+
Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.
+
{{domxref("XMLHttpRequest.open()")}}
+
Initializes a request.
+
{{domxref("XMLHttpRequest.overrideMimeType()")}}
+
Overrides the MIME type returned by the server.
+
{{domxref("XMLHttpRequest.send()")}}
+
Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.
+
{{domxref("XMLHttpRequest.setRequestHeader()")}}
+
Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send().
+
+ +

Non-standard methods

+ +
+
{{domxref("XMLHttpRequest.init()")}}
+
Initializes the object for use from C++ code.
+
+ +
Warning: This method must not be called from JavaScript.
+ +
+
{{domxref("XMLHttpRequest.openRequest()")}}
+
Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use open() instead. See the documentation for open().
+
{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}
+
A variant of the send() method that sends binary data.
+
+ +

Events

+ +
+
{{domxref("XMLHttpRequest/abort_event", "abort")}}
+
Fired when a request has been aborted, for example because the program called {{domxref("XMLHttpRequest.abort()")}}.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onabort", "onabort")}} property.
+
{{domxref("XMLHttpRequest/error_event", "error")}}
+
Fired when the request encountered an error.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onerror", "onerror")}} property.
+
{{domxref("XMLHttpRequest/load_event", "load")}}
+
Fired when an {{domxref("XMLHttpRequest")}} transaction completes successfully.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onload", "onload")}} property.
+
{{domxref("XMLHttpRequest/loadend_event", "loadend")}}
+
Fired when a request has completed, whether successfully (after {{domxref("XMLHttpRequest/load_event", "load")}}) or unsuccessfully (after {{domxref("XMLHttpRequest/abort_event", "abort")}} or {{domxref("XMLHttpRequest/error_event", "error")}}).
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onloadend", "onloadend")}} property.
+
{{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}
+
Fired when a request has started to load data.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onloadstart", "onloadstart")}} property.
+
{{domxref("XMLHttpRequest/progress_event", "progress")}}
+
Fired periodically when a request receives more data.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/onprogress", "onprogress")}} property.
+
{{domxref("XMLHttpRequest/timeout_event", "timeout")}}
+
Fired when progress is terminated due to preset time expiring.
+ Also available via the {{domxref("XMLHttpRequestEventTarget/ontimeout", "ontimeout")}} property.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

Browser compatibility

+ + + +
{{Compat("api.XMLHttpRequest")}}
+ +

See also

+ + diff --git a/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html new file mode 100644 index 0000000000..1de088b719 --- /dev/null +++ b/files/id/web/api/xmlhttprequest/using_xmlhttprequest/index.html @@ -0,0 +1,793 @@ +--- +title: Using XMLHttpRequest +slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +
{{APIRef("XMLHttpRequest")}}
+ +
Dalam panduan ini, kita akan melihat bagaimana cara untuk mengunakan {{domxref("XMLHttpRequest")}}  untuk menyelesaikan permasalahan HTTP request yang dalam penggunaan untuk pertukaran data antara halaman web dan server. Contoh umum dan kasus penggunaan lebih jelas untuk XMLHttpRequest disertakan.
+ +
+ +
Untuk mengirim HTTP request,  buatlah sebuah object XMLHttpRequest , buka sebuah URL dan kirim request tersebut. setelah transaksi selesai, objek akan berisi informasi yang berguna seperti badan respon dan status HTTP dari hasilnya.
+ +
+ +
function reqListener () {
+  console.log(this.responseText);
+}
+
+var oReq = new XMLHttpRequest();
+oReq.addEventListener("load", reqListener);
+oReq.open("GET", "http://www.example.org/example.txt");
+oReq.send();
+ +

Tipe-Tipe dari Request

+ +

Sebuh request yang dihasilkan melalui XMLHttpRequest dapat mengambil data dari salah satu cara, asynchronously or synchronously. Tipe dari request ditentukan onleh opsi async argument (argument ke-tiga) yang telah diset dialam metode {{domxref("XMLHttpRequest.open()")}}. Jika argument tersebut true atau tidak ditentukan. XMLHttpRequest akan diproses secara asynchronous,jika tidak proses akan berjalan secara synchronous. Diskusi detail dan demonstrasi dari kedua cara merequest tersebut dapat ditemukan pada halaman synchronous and asynchronous requests. Jangan gunakan permintaan synchronous di luar Pekerja Web.

+ +
Note: Dimulai dari Gecko 30.0 {{ geckoRelease("30.0") }}, permintaan synchronous pada utas utama telah ditinggalkan karena efek negatif terhadap pengalaman pengguna.
+ +
Note: fungsi konstruksi XMLHttpRequest tidak terbatas hanya pada dokumen XML. Itu dimulai dengan "XML" karena ketika itu dibuat format utama yang awalnya digunakan untuk Asynchronous Data Exchange adalah XML
+ +

Menangani Respons

+ +

Ada beberapa jenis atribut respons  ditentukan oleh spesifikasi standar untuk {domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}} constructor. Ini memberi tahu klien membuat informasi penting XMLHttpRequest tentang status respons. Beberapa kasus di mana berurusan dengan jenis respons non-teks mungkin melibatkan beberapa manipulasi dan analisis diuraikan dalam bagian berikut.

+ +

Menganalisa dan Memanipulasi Properti responseXML

+ +

Jika kamu mengunakan XMLHttpRequest  untuk mendapatkan konten dokumen XML jarak jauh, properti {{domxref("XMLHttpRequest.responseXML", "responseXML")}}  akan menjadi objek DOM yang berisi dokumen XML parsing. Ini terbentuk sulit untuk dimanipulasi dan dianalisis. Ada empat cara utama untuk menganalisis dokumen XML ini:

+ +
    +
  1. Menggunakan XPath untuk mengatasi (atau menunjuk ke) bagian-bagiannya.
  2. +
  3. Secara manual Parsing dan men-serialisasikan XML ke string atau objek
  4. +
  5. Menggunakan {{domxref("XMLSerializer")}} untuk meng-serialisasi Pohon DOM ke strings atau ke file.
  6. +
  7. {{jsxref("RegExp")}} bisa digunakan jika kamu selalu tau konten dari XML document sebelumnya. Kamu mungkin ingin menghapus jeda baris, jika Anda menggunakan RegEx untuk memindai berkenaan dengan jeda baris. Namun, metode ini adalah "pilihan terakhir" karena jika kode XML sedikit berubah, metode ini kemungkinan akan gagal.
  8. +
+ +
+

Note: XMLHttpRequest sekarang dapat menafsirkan HTML untuk Anda menggunakan properti {{domxref("XMLHttpRequest.responseXML", "responseXML")}}. Baca artikel HTML dalam XMLHttpRequest untuk mempelajari cara untuk melakukannya.

+
+ +

Memproses sebuah Properti responseText yang Berisi HTML Dokument

+ +

Jika kamu mengunakan XMLHttpRequest untuk mendapatkan konten dari halaman web HTML jarak jauh. Properti {{domxref("XMLHttpRequest.responseText", "responseText")}} adalah sebuah string yang berisi data HTML mentah. Hal ini terbukti sulit untuk dimanipulasi dan dianalisi. Karenanya ada tiga cara utama untuk

+ +

If you use XMLHttpRequest to get the content of a remote HTML webpage, the {{domxref("XMLHttpRequest.responseText", "responseText")}} property is a string containing the raw HTML. This could prove difficult to manipulate and analyze. Ada tiga cara utama untuk menganalisis dan mengurai string HTML mentah ini:

+ +
    +
  1. Use the XMLHttpRequest.responseXML property as covered in the article HTML in XMLHttpRequest.
  2. +
  3. Inject the content into the body of a document fragment via fragment.body.innerHTML and traverse the DOM of the fragment.
  4. +
  5. {{jsxref("RegExp")}} can be used if you always know the content of the HTML responseText beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to linebreaks. However, this method is a "last resort" since if the HTML code changes slightly, the method will likely fail.
  6. +
+ +

Handling binary data

+ +

Although {{domxref("XMLHttpRequest")}} is most commonly used to send and receive textual data, it can be used to send and receive binary content. There are several well tested methods for coercing the response of an XMLHttpRequest into sending binary data. These involve utilizing the {{domxref("XMLHttpRequest.overrideMimeType", "overrideMimeType()")}} method on the XMLHttpRequest object and is a workable solution.

+ +
var oReq = new XMLHttpRequest();
+oReq.open("GET", url);
+// retrieve data unprocessed as a binary string
+oReq.overrideMimeType("text/plain; charset=x-user-defined");
+/* ... */
+
+ +

However, more modern techniques are available, since the {{domxref("XMLHttpRequest.responseType", "responseType")}} attribute now supports a number of additional content types, which makes sending and receiving binary data much easier.

+ +

For example, consider this snippet, which uses the responseType of "arraybuffer" to fetch the remote content into a {{jsxref("ArrayBuffer")}} object, which stores the raw binary data.

+ +
var oReq = new XMLHttpRequest();
+
+oReq.onload = function(e) {
+  var arraybuffer = oReq.response; // not responseText
+  /* ... */
+}
+oReq.open("GET", url);
+oReq.responseType = "arraybuffer";
+oReq.send();
+ +

For more examples check out the Sending and Receiving Binary Data page

+ +

Monitoring progress

+ +

XMLHttpRequest provides the ability to listen to various events that can occur while the request is being processed. This includes periodic progress notifications, error notifications, and so forth.

+ +

Support for DOM {{event("progress")}} event monitoring of XMLHttpRequest transfers follows the specification for progress events: these events implement the {{domxref("ProgressEvent")}} interface. The actual events you can monitor to determine the state of an ongoing transfer are:

+ +
+
{{event("progress")}}
+
The amount of data that has been retrieved has changed.
+
{{event("load")}}
+
The transfer is complete; all data is now in the response
+
+ +
var oReq = new XMLHttpRequest();
+
+oReq.addEventListener("progress", updateProgress);
+oReq.addEventListener("load", transferComplete);
+oReq.addEventListener("error", transferFailed);
+oReq.addEventListener("abort", transferCanceled);
+
+oReq.open();
+
+// ...
+
+// progress on transfers from the server to the client (downloads)
+function updateProgress (oEvent) {
+  if (oEvent.lengthComputable) {
+    var percentComplete = oEvent.loaded / oEvent.total * 100;
+    // ...
+  } else {
+    // Unable to compute progress information since the total size is unknown
+  }
+}
+
+function transferComplete(evt) {
+  console.log("The transfer is complete.");
+}
+
+function transferFailed(evt) {
+  console.log("An error occurred while transferring the file.");
+}
+
+function transferCanceled(evt) {
+  console.log("The transfer has been canceled by the user.");
+}
+ +

Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using XMLHttpRequest.

+ +
Note: You need to add the event listeners before calling open() on the request. Otherwise the progress events will not fire.
+ +

The progress event handler, specified by the updateProgress() function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's total and loaded fields. However, if the lengthComputable field is false, the total length is not known and will be zero.

+ +

Progress events exist for both download and upload transfers. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object, as shown below:

+ +
var oReq = new XMLHttpRequest();
+
+oReq.upload.addEventListener("progress", updateProgress);
+oReq.upload.addEventListener("load", transferComplete);
+oReq.upload.addEventListener("error", transferFailed);
+oReq.upload.addEventListener("abort", transferCanceled);
+
+oReq.open();
+
+ +
Note: Progress events are not available for the file: protocol.
+ +
+

Note: Starting in {{Gecko("9.0")}}, progress events can now be relied upon to come in for every chunk of data received, including the last chunk in cases in which the last packet is received and the connection closed before the progress event is fired. In this case, the progress event is automatically fired when the load event occurs for that packet. This lets you now reliably monitor progress by only watching the "progress" event.

+
+ +
+

Note: As of {{Gecko("12.0")}}, if your progress event is called with a responseType of "moz-blob", the value of response is a {{domxref("Blob")}} containing the data received so far.

+
+ +

One can also detect all three load-ending conditions (abort, load, or error) using the loadend event:

+ +
req.addEventListener("loadend", loadEnd);
+
+function loadEnd(e) {
+  console.log("The transfer finished (although we don't know if it succeeded or not).");
+}
+
+ +

Note there is no way to be certain, from the information received by the loadend event, as to which condition caused the operation to terminate; however, you can use this to handle tasks that need to be performed in all end-of-transfer scenarios.

+ +

Submitting forms and uploading files

+ +

Instances of XMLHttpRequest can be used to submit forms in two ways:

+ + + +

Using the FormData API is the simplest and fastest, but has the disadvantage that data collected can not be stringified.
+ Using only AJAX is more complex, but typically more flexible and powerful.

+ +

Using nothing but XMLHttpRequest

+ +

Submitting forms without the FormData API does not require other APIs for most use cases. The only case where you need an additional API is if you want to upload one or more files, where you use the {{domxref("FileReader")}} API.

+ +

A brief introduction to the submit methods

+ +

An html {{ HTMLElement("form") }} can be sent in four ways:

+ + + +

Now, consider the submission of a form containing only two fields, named foo and baz. If you are using the POST method the server will receive a string similar to one of the following three examples, depending on the encoding type you are using:

+ + + +

However, if you are using the GET method, a string like the following will be simply added to the URL:

+ +
?foo=bar&baz=The%20first%20line.%0AThe%20second%20line.
+ +

A little vanilla framework

+ +

All these effects are done automatically by the web browser whenever you submit a {{HTMLElement("form")}}. If you want to perform the same effects using JavaScript you have to instruct the interpreter about everything. Therefore, how to send forms in pure AJAX is too complex to be explained here in detail. For this reason, here we place a complete (yet didactic) framework, able to use all four ways to submit, and to upload files:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Sending forms with pure AJAX &ndash; MDN</title>
+<script type="text/javascript">
+
+"use strict";
+
+/*\
+|*|
+|*|  :: XMLHttpRequest.prototype.sendAsBinary() Polyfill ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
+\*/
+
+if (!XMLHttpRequest.prototype.sendAsBinary) {
+  XMLHttpRequest.prototype.sendAsBinary = function(sData) {
+    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
+    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
+      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
+    }
+    /* send as ArrayBufferView...: */
+    this.send(ui8Data);
+    /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
+  };
+}
+
+/*\
+|*|
+|*|  :: AJAX Form Submit Framework ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
+|*|
+|*|  This framework is released under the GNU Public License, version 3 or later.
+|*|  https://www.gnu.org/licenses/gpl-3.0-standalone.html
+|*|
+|*|  Syntax:
+|*|
+|*|   AJAXSubmit(HTMLFormElement);
+\*/
+
+var AJAXSubmit = (function () {
+
+  function ajaxSuccess () {
+    /* console.log("AJAXSubmit - Success!"); */
+    console.log(this.responseText);
+    /* you can get the serialized data through the "submittedData" custom property: */
+    /* console.log(JSON.stringify(this.submittedData)); */
+  }
+
+  function submitData (oData) {
+    /* the AJAX request... */
+    var oAjaxReq = new XMLHttpRequest();
+    oAjaxReq.submittedData = oData;
+    oAjaxReq.onload = ajaxSuccess;
+    if (oData.technique === 0) {
+      /* method is GET */
+      oAjaxReq.open("get", oData.receiver.replace(/(?:\?.*)?$/,
+          oData.segments.length > 0 ? "?" + oData.segments.join("&") : ""), true);
+      oAjaxReq.send(null);
+    } else {
+      /* method is POST */
+      oAjaxReq.open("post", oData.receiver, true);
+      if (oData.technique === 3) {
+        /* enctype is multipart/form-data */
+        var sBoundary = "---------------------------" + Date.now().toString(16);
+        oAjaxReq.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
+        oAjaxReq.sendAsBinary("--" + sBoundary + "\r\n" +
+            oData.segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n");
+      } else {
+        /* enctype is application/x-www-form-urlencoded or text/plain */
+        oAjaxReq.setRequestHeader("Content-Type", oData.contentType);
+        oAjaxReq.send(oData.segments.join(oData.technique === 2 ? "\r\n" : "&"));
+      }
+    }
+  }
+
+  function processStatus (oData) {
+    if (oData.status > 0) { return; }
+    /* the form is now totally serialized! do something before sending it to the server... */
+    /* doSomething(oData); */
+    /* console.log("AJAXSubmit - The form is now serialized. Submitting..."); */
+    submitData (oData);
+  }
+
+  function pushSegment (oFREvt) {
+    this.owner.segments[this.segmentIdx] += oFREvt.target.result + "\r\n";
+    this.owner.status--;
+    processStatus(this.owner);
+  }
+
+  function plainEscape (sText) {
+    /* How should I treat a text/plain form encoding?
+       What characters are not allowed? this is what I suppose...: */
+    /* "4\3\7 - Einstein said E=mc2" ----> "4\\3\\7\ -\ Einstein\ said\ E\=mc2" */
+    return sText.replace(/[\s\=\\]/g, "\\$&");
+  }
+
+  function SubmitRequest (oTarget) {
+    var nFile, sFieldType, oField, oSegmReq, oFile, bIsPost = oTarget.method.toLowerCase() === "post";
+    /* console.log("AJAXSubmit - Serializing form..."); */
+    this.contentType = bIsPost && oTarget.enctype ? oTarget.enctype : "application\/x-www-form-urlencoded";
+    this.technique = bIsPost ?
+        this.contentType === "multipart\/form-data" ? 3 : this.contentType === "text\/plain" ? 2 : 1 : 0;
+    this.receiver = oTarget.action;
+    this.status = 0;
+    this.segments = [];
+    var fFilter = this.technique === 2 ? plainEscape : escape;
+    for (var nItem = 0; nItem < oTarget.elements.length; nItem++) {
+      oField = oTarget.elements[nItem];
+      if (!oField.hasAttribute("name")) { continue; }
+      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
+      if (sFieldType === "FILE" && oField.files.length > 0) {
+        if (this.technique === 3) {
+          /* enctype is multipart/form-data */
+          for (nFile = 0; nFile < oField.files.length; nFile++) {
+            oFile = oField.files[nFile];
+            oSegmReq = new FileReader();
+            /* (custom properties:) */
+            oSegmReq.segmentIdx = this.segments.length;
+            oSegmReq.owner = this;
+            /* (end of custom properties) */
+            oSegmReq.onload = pushSegment;
+            this.segments.push("Content-Disposition: form-data; name=\"" +
+                oField.name + "\"; filename=\"" + oFile.name +
+                "\"\r\nContent-Type: " + oFile.type + "\r\n\r\n");
+            this.status++;
+            oSegmReq.readAsBinaryString(oFile);
+          }
+        } else {
+          /* enctype is application/x-www-form-urlencoded or text/plain or
+             method is GET: files will not be sent! */
+          for (nFile = 0; nFile < oField.files.length;
+              this.segments.push(fFilter(oField.name) + "=" + fFilter(oField.files[nFile++].name)));
+        }
+      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
+        /* NOTE: this will submit _all_ submit buttons. Detecting the correct one is non-trivial. */
+        /* field type is not FILE or is FILE but is empty */
+        this.segments.push(
+          this.technique === 3 ? /* enctype is multipart/form-data */
+            "Content-Disposition: form-data; name=\"" + oField.name + "\"\r\n\r\n" + oField.value + "\r\n"
+          : /* enctype is application/x-www-form-urlencoded or text/plain or method is GET */
+            fFilter(oField.name) + "=" + fFilter(oField.value)
+        );
+      }
+    }
+    processStatus(this);
+  }
+
+  return function (oFormElement) {
+    if (!oFormElement.action) { return; }
+    new SubmitRequest(oFormElement);
+  };
+
+})();
+
+</script>
+</head>
+<body>
+
+<h1>Sending forms with pure AJAX</h1>
+
+<h2>Using the GET method</h2>
+
+<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h2>Using the POST method</h2>
+<h3>Enctype: application/x-www-form-urlencoded (default)</h3>
+
+<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: text/plain</h3>
+
+<form action="register.php" method="post" enctype="text/plain"
+    onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      Your name: <input type="text" name="user" />
+    </p>
+    <p>
+      Your message:<br />
+      <textarea name="message" cols="40" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: multipart/form-data</h3>
+
+<form action="register.php" method="post" enctype="multipart/form-data"
+    onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Upload example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" /><br />
+      Sex:
+      <input id="sex_male" type="radio" name="sex" value="male" />
+      <label for="sex_male">Male</label>
+      <input id="sex_female" type="radio" name="sex" value="female" />
+      <label for="sex_female">Female</label><br />
+      Password: <input type="password" name="secret" /><br />
+      What do you prefer:
+      <select name="image_type">
+        <option>Books</option>
+        <option>Cinema</option>
+        <option>TV</option>
+      </select>
+    </p>
+    <p>
+      Post your photos:
+      <input type="file" multiple name="photos[]">
+    </p>
+    <p>
+      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" />
+      <label for="vehicle_bike">I have a bike</label><br />
+      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" />
+      <label for="vehicle_car">I have a car</label>
+    </p>
+    <p>
+      Describe yourself:<br />
+      <textarea name="description" cols="50" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+</body>
+</html>
+
+ +

To test this, create a page named register.php (which is the action attribute of these sample forms), and put the following minimalistic content:

+ +
<?php
+/* register.php */
+
+header("Content-type: text/plain");
+
+/*
+NOTE: You should never use `print_r()` in production scripts, or
+otherwise output client-submitted data without sanitizing it first.
+Failing to sanitize can lead to cross-site scripting vulnerabilities.
+*/
+
+echo ":: data received via GET ::\n\n";
+print_r($_GET);
+
+echo "\n\n:: Data received via POST ::\n\n";
+print_r($_POST);
+
+echo "\n\n:: Data received as \"raw\" (text/plain encoding) ::\n\n";
+if (isset($HTTP_RAW_POST_DATA)) { echo $HTTP_RAW_POST_DATA; }
+
+echo "\n\n:: Files received ::\n\n";
+print_r($_FILES);
+
+
+ +

The syntax to activate this script is simply:

+ +
AJAXSubmit(myForm);
+ +
Note: This framework uses the {{domxref("FileReader")}} API to transmit file uploads. This is a recent API and is not implemented in IE9 or below. For this reason, the AJAX-only upload is considered an experimental technique. If you do not need to upload binary files, this framework works fine in most browsers.
+ +
Note: The best way to send binary content is via {{jsxref("ArrayBuffer", "ArrayBuffers")}} or {{domxref("Blob", "Blobs")}} in conjuncton with the {{domxref("XMLHttpRequest.send()", "send()")}} method and possibly the {{domxref("FileReader.readAsArrayBuffer()", "readAsArrayBuffer()")}} method of the FileReader API. But, since the aim of this script is to work with a stringifiable raw data, we used the {{domxref("XMLHttpRequest.sendAsBinary()", "sendAsBinary()")}} method in conjunction with the {{domxref("FileReader.readAsBinaryString()", "readAsBinaryString()")}} method of the FileReader API. As such, the above script makes sense only when you are dealing with small files. If you do not intend to upload binary content, consider instead using the FormData API.
+ +
Note: The non-standard sendAsBinary method is considered deprecated as of Gecko 31 {{geckoRelease(31)}} and will be removed soon. The standard send(Blob data) method can be used instead.
+ +

Using FormData objects

+ +

The {{domxref("XMLHttpRequest.FormData", "FormData")}} constructor lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primary use is in sending form data, but can also be used independently from a form in order to transmit user keyed data. The transmitted data is in the same format the form's submit() method uses to send data, if the form's encoding type were set to "multipart/form-data". FormData objects can be utilized in a number of ways with an XMLHttpRequest. For examples, and explanations of how one can utilize FormData with XMLHttpRequests, see the Using FormData Objects page. For didactic purposes here is a translation of the previous example transformed to use the FormData API. Note the brevity of the code:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" charset="UTF-8" />
+<title>Sending forms with FormData &ndash; MDN</title>
+<script>
+"use strict";
+
+function ajaxSuccess () {
+  console.log(this.responseText);
+}
+
+function AJAXSubmit (oFormElement) {
+  if (!oFormElement.action) { return; }
+  var oReq = new XMLHttpRequest();
+  oReq.onload = ajaxSuccess;
+  if (oFormElement.method.toLowerCase() === "post") {
+    oReq.open("post", oFormElement.action);
+    oReq.send(new FormData(oFormElement));
+  } else {
+    var oField, sFieldType, nFile, sSearch = "";
+    for (var nItem = 0; nItem < oFormElement.elements.length; nItem++) {
+      oField = oFormElement.elements[nItem];
+      if (!oField.hasAttribute("name")) { continue; }
+      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ?
+          oField.getAttribute("type").toUpperCase() : "TEXT";
+      if (sFieldType === "FILE") {
+        for (nFile = 0; nFile < oField.files.length;
+            sSearch += "&" + escape(oField.name) + "=" + escape(oField.files[nFile++].name));
+      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
+        sSearch += "&" + escape(oField.name) + "=" + escape(oField.value);
+      }
+    }
+    oReq.open("get", oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&/, "?")), true);
+    oReq.send(null);
+  }
+}
+</script>
+</head>
+<body>
+
+<h1>Sending forms with FormData</h1>
+
+<h2>Using the GET method</h2>
+
+<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h2>Using the POST method</h2>
+<h3>Enctype: application/x-www-form-urlencoded (default)</h3>
+
+<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: text/plain</h3>
+
+<p>The text/plain encoding is not supported by the FormData API.</p>
+
+<h3>Enctype: multipart/form-data</h3>
+
+<form action="register.php" method="post" enctype="multipart/form-data"
+    onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Upload example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" /><br />
+      Sex:
+      <input id="sex_male" type="radio" name="sex" value="male" />
+      <label for="sex_male">Male</label>
+      <input id="sex_female" type="radio" name="sex" value="female" />
+      <label for="sex_female">Female</label><br />
+      Password: <input type="password" name="secret" /><br />
+      What do you prefer:
+      <select name="image_type">
+        <option>Books</option>
+        <option>Cinema</option>
+        <option>TV</option>
+      </select>
+    </p>
+    <p>
+      Post your photos:
+      <input type="file" multiple name="photos[]">
+    </p>
+    <p>
+      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" />
+      <label for="vehicle_bike">I have a bike</label><br />
+      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" />
+      <label for="vehicle_car">I have a car</label>
+    </p>
+    <p>
+      Describe yourself:<br />
+      <textarea name="description" cols="50" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+</body>
+</html>
+
+ +
Note: As we said, {{domxref("FormData")}} objects are not stringifiable objects. If you want to stringify a submitted data, use the previous pure-AJAX example. Note also that, although in this example there are some file {{ HTMLElement("input") }} fields, when you submit a form through the FormData API you do not need to use the {{domxref("FileReader")}} API also: files are automatically loaded and uploaded.
+ +

Get last modified date

+ +
function getHeaderTime () {
+  console.log(this.getResponseHeader("Last-Modified"));  /* A valid GMTString date or null */
+}
+
+var oReq = new XMLHttpRequest();
+oReq.open("HEAD" /* use HEAD if you only need the headers! */, "yourpage.html");
+oReq.onload = getHeaderTime;
+oReq.send();
+ +

Do something when last modified date changes

+ +

Let's create two functions:

+ +
function getHeaderTime () {
+  var nLastVisit = parseFloat(window.localStorage.getItem('lm_' + this.filepath));
+  var nLastModif = Date.parse(this.getResponseHeader("Last-Modified"));
+
+  if (isNaN(nLastVisit) || nLastModif > nLastVisit) {
+    window.localStorage.setItem('lm_' + this.filepath, Date.now());
+    isFinite(nLastVisit) && this.callback(nLastModif, nLastVisit);
+  }
+}
+
+function ifHasChanged(sURL, fCallback) {
+  var oReq = new XMLHttpRequest();
+  oReq.open("HEAD" /* use HEAD - we only need the headers! */, sURL);
+  oReq.callback = fCallback;
+  oReq.filepath = sURL;
+  oReq.onload = getHeaderTime;
+  oReq.send();
+}
+ +

And to test:

+ +
/* Let's test the file "yourpage.html"... */
+
+ifHasChanged("yourpage.html", function (nModif, nVisit) {
+  console.log("The page '" + this.filepath + "' has been changed on " + (new Date(nModif)).toLocaleString() + "!");
+});
+ +

If you want to know if the current page has changed, please read the article about {{domxref("document.lastModified")}}.

+ +

Cross-site XMLHttpRequest

+ +

Modern browsers support cross-site requests by implementing the Cross-Origin Resource Sharing (CORS) standard. As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work. Otherwise, an INVALID_ACCESS_ERR exception is thrown.

+ +

Bypassing the cache

+ +

A cross-browser compatible approach to bypassing the cache is appending a timestamp to the URL, being sure to include a "?" or "&" as appropriate. For example:

+ +
http://foo.com/bar.html -> http://foo.com/bar.html?12345
+http://foo.com/bar.html?foobar=baz -> http://foo.com/bar.html?foobar=baz&12345
+
+ +

As the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.

+ +

You can automatically adjust URLs using the following code:

+ +
var oReq = new XMLHttpRequest();
+
+oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime());
+oReq.send(null);
+ +

Security

+ +

{{fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference capability.policy.<policyname>.XMLHttpRequest.open</policyname> to allAccess to give specific sites cross-site access. This is no longer supported.")}}

+ +

{{fx_minversion_note(5, "Versions of Firefox prior to Firefox 5 could use netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\"); to request cross-site access. This is no longer supported, even though it produces no warning and permission dialog is still presented.")}}

+ +

The recommended way to enable cross-site scripting is to use the Access-Control-Allow-Origin HTTP header in the response to the XMLHttpRequest.

+ +

XMLHttpRequests being stopped

+ +

If you conclude with an XMLHttpRequest receiving status=0 and statusText=null, this means the request was not allowed to be performed. It was UNSENT. A likely cause for this is when the XMLHttpRequest origin (at the creation of the XMLHttpRequest) has changed when the XMLHttpRequest is subsequently open(). This case can happen, for example, when one has an XMLHttpRequest that gets fired on an onunload event for a window, the expected XMLHttpRequest is created when the window to be closed is still there, and finally sending the request (in otherwords, open()) when this window has lost its focus and another window gains focus. The most effective way to avoid this problem is to set a listener on the new window's {{event("activate")}} event which is set once the terminated window has its {{event("unload")}} event triggered.

+ +

Workers

+ +

Setting overrideMimeType does not work from a {{domxref("Worker")}}.  See {{bug(678057)}} for more details.  Other browsers may handle this differently.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ +
    +
  1. MDN AJAX introduction
  2. +
  3. HTML in XMLHttpRequest
  4. +
  5. HTTP access control
  6. +
  7. How to check the security state of an XMLHTTPRequest over SSL
  8. +
  9. XMLHttpRequest - REST and the Rich User Experience
  10. +
  11. Microsoft documentation
  12. +
  13. "Using the XMLHttpRequest Object" (jibbering.com)
  14. +
  15. The XMLHttpRequest object: WHATWG specification
  16. +
diff --git a/files/id/web/css/@font-face/font-display/index.html b/files/id/web/css/@font-face/font-display/index.html new file mode 100644 index 0000000000..50fed7426a --- /dev/null +++ b/files/id/web/css/@font-face/font-display/index.html @@ -0,0 +1,101 @@ +--- +title: font-display +slug: Web/CSS/@font-face/font-display +translation_of: Web/CSS/@font-face/font-display +--- +
{{CSSRef}}
+ +

The font-display descriptor determines how a font face is displayed based on whether and when it is downloaded and ready to use.

+ +

The font display timeline

+ +

The font display timeline is based on a timer that begins the moment the user agent attempts to use a given downloaded font face. The timeline is divided into the three periods below which dictate the rendering behavior of any elements using the font face.

+ +
+
Font block period
+
If the font face is not loaded, any element attempting to use it must render an invisible fallback font face. If the font face successfully loads during this period, it is used normally.
+
Font swap period
+
If the font face is not loaded, any element attempting to use it must render a fallback font face. If the font face successfully loads during this period, it is used normally.
+
Font failure period
+
If the font face is not loaded, the user agent treats it as a failed load causing normal font fallback.
+
+ +

{{cssinfo}}

+ +

Syntax

+ +
/* Keyword values */
+font-display: auto;
+font-display: block;
+font-display: swap;
+font-display: fallback;
+font-display: optional;
+ +

Values

+ +
+
auto
+
The font display strategy is defined by the user agent.
+
block
+
Gives the font face a short block period and an infinite swap period.
+
swap
+
Gives the font face an extremely small block period and an infinite swap period.
+
fallback
+
Gives the font face an extremely small block period and a short swap period.
+
optional
+
Gives the font face an extremely small block period and no swap period.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +
@font-face {
+  font-family: ExampleFont;
+  src: url(/path/to/fonts/examplefont.woff) format('woff'),
+       url(/path/to/fonts/examplefont.eot) format('eot');
+  font-weight: 400;
+  font-style: normal;
+  font-display: fallback;
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Fonts', '#font-display-desc', 'font-display')}}{{Spec2('CSS4 Fonts')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.at-rules.font-face.font-display")}}

+ +

See also

+ + diff --git a/files/id/web/css/@font-face/index.html b/files/id/web/css/@font-face/index.html new file mode 100644 index 0000000000..940386b922 --- /dev/null +++ b/files/id/web/css/@font-face/index.html @@ -0,0 +1,199 @@ +--- +title: '@font-face' +slug: Web/CSS/@font-face +tags: + - '@font-face' + - At-rule + - CSS + - CSS Fonts + - Fonts + - NeedsTranslation + - Reference + - TopicStub + - typography +translation_of: Web/CSS/@font-face +--- +
{{CSSRef}}
+ +

The @font-face CSS at-rule specifies a custom font with which to display text; the font can be loaded from either a remote server or a locally-installed font on the user's own computer. If the local() function is provided, specifying a font name to look for on the user's computer, and the {{Glossary("user agent")}} finds a match, that local font is used. Otherwise, the font resource specified using the url() function is downloaded and used.

+ +

By allowing authors to provide their own fonts, @font-face makes it possible to design content without being limited to the so-called "web-safe" fonts (that is, the fonts which are so common that they're considered to be universally available). The ability to specify the name of a locally-installed font to look for and use makes it possible to customize the font beyond the basics while making it possible to do so without relying on an Internet connection.

+ +

It's common to use both url() and local() together, so that the user's installed copy of the font is used if available, falling back to downloading a copy of the font if it's not found on the user's device.

+ +

The @font-face at-rule may be used not only at the top level of a CSS, but also inside any CSS conditional-group at-rule.

+ +
@font-face {
+  font-family: "Open Sans";
+  src: url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2"),
+       url("/fonts/OpenSans-Regular-webfont.woff") format("woff");
+}
+ +

Syntax

+ +

Descriptors

+ +
+
{{cssxref("@font-face/font-display", "font-display")}}
+
Determines how a font face is displayed based on whether and when it is downloaded and ready to use.
+
{{cssxref("@font-face/font-family", "font-family")}}
+
Specifies a name that will be used as the font face value for font properties.
+
{{cssxref("@font-face/font-stretch", "font-stretch")}}
+
A {{cssxref("font-stretch")}} value. Since Firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-stretch: 50% 200%;
+
{{cssxref("@font-face/font-style", "font-style")}}
+
A {{cssxref("font-style")}} value. Since Firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-style: oblique 20deg 50deg;
+
{{cssxref("@font-face/font-weight", "font-weight")}}
+
A {{cssxref("font-weight")}} value. Since Firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-weight: 100 400;
+
{{cssxref("@font-face/font-variant", "font-variant")}}
+
A {{cssxref("font-variant")}} value.
+
{{cssxref("font-feature-settings", "font-feature-settings")}}
+
Allows control over advanced typographic features in OpenType fonts.
+
{{cssxref("@font-face/font-variation-settings", "font-variation-settings")}}
+
Allows low-level control over OpenType or TrueType font variations, by specifying the four letter axis names of the features to vary, along with their variation values.
+
{{cssxref("@font-face/src", "src")}}
+
+

Specifies the resource containing the font data. This can be a URL to a remote font file location or the name of a font on the user's computer.

+ +

To provide the browser with a hint as to what format a font resource is — so it can select a suitable one — it is possible to include a format type inside a format() function:

+ +
src: url(ideal-sans-serif.woff) format("woff"),
+     url(basic-sans-serif.ttf) format("truetype");
+ +

The available types are: "woff", "woff2", "truetype", "opentype", "embedded-opentype", and "svg".

+
+
{{cssxref("@font-face/unicode-range", "unicode-range")}}
+
The range of Unicode code points to be used from the font.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

This example simply specifies a downloadable font to use, applying it to the entire body of the document:

+ +

View the live example

+ +
<html>
+<head>
+  <title>Web Font Sample</title>
+  <style type="text/css" media="screen, print">
+    @font-face {
+      font-family: "Bitstream Vera Serif Bold";
+      src: url("https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf");
+    }
+
+    body { font-family: "Bitstream Vera Serif Bold", serif }
+  </style>
+</head>
+<body>
+  This is Bitstream Vera Serif Bold.
+</body>
+</html>
+
+ +

In this example, the user's local copy of "Helvetica Neue Bold" is used; if the user does not have that font installed (two different names are tried), then the downloadable font named "MgOpenModernaBold.ttf" is used instead:

+ +
@font-face {
+  font-family: MyHelvetica;
+  src: local("Helvetica Neue Bold"),
+       local("HelveticaNeue-Bold"),
+       url(MgOpenModernaBold.ttf);
+  font-weight: bold;
+}
+
+ +

Font MIME Types

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
FormatMIME type
TrueTypefont/ttf
OpenTypefont/otf
Web Open Font Formatfont/woff
Web Open Font Format 2font/woff2
+ +

Notes

+ + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WOFF2.0', '', 'WOFF2 font format')}}{{Spec2('WOFF2.0')}}Font format specification with new compression algorithm
{{SpecName('WOFF1.0', '', 'WOFF font format')}}{{Spec2('WOFF1.0')}}Font format specification
{{SpecName('CSS3 Fonts', '#font-face-rule', '@font-face')}}{{Spec2('CSS3 Fonts')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.at-rules.font-face")}}

+ +

See also

+ + diff --git a/files/id/web/css/_colon_active/index.html b/files/id/web/css/_colon_active/index.html new file mode 100644 index 0000000000..67d9357bef --- /dev/null +++ b/files/id/web/css/_colon_active/index.html @@ -0,0 +1,143 @@ +--- +title: ':active' +slug: 'Web/CSS/:active' +translation_of: 'Web/CSS/:active' +--- +
{{CSSRef}}
+ +

Rangkuman

+ +

:active CSS pseudo-class menunjukkan kapan sebuah elemen telah diaktifasi oleh pengguna. Hal ini memperbolehkan halaman memberikan feedback (korelasi) sehingga aktivasi telah terdeteksi oleh browser. Ketika berinteraksi dengan mouse, hal ini secara tipikal waktu antara pengguna menekan tombol mouse dan merelasisasikannya.  :active pseudo-class juga secara tipical ditampilkan ketika menggunakan tombol tab pada keyboard. Hal ini sering digunakan pada element HTML {{HTMLElement("a")}} dan {{HTMLElement("button")}}, tetapi boleh jadi tidak terbatas pada hal tersebut.

+ +

Style ini boleh jadi digunakan lebih oleh sebuah link-related pseudo-classes (tautan-terhubung dengan pseudo kelas) lainnya, yang mana merupakan {{cssxref(":link")}}, {{cssxref(":hover")}}, and {{cssxref(":visited")}}, ditampilkan dalam aturan bagian-bagiannya. Dalam memperoleh penampilan yang teraprofiasi dengan link, kamu membutuhkan menempatkan aturan :active setelah seluruh yang lainnya terhubungan dengan aturan link (link-related-rules), seperti diuraikan oleh LHVA-order:  :link — :visited — :hover — :active.

+ +
Cataan: Pada system dengan multi tombol mouse, CSS 3 spesifik bahwa :active pseudo-class harus hanya diterapkan pada tombol utama; pada klik kanan mouse, ini secara tipikal kebanyakan pada tombol kiri.
+ +

Contoh

+ +
+

HTML

+ +
<body>
+    <h1>:active CSS selector example</h1>
+    <p>The following link will turn lime during the time you click it and release the click: <a href="#">Mozilla Developer Network</a>.</p>
+</body>
+ +

CSS

+ +
body { background-color: #ffffc9 }
+a:link { color: blue } /* unvisited links */
+a:visited { color: purple } /* visited links */
+a:hover { font-weight: bold } /* user hovers */
+a:active { color: lime } /* active links */
+
+ +
{{EmbedLiveSample('example',600,140)}}
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#active-pseudo', ':active')}}{{Spec2('CSS4 Selectors')}}No change.
{{SpecName('CSS3 Selectors', '#useraction-pseudos', ':active')}}{{Spec2('CSS3 Selectors')}}No change.
{{SpecName('CSS2.1', 'selector.html#dynamic-pseudo-classes', ':active')}}{{Spec2('CSS2.1')}}No change.
{{SpecName('CSS1', '#anchor-pseudo-classes', ':active')}}{{Spec2('CSS1')}}Initial definition.
+ +

Dukungan Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}4.05.01.0
Support on non-<a> elements1.0{{CompatGeckoDesktop("1.0")}}8.07.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile("1.0")}}6.06.01.0
Support on non-<a> elements1.0{{CompatGeckoMobile("1.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} [1]
+
+ +

[1] Secara menyeluruh, Safari Mobile tidak menggunakan {{cssxref(":active")}} kesatuan yang tidak ada pada sebuah touchstart event handler pada elemen yang relevan atau pada {{HTMLElement("body")}}.

+ +

Lihat juga

+ + diff --git a/files/id/web/css/background-color/index.html b/files/id/web/css/background-color/index.html new file mode 100644 index 0000000000..920b4d28e5 --- /dev/null +++ b/files/id/web/css/background-color/index.html @@ -0,0 +1,149 @@ +--- +title: background-color +slug: Web/CSS/background-color +translation_of: Web/CSS/background-color +--- +
{{CSSRef}}
+ +

Background-color CSS digunakan untuk seting warna latar belakang dari element yang di inginkan.

+ +
{{EmbedInteractiveExample("pages/css/background-color.html")}}
+ + + +

Syntax

+ +
/* Keyword values */
+background-color: red;
+background-color: indigo;
+
+/* Hexadecimal value */
+background-color: #bbff00;    /* Fully opaque */
+background-color: #11ffee00;  /* Fully transparent */
+background-color: #11ffeeff;  /* Fully opaque */
+
+/* RGB value */
+background-color: rgb(255, 255, 128);        /* Fully opaque */
+background-color: rgba(117, 190, 218, 0.5);  /* 50% transparent */
+
+/* HSL value */
+background-color: hsl(50, 33%, 25%);         /* Fully opaque */
+background-color: hsla(50, 33%, 25%, 0.75);  /* 75% transparent */
+
+/* Special keyword values */
+background-color: currentcolor;
+background-color: transparent;
+
+/* Global values */
+background-color: inherit;
+background-color: initial;
+background-color: unset;
+ +

Background-color menggunakan hanya satu jenis warna <color> nilai.

+ +

Values

+ +
+
{{cssxref("<color>")}}
+
The uniform color of the background. It is rendered behind any {{cssxref("background-image")}} that is specified, although the color will still be visible through any transparency in the image.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Contoh

+ +

HTML

+ +
<div class="exampleone">
+  Lorem ipsum dolor sit amet, consectetuer
+</div>
+
+<div class="exampletwo">
+  Lorem ipsum dolor sit amet, consectetuer
+</div>
+
+<div class="examplethree">
+  Lorem ipsum dolor sit amet, consectetuer
+</div>
+ +

CSS

+ +
.exampleone {
+  background-color: teal;
+  color: white;
+}
+
+.exampletwo {
+  background-color: rgb(153,102,153);
+  color: rgb(255,255,204);
+}
+
+.examplethree {
+  background-color: #777799;
+  color: #FFFFFF;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("Examples", 200, 150)}}

+ +

Accessibility concerns

+ +

It is important to ensure that the contrast ratio between the background color and the color of the text placed over it is high enough that people experiencing low vision conditions will be able to read the content of the page.

+ +

Color contrast ratio is determined by comparing the luminosity of the text and background color values. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. Large text is defined as 18.66px and bold or larger, or 24px or larger.

+ + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#background-color', 'background-color')}}{{Spec2('CSS3 Backgrounds')}}Though technically removing the transparent keyword, this doesn't change anything as it has been incorporated as a true {{cssxref("<color>")}}
{{SpecName('CSS2.1', 'colors.html#propdef-background-color', 'background-color')}}{{Spec2('CSS2.1')}}No change
{{SpecName('CSS1', '#background-color', 'background-color')}}{{Spec2('CSS1')}}Initial definition
+ +
{{cssinfo}}
+ +

Browser compatibility

+ + + +

{{Compat("css.properties.background-color")}}

+ +

See also

+ + diff --git a/files/id/web/css/css_box_model/index.html b/files/id/web/css/css_box_model/index.html new file mode 100644 index 0000000000..08152c9c16 --- /dev/null +++ b/files/id/web/css/css_box_model/index.html @@ -0,0 +1,115 @@ +--- +title: CSS Basic Box Model +slug: Web/CSS/CSS_Box_Model +tags: + - CSS + - CSS Box Model + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/CSS/CSS_Box_Model +--- +
{{CSSRef}}
+ +

CSS Basic Box Model is a module of CSS that defines the rectangular boxes—including their padding and margin—that are generated for elements and laid out according to the visual formatting model.

+ +

Reference

+ +

Properties

+ +

Properties controlling the flow of content in a box

+ +
+ +
+ +

Properties controlling the size of a box

+ +
+ +
+ +

Properties controlling the margins of a box

+ +
+ +
+ +

Properties controlling the paddings of a box

+ +
+ +
+ +

Other properties

+ +
+ +
+ +

Guides

+ +
+
Introduction to the CSS box model
+
Explains one of the fundamental concept of CSS: the box model. This model defines how CSS lays out elements, including their content, padding, border, and margin areas.
+
Mastering margin collapsing
+
Sometimes, two adjacent margins are collapsed into one. This article describes the rules that govern when and why this happens, and how to control it.
+
Visual formatting model
+
Explains the visual formatting model.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Box")}}{{Spec2("CSS3 Box")}}Added margin-trim
{{SpecName("CSS2.1", "box.html")}}{{Spec2("CSS2.1")}} 
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Initial definition.
diff --git a/files/id/web/css/css_box_model/introduction_to_the_css_box_model/index.html b/files/id/web/css/css_box_model/introduction_to_the_css_box_model/index.html new file mode 100644 index 0000000000..d81bae36e6 --- /dev/null +++ b/files/id/web/css/css_box_model/introduction_to_the_css_box_model/index.html @@ -0,0 +1,73 @@ +--- +title: Introduction to the CSS basic box model +slug: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model +translation_of: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model +--- +
{{CSSRef}}
+ +

When laying out a document, the browser's rendering engine represents each element as a rectangular box according to the standard CSS basic box model. CSS determines the size, position, and properties (color, background, border size, etc.) of these boxes.

+ +

Every box is composed of four parts (or areas), defined by their respective edges: the content edge, padding edge, border edge, and margin edge.

+ +

CSS Box model

+ +

The content area, bounded by the content edge, contains the "real" content of the element, such as text, an image, or a video player. Its dimensions are the content width (or content-box width) and the content height (or content-box height). It often has a background color or background image.

+ +

If the {{cssxref("box-sizing")}} property is set to content-box (default) and if the element is a block element, the content area's size can be explicitly defined with the {{cssxref("width")}}, {{cssxref("min-width")}}, {{cssxref("max-width")}}, {{ cssxref("height") }}, {{cssxref("min-height")}}, and {{cssxref("max-height")}} properties.

+ +

The padding area, bounded by the padding edge, extends the content area to include the element's padding. Its dimensions are the padding-box width and the padding-box height.

+ +

The thickness of the padding is determined by the {{cssxref("padding-top")}}, {{cssxref("padding-right")}}, {{cssxref("padding-bottom")}}, {{cssxref("padding-left")}}, and shorthand {{cssxref("padding")}} properties.

+ +

The border area, bounded by the border edge, extends the padding area to include the element's borders. Its dimensions are the border-box width and the border-box height.

+ +

The thickness of the borders are determined by the {{cssxref("border-width")}} and shorthand {{cssxref("border")}} properties. If the {{cssxref("box-sizing")}} property is set to border-box, the border area's size can be explicitly defined with the {{cssxref("width")}}, {{cssxref("min-width")}}, {{cssxref("max-width")}}, {{ cssxref("height") }}, {{cssxref("min-height")}}, and {{cssxref("max-height")}} properties. When there is a background ({{cssxref("background-color")}} or {{cssxref("background-image")}}) set on a box, it extends to the outer edge of the border (i.e. extends underneath the border in z-ordering). This default behavior can be altered with the {{cssxref("background-clip")}} css property.

+ +

The margin area, bounded by the margin edge, extends the border area to include an empty area used to separate the element from its neighbors. Its dimensions are the margin-box width and the margin-box height.

+ +

The size of the margin area is determined by the {{cssxref("margin-top")}}, {{cssxref("margin-right")}}, {{cssxref("margin-bottom")}}, {{cssxref("margin-left")}}, and shorthand {{cssxref("margin")}} properties. When margin collapsing occurs, the margin area is not clearly defined since margins are shared between boxes.

+ +

Finally, note that for non-replaced inline elements, the amount of space taken up (the contribution to the height of the line) is determined by the {{cssxref('line-height')}} property, even though the borders and padding are still displayed around the content.

+ +

See also

+ + + +

Specification

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Box', '#intro')}}{{Spec2('CSS3 Box')}}
{{ SpecName("CSS2.1","box.html#box-dimensions")}}{{ Spec2('CSS2.1') }}Though more precisely worded, there is no practical change.
{{ SpecName("CSS1","#formatting-model")}}{{ Spec2('CSS1') }}Initial definition.
+ +

See also

+ + diff --git a/files/id/web/css/css_selectors/index.html b/files/id/web/css/css_selectors/index.html new file mode 100644 index 0000000000..8bf3fb0034 --- /dev/null +++ b/files/id/web/css/css_selectors/index.html @@ -0,0 +1,154 @@ +--- +title: CSS Selectors +slug: Web/CSS/CSS_Selectors +tags: + - CSS + - CSS Selectors + - NeedsTranslation + - Overview + - Reference + - Selectors + - TopicStub +translation_of: Web/CSS/CSS_Selectors +--- +
{{CSSRef}}
+ +

Selectors define to which elements a set of CSS rules apply.

+ +

Dasar Selektor

+ +
+
Type selectors (Jenis-Jenis Seleksi)
+
Dasar selektor ini memilih seluruh elemen sehingga ditampilkan dengan pemberian nama.
+ Syntax: eltname
+ Example: Input akan menampilkan sebuah elemen  {{HTMLElement('input')}}.
+
Class selectors (Selektor Class)
+
Dasar selektor ini memilih elemen yang didasarkan pada nilai attribut classnya.
+ Syntax: .classname
+ Example: .index akan menampilkan sebuah elemen yang mempunyai indeks class (seperti didefenisikan oleh sebuah attribut class="index" atau yang serupa).
+
ID selectors (selektor ID)
+
Dasar selektor ini memilih cabangan (nodes) didasarkan pada nilai attribut idnya. Bisa jadi hanya satu elemen dengan sebuah pemberian ID dalam sebuah dokumen.
+ Syntax: #idname
+ Example: #toc akan menampilkan elemen yang mempunyai id toc (seperti didefenisikan dengan atrribut id="toc" atau yang serupa).
+
Universal selectors (selektor seluruhnya)
+
Dasar selektor ini memilih seluruh nodes (cabangan). Ini juga ada dalam hanya sebuah satu-kumpulan nama (namespace) dan  dalam seluruh kumpulan nama (all-namespace) yang juga bervariasi.
+ Syntax: * ns|* *|*
+ Example: * akan menampilkan seluruh elemen dari dokumen.
+
Attribute selectors (selektor attribut)
+
Dasar selektor ini memilih nodes (cabangan)  didasarkan pada sebuah nilai dari atributnya.
+ Syntax: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value]
+ Example: [autoplay] akan menampilkan seluruh elemen yang mempunyai attribut autoplay pengaturan (pada sebuah nilai).
+
+ +

Combinators

+ +
+
Adjacent sibling selectors
+
The '+' combinator selects nodes that immediately follow the former specified element.
+ Syntax: A + B
+ Example: ul + li will match any {{HTMLElement('li')}} that immediately follows a {{HTMLElement('ul')}}.
+
General sibling selectors
+
The '~' combinator selects nodes that follow (not necessarily immediately) the former specified element, if both elements shared the same parent.
+ Syntax: A ~ B
+ Example: p ~ span will match all {{HTMLElement('span')}} elements that follow a {{HTMLElement('p')}} element inside the same element.
+
Child selectors
+
The '>' combinator selects nodes that are direct children of the former specified element.
+ Syntax: A > B
+ Example: ul > li will match all {{HTMLElement('li')}} elements that are inside a {{HTMLElement('ul')}} element.
+
Descendant selectors
+
The ' ' combinator selects nodes that are children (not necessary direct children) of the former specified element.
+ Syntax: A B
+ Example: div span will match any {{HTMLElement('span')}} element that is inside a {{HTMLElement('div')}} element.
+
+ +

Pseudo-elements

+ +

Pseudo-elements are abstractions of the tree representing entities beyond what HTML does. For example, HTML doesn't have an element describing the first letter or line of a paragraph, or the marker of a list. Pseudo-elements represent these entities and allow CSS rules to be associated with them. that way, these entitities can be styled independently.

+ +

Pseudo-classes

+ +

Pseudo-classes allow to select elements based on information that is not contained in the document tree like a state or that is particularly complex to extract. E.g. they match if a link has been previously visited or not.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors')}}{{Spec2('CSS4 Selectors')}} 
{{SpecName('CSS3 Selectors')}}{{Spec2('CSS3 Selectors')}} 
{{SpecName('CSS2.1', 'selector.html')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1')}}{{Spec2('CSS1')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatGeckoDesktop("1")}}3.03.51.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.5{{CompatGeckoMobile("1.9.2")}}{{CompatUnknown}}{{CompatUnknown}}3.2
+
diff --git a/files/id/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html b/files/id/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html new file mode 100644 index 0000000000..9ec7339a95 --- /dev/null +++ b/files/id/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html @@ -0,0 +1,64 @@ +--- +title: 'Using the :target pseudo-class in selectors' +slug: 'Web/CSS/CSS_Selectors/Using_the_:target_pseudo-class_in_selectors' +translation_of: 'Web/CSS/CSS_Selectors/Using_the_:target_pseudo-class_in_selectors' +--- +

When a URL points at a specific piece of a document, it can be difficult to ascertain. Find out how you can use some simple CSS to draw attention to the target of a URL and improve the user's experience. {{CSSRef}}

+ +

Membantu mengidentifikasi tujuan dari sebuah tautan yang ditujukan pada sebuan bagian khusus sebuah dokumen, CSS3 Selectors mengenalkan {{ Cssxref(":target") }} pseudo-class.

+ +

Penentuan Sebuah Target

+ +

pseudo-class {{ Cssxref(":target") }} digunakan pada menampilkan target elemen dari sebuah URI berisikan sebuah pengidentifikasi menurut bagian bagian. Sebagai contoh, pada URI http://developer.mozilla.org/en/docs/Using_the_:target_selector#Example berisi bagian bagian pengidentifikasi #Example. Dalam HTML, pengidentifikasi ditemukan sebagai nilai dari masing masing id atau nama attribut, sejak keduanya membagi namespace (kelompok id atau nama) yang sama. Dengan begitu, contoh URI akan menunjukkan kop "Example" dalam dokumen ini.  

+ +

Misalkan kamu berharap untuk menampilkan sebuah elemen h2 yang merupakan target sebuah URI, tetapi tidak menginginkan sesuatu jenis dari elemen lainnya untuk menemukan sebuah target tampilan. Ini cukup menyederhakan:

+ +
h2:target {font-weight: bold;}
+
+ +

Ini juga memungkinkan untuk membuat tampilan yang spesifik dari sebuah bagian bagian terkecil sebuah dokumen. Ini dilakukan menggunakan identifikasi nilai yang menemukan URI didalamnya. Dengan begitu, untuk menambahkan sebuah border pada #Example terpisah, kita dapat menuliskannya dengan:

+ +
#Example:target {border: 1px solid black;}
+ +

Menargetkan Seluruh Elemen

+ +

Jika intensif (berkelanjutan) untuk membuat sebuah "blanket" tampilan yang akan diterapkan pada seluruh target element, selanjutnya seleksi secara umum yang dapat diterapkan didalamnya:

+ +
:target {color: red;}
+
+ +

Contoh

+ +

Berikut contoh, ada lima poin tautan elemen dalam dokumen yang sama. Menyeleksi link "First", sebagai contoh, akan menyebabkan <h1 id="one"> menjadi target elemen. Catatan bahwa dokumen boleh melompat pada sebuah scroll posisi baru, selama target elemen ditempatkan pada posisi atas dari jendela browser jika memungkinkan. 

+ +
+
<h4 id="one">...</h4> <p id="two">...</p>
+<div id="three">...</div> <a id="four">...</a> <em id="five">...</em>
+
+<a href="#one">First</a>
+<a href="#two">Second</a>
+<a href="#three">Third</a>
+<a href="#four">Fourth</a>
+<a href="#five">Fifth</a>
+
+ +

Kesimpulan

+ +

Dalam kasus dimana sebuah pengidentifikasi poin bagian bagian dari sebuah bagian dokumen, para pembaca bisa jadi dibingungkan tentang yang mana bagian dari dokumen yang mereka anggap untuk dapat dibaca (diseleksi). Dengan gaya target sebuah URI, kebingungan pembaca dapat dikurangi atau dihilangkan. 

+ + + + + +
+

Original Document Information

+ + +
diff --git a/files/id/web/css/flex-direction/index.html b/files/id/web/css/flex-direction/index.html new file mode 100644 index 0000000000..7406212148 --- /dev/null +++ b/files/id/web/css/flex-direction/index.html @@ -0,0 +1,155 @@ +--- +title: flex-direction +slug: Web/CSS/flex-direction +translation_of: Web/CSS/flex-direction +--- +
{{CSSRef}}
+ +


+

+ +

flex-direction  adalah properti css yang menentukan sumbu utama dan arah (normal atau terbalik ) dari flex item yang ditempatkan di flex container / wadah .

+ +
{{EmbedInteractiveExample("pages/css/flex-direction.html")}}
+ + + +

Note that the values row and row-reverse are affected by the directionality of the flex container. If its {{HTMLAttrxRef("dir")}} attribute is ltr, row represents the horizontal axis oriented from the left to the right, and row-reverse from the right to the left; if the dir attribute is rtl, row represents the axis oriented from the right to the left, and row-reverse from the left to the right.

+ +

Syntax

+ +
/* The direction text is laid out in a line */
+flex-direction: row;
+
+/* Like <row>, but reversed */
+flex-direction: row-reverse;
+
+/* The direction in which lines of text are stacked */
+flex-direction: column;
+
+/* Like <column>, but reversed */
+flex-direction: column-reverse;
+
+/* Global values */
+flex-direction: inherit;
+flex-direction: initial;
+flex-direction: unset;
+
+ +

Values

+ +

The following values are accepted:

+ +
+
row
+
The flex container's main-axis is defined to be the same as the text direction. The main-start and main-end points are the same as the content direction.
+
row-reverse
+
Behaves the same as row but the main-start and main-end points are permuted.
+
column
+
The flex container's main-axis is the same as the block-axis. The main-start and main-end points are the same as the before and after points of the writing-mode.
+
column-reverse
+
Behaves the same as column but the main-start and main-end are permuted.
+
+ +

Accessibility concerns

+ +

Using the flex-direction property with values of row-reverse or column-reverse will create a disconnect between the visual presentation of content and DOM order. This will adversely affect users experiencing low vision navigating with the aid of assistive technology such as a screen reader. If the visual (CSS) order is important, then screen reader users will not have access to the correct reading order.

+ + + +

Formal definition

+ +

{{cssinfo}}

+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

Reversing flex container columns and rows

+ +

HTML

+ +
<h4>This is a Column-Reverse</h4>
+<div id="content">
+  <div class="box" style="background-color:red;">A</div>
+  <div class="box" style="background-color:lightblue;">B</div>
+  <div class="box" style="background-color:yellow;">C</div>
+</div>
+<h4>This is a Row-Reverse</h4>
+<div id="content1">
+  <div class="box1" style="background-color:red;">A</div>
+  <div class="box1" style="background-color:lightblue;">B</div>
+  <div class="box1" style="background-color:yellow;">C</div>
+</div>
+
+ +

CSS

+ +
#content {
+  width: 200px;
+  height: 200px;
+  border: 1px solid #c3c3c3;
+  display: flex;
+  flex-direction: column-reverse;
+}
+
+.box {
+  width: 50px;
+  height: 50px;
+}
+
+#content1 {
+  width: 200px;
+  height: 200px;
+  border: 1px solid #c3c3c3;
+  display: flex;
+  flex-direction: row-reverse;
+}
+
+.box1 {
+  width: 50px;
+  height: 50px;
+}
+ +

Result

+ +

{{EmbedLiveSample('Reversing_flex_container_columns_and_rows', '', '550')}}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Flexbox', '#flex-direction-property', 'flex-direction')}}{{Spec2('CSS3 Flexbox')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.properties.flex-direction")}}

+ +

See also

+ + diff --git a/files/id/web/css/index.html b/files/id/web/css/index.html new file mode 100644 index 0000000000..c4f9c56adb --- /dev/null +++ b/files/id/web/css/index.html @@ -0,0 +1,64 @@ +--- +title: CSS +slug: Web/CSS +translation_of: Web/CSS +--- +

Cascading Style Sheets, dikenal juga sebagai CSS, adalah bahasa stylesheet yang digunakan untuk merubah tampilan dokumen yang terulis dalam HTML atau XML (termasuk variasi bahasa XML seperti SVG atau XHTML). CSS menjelaskan bagaimana elemen terstruktur yang harus ditampilkan di layar, di kertas, dalam cara komunikasi, atau dalam media yang lain.

+ +

CSS adalah salah satu dari bahasa inti dari open web (web berbasis terbuka) dan telah berstandar W3C specification. Dibangun dalam berbagai level, CSS1 sekarang sudah kuno, CSS2.1 direkomendasi dan CSS3, sekarang terbagi dalam modul kecil, bergerak dalam jalur standar.

+ +
+ + +
+
+

Dokumentasi dan tutorial

+ +
+
Kunci konsep CSS
+
Menjelaskan syntax dan lembar bahasa dan memperkenalkan dasar-dasar seperti specificity dan inheritance, box model dan margin collapsing, stacking dan konteks block-formatting, atau initial, computed, used dan nilai actual. Entitas seperti CSS shorthand properties juga dijelaskan.
+
Panduan Pengembang CSS
+
Artikel yang membantu mempelajari tehnik CSS untuk membuat konten anda bersinar.
+
+ +

Alat untuk pengembang CSS

+ +
    +
  • W3C CSS Validation Service mengecek bila CSS yang diberikan adalah valid. Ini adalah alat debugging yang berguna.
  • +
  • Firebug extension milik Firefox, extensi populer yang mengizinkan untuk merubah secara langsung CSS dalam situs yang dilihat. Sangat praktis untuk beberapa perubahan, bahkan ekstensi ini berguna lebih banyak.
  • +
  • Web Developer extension milik FireFox juga mengizinkan melihat dan merubah scara langsung CSS dalam situs yang dilihat. lebih mudah daripada Firebug, walaupun kurang berguna.
  • +
  • EditCSS extension milik FireFox mengizinkan mengubah CSS dalam sidebar.
  • +
+ + + + +
+ +
+ + +
    +
  • CSS Text-decoration Level 3 mencapai status Candidate Recommandation, termasuk properti text-decoration-* dan text-emphasis-*. Berikut lingk yang menjelaskan hal ini {{cssxref("text-shadow")}}. (August 1st, 2013)
  • +
  • Gecko sekarang suport {{cssxref("background-origin")}}: local. Ini tersedia dari Firefox 25 (dan siap juga dalam Nightly). (July 25th, 2013)
  • +
  • Pointer Events mencapai status Candidate Recommandation, berarti properti CSS touch-action, yang hanya dapat diimplementasikan pada IE10 (dengan prefiks -ms- ), sekarang bukan percobaan lagi. (May 6th, 2013)
  • +
  • Gecko suport flexible boxes yang telah ditambahkan untuk menyesuaikan spesifikasi terkini tercantum: dari Firefox 23 {{cssxref("::before")}} dan {{cssxref("::after")}} bersama dengan item fleksibel, dan semacam itu, dapat dipindah menggunakan {{cssxref("order")}} dan {{cssxref("align-self")}}. (May 3rd, 2013)
  • +
+
+
+
diff --git a/files/id/web/css/mask-border-width/index.html b/files/id/web/css/mask-border-width/index.html new file mode 100644 index 0000000000..b017ac4a56 --- /dev/null +++ b/files/id/web/css/mask-border-width/index.html @@ -0,0 +1,104 @@ +--- +title: mask-border-width +slug: Web/CSS/mask-border-width +translation_of: Web/CSS/mask-border-width +--- +
{{CSSRef}}
+ +

The mask-border-width CSS properti mengatur lebar elemen mask border.

+ +

Syntax

+ +
/* Keyword value */
+mask-border-width: auto;
+
+/* <length> value */
+mask-border-width: 1rem;
+
+/* <percentage> value */
+mask-border-width: 25%;
+
+/* <number> value */
+mask-border-width: 3;
+
+/* vertical | horizontal */
+mask-border-width: 2em 3em;
+
+/* top | horizontal | bottom */
+mask-border-width: 5% 15% 10%;
+
+/* top | right | bottom | left */
+mask-border-width: 5% 2em 10% auto;
+
+/* Global values */
+mask-border-width: inherit;
+mask-border-width: initial;
+mask-border-width: unset;
+
+ +

The mask-border-width properti dapat ditentukan menggunakan satu, dua, tiga, atau empat nilai yang dipilih dari daftar nilai di bawah.

+ + + +

Values

+ +
+
<length-percentage>
+
Lebar batas topeng, ditetapkan sebagai {{cssxref ("<length>")}} atau {{cssxref ("<percentage>")}}. Persentase relatif terhadap lebar area perbatasan untuk offset horizontal dan tinggi area perbatasan untuk offset vertikal. Tidak boleh negatif.
+
<number>
+
Lebar batas topeng, ditentukan sebagai kelipatan yang sesuai {{cssxref("border-width")}}. Tidak boleh negatif.
+
auto
+
Lebar batas topeng dibuat sama dengan lebar atau tinggi intrinsik (mana yang dapat diterapkan) yang sesuai {{cssxref("mask-border-slice")}}. Jika gambar tidak memiliki dimensi intrinsik yang diperlukan, sesuai border-width digunakan sebagai gantinya.
+
+ +

Formal definition

+ +

{{cssinfo}}

+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

Basic usage

+ +

Properti ini tampaknya belum didukung di mana pun. Ketika akhirnya mulai didukung, itu akan berfungsi untuk menentukan lebar topeng perbatasan - mengatur ini ke nilai yang berbeda menjadi mask-border-slice akan menyebabkan irisan diskalakan agar sesuai dengan topeng perbatasan.

+ +
mask-border-width: 30 fill;
+ +

Browser berbasis Chromium mendukung versi lama properti ini — mask-box-image-width — dengan awalan:

+ +
-webkit-mask-box-image-width: 20px;
+ +
+

Note: The mask-border Halaman menampilkan contoh yang berfungsi (menggunakan properti topeng perbatasan awalan kedaluwarsa yang didukung di Chromium), sehingga Anda bisa mendapatkan gambaran tentang efeknya.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS Masks", "#propdef-mask-border-width", "mask-border-width")}}{{Spec2("CSS Masks")}}Initial definition
+ +

Browser compatibility

+ +

TBD

diff --git a/files/id/web/css/referensi/index.html b/files/id/web/css/referensi/index.html new file mode 100644 index 0000000000..7609391ca5 --- /dev/null +++ b/files/id/web/css/referensi/index.html @@ -0,0 +1,185 @@ +--- +title: Referensi CSS +slug: Web/CSS/referensi +translation_of: Web/CSS/Reference +--- +
{{CSSRef}}
+ +

Gunakan referensi CSS ini untuk menelusuri indeks alfabetikal dari semua properti CSS umum, pseudo-classes, pseudo-elements, data types, dan at-rules. Anda juga dapat menulusuri konsep dasar and a list of selektor berdasarkan jenis. Juga ada referensi DOM-CSS / CSSOM.

+ +

Basic rule syntax

+ +

Style rule syntax

+ +
style-rule ::=
+    selectors-list {
+      properties-list
+    }
+
+ +

... where :

+ +
selectors-list ::=
+    selector[:pseudo-class] [::pseudo-element]
+    [, selectors-list]
+
+properties-list ::=
+    [property : value] [; properties-list]
+
+ +

See the index of selectors, pseudo-classes, and pseudo-elements below. The syntax for each specified value depends on the data type defined for each specified property.

+ +

Style rule examples

+ +
strong {
+  color: red;
+}
+
+div.menu-bar li:hover > ul {
+  display: block;
+}
+
+ +

For a beginner-level introduction to the syntax of selectors, see our guide on CSS Selectors. Be aware that any syntax error in a rule definition invalidates the entire rule. Invalid rules are ignored by the browser. Note that CSS rule definitions are entirely (ASCII) text-based, whereas DOM-CSS / CSSOM (the rule management system) is object-based.

+ +

At-rule syntax

+ +

As the structure of at-rules varies widely, please see At-rule to find the syntax of the specific one you want.

+ +

Keyword index

+ +
+

Note: The property names in this index do not include the JavaScript names where they differ from the CSS standard names.

+
+ +
{{CSS_Ref}}
+ +

Selectors

+ +

The following are the various selectors, which allow styles to be conditional based on various features of elements within the DOM.

+ +

Basic selectors

+ +

Basic selectors are fundamental selectors; these are the most basic selectors that are frequently combined to create other, more complex selectors.

+ + + +

Grouping selectors

+ +
+
Selector list A, B
+
Specifies that both A and B elements are selected. This is a grouping method to select several matching elements.
+
+ +

Combinators

+ +

Combinators are selectors that establish a relationship between two or more simple selectors, such as "A is a child of B" or "A is adjacent to B."

+ +
+
Adjacent sibling combinator A + B
+
Specifies that the elements selected by both A and B have the same parent and that the element selected by B immediately follows the element selected by A horizontally.
+
General sibling combinator A ~ B
+
Specifies that the elements selected by both A and B share the same parent and that the element selected by A comes before—but not necessarily immediately before—the element selected by B.
+
Child combinator A > B
+
Specifies that the element selected by B is the direct child of the element selected by A.
+
Descendant combinator A B
+
Specifies that the element selected by B is a descendant of the element selected by A, but is not necessarily a direct child.
+
Column combinator A || B {{Experimental_Inline}}
+
Specifies that the element selected by B is located within the table column specified by A. Elements which span multiple columns are considered to be a member of all of those columns.
+
+ +

Pseudo

+ +
+
Pseudo classes :
+
Specifies a special state of the selected element(s).
+
Pseudo elements ::
+
Represents entities that are not included in HTML.
+
+ +
+

See also: Selectors in the Selectors Level 4 specification.

+
+ +

Concepts

+ +

Syntax and semantics

+ + + +

Values

+ + + +

Layout

+ + + +

DOM-CSS / CSSOM

+ +

Major object types

+ + + +

Important methods

+ + + +

See also

+ + + + + + diff --git a/files/id/web/css/text-transform/index.html b/files/id/web/css/text-transform/index.html new file mode 100644 index 0000000000..41db13ecf4 --- /dev/null +++ b/files/id/web/css/text-transform/index.html @@ -0,0 +1,307 @@ +--- +title: text-transform +slug: Web/CSS/text-transform +translation_of: Web/CSS/text-transform +--- +
{{CSSRef}}
+ +

Properti CSS text-transform menerangkan bagaimana mengatur teks sebuah elemen. Properti ini dapat digunakan untuk membuat sebuah teks menjadi besar atau kecil semua, atau membuat setiap kata dikapitalisasi.

+ +
/* Nilai Kata-kunci */
+text-transform: capitalize;
+text-transform: uppercase;
+text-transform: lowercase;
+text-transform: none;
+text-transform: full-width;
+
+/* Nilai Global */
+text-transform: inherit;
+text-transform: initial;
+text-transform: unset;
+
+ +

Properti text-transform memperhatikan peraturan khusus untuk setiap bahasa, seperti:

+ + + +

Pilihan bahasa didefinisikan dengan atribut HTML lang atau dengan atribut XML xml:lang.

+ +

Dukungan untuk kasus-kasus tertentu tidak sama untuk semua peramban, harap periksa tabel kompatibilitas peramban.

+ +

{{cssinfo}}

+ +

Syntax

+ +
+
capitalize
+
+

Adalah kata kunci yang mengubah secara paksa huruf pertama dari setiap kata menjadi huruf besar. Karakter lainnya tidak berubah; huruf-huruf tersebut akan tetap seperti pertama kali dituliskan pada katanya. Sebuah huruf adalah karakter Unicode dari kategori Huruf atau Angka umum {{experimental_inline}} : pilihan ini tidak memasukkan tanda baca atau simbal pada awal kata.

+ +
Penulis tidak seharusnya mengharapkan capitalize untuk mengikuti konvensi huruf besar untuk bahasa tertentu (seperti mengabaikan artikel dalam bahasa Inggris).
+ +
Kata kunci capitalize kurang dispesifikasikan pada CSS 1 dan CSS 2.1. Terdapat perbedaan antara peramban untuk memperhitungkan huruf pertama (Firefox menganggap - dan _ sebagai huruf, tetapi peramban lain tidak. Baik Webkit dan Gecko tidak dengan tepat menanggap simbol berdasarkan huruf seperti sebagai benar-benar huruf. Internet Explorer 9 menerapkan definisi CSS 2 yang paling mendekati, tetapi dengan beberapa kasus sangat aneh). Dengan mendefinisikan bagaimana penerapan yang benar secara jelas, CSS Text Level 3 membersihkan kekacauan ini. Baris capitalize di tabel kompatibilitas peramban mempunyai informasi pada versi berapa mesin peramban mulai mendukung penerapan ini
+
+
uppercase
+
Adalah kata kunci yang mengubah semua karakter menjadi huruf besar.
+
lowercase
+
Adalah kata kunci yang mengubah semua karakter menjadi huruf kecil.
+
none
+
Adalah kata kunci yang mencegah perubahan dari semua karakter.
+
full-width {{experimental_inline}}
+
Adalah kata kunci yang mengharuskan penulisan karakter — biasanya ideogram dan tulisan latin — di dalam kotak persegi, yang membuat mereka dapat sejajar dalam tulisan Asia Timur kebanyakan (seperti bahasa Cina atau Jepang).
+ +
+ +

Sintaksis Formal

+ +
{{csssyntax}}
+ +

Contoh

+ +

none

+ +
<p>Kalimat Awal
+  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
+</p>
+<p>text-transform: none
+  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
+</p>
+
+ +
span {
+  text-transform: none;
+}
+strong { float: right; }
+ +

This demonstrates no text transformation.

+ +

{{ EmbedLiveSample('none', '100%', '100px') }}

+ +

capitalize (Umum)

+ +
<p>Kalimat Awal
+  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
+</p>
+<p>text-transform: capitalize
+  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
+</p>
+ +
span {
+  text-transform: capitalize;
+}
+strong { float: right; }
+ +

Contoh ini menunjukkan kata yang dikapitalkan.

+ +

{{ EmbedLiveSample('capitalize_(General)', '100%', '100px') }}

+ +

capitalize (Tanda Baca)

+ +
<p>Kalimat Awal
+  <strong>(this) “is” [a] –short– -test- «for» *the* _css_ ¿capitalize? ?¡transform!</strong>
+</p>
+<p>text-transform: capitalize
+  <strong><span>(this) “is” [a] –short– -test- «for» *the* _css_ ¿capitalize? ?¡transform!</span></strong>
+</p>
+ +
span {
+  text-transform: capitalize;
+}
+strong { float: right; }
+ +

Contoh ini mennjukkan bagaimana tanda baca di awal sebuah kata diabaikan. Kata kunci ini bekerja pada huruf pertama yang termasuk dalam bagian karakter Unicode dari kategori Huruf dan Angka umum.

+ +

{{ EmbedLiveSample('capitalize_(Punctuation)', '100%', '100px') }}

+ +

capitalize (Simbol)

+ +
<p>Kalimat Awal
+  <strong>ⓐⓑⓒ (ⓓⓔⓕ) —ⓖⓗⓘ— ⓙkl</strong>
+</p>
+<p>text-transform: capitalize
+  <strong><span>ⓐⓑⓒ (ⓓⓔⓕ) —ⓖⓗⓘ— ⓙkl</span></strong>
+</p>
+ +
span {
+  text-transform: capitalize;
+}
+strong { float: right; }
+ +

Contoh ini menunjukkan bagaimana simbol di awal kata diabaikan. Kata kunci ini bekerja pada huruf pertama yang termasuk dalam bagian karakter Unicode dari kategori Huruf dan Angka umum.

+ +

{{ EmbedLiveSample('capitalize_(Symbols)', '100%', '100px') }}

+ +

capitalize (dwihuruf Belanda ij)

+ +
<p>Kalimat Awal
+  <strong lang="nl">The Dutch word: "ijsland" starts with a digraph.</strong>
+</p>
+<p>text-transform: capitalize
+  <strong><span lang="nl">The Dutch word: "ijsland" starts with a digraph.</span></strong>
+</p>
+ +
span {
+  text-transform: capitalize;
+}
+strong { float: right; }
+ +

Contoh ini menunjukkan bagaimana dwihuruf bahasa Belanda ij harus diperlakukan sebagai huruf tunggal.

+ +

{{ EmbedLiveSample('capitalize_(Dutch_ij_digraph)', '100%', '100px') }}

+ +

uppercase (Umum)

+ +
<p>Kalimat Awal
+  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
+</p>
+<p>text-transform: uppercase
+  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
+</p>
+ +
span {
+  text-transform: uppercase;
+}
+strong { float: right; }
+ +

Contoh ini menunjukkan bagaimana kalimat diubah menjadi huruf besar.

+ +

{{ EmbedLiveSample('uppercase_(General)', '100%', '100px') }}

+ +

uppercase (Huruf Vokal Yunani)

+ +
<p>Kalimat Awal
+  <strong>Θα πάμε στο "Θεϊκό φαΐ" ή στη "Νεράιδα"</strong>
+</p>
+<p>text-transform: uppercase
+  <strong><span>Θα πάμε στο "Θεϊκό φαΐ" ή στη "Νεράιδα"</span></strong>
+</p>
+ +
span {
+  text-transform: uppercase;
+}
+strong { float: right; }
+ +

Contoh ini menunjukkan bagaimana huruf vokal bahasa Yunani, kecuali huruf disjungtif eta, kehilangan aksen, dan aksen pada huruf vokal pertama dari pasangan vokal menjadi diaeresis pada huruf vokal kedua.

+ +

{{ EmbedLiveSample('uppercase_(Greek_Vowels)', '100%', '100px') }}

+ +

lowercase (Umum)

+ +
<p>Kalimat Awal
+  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
+</p>
+<p>text-transform: lowercase
+  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
+</p>
+ +
span {
+  text-transform: lowercase;
+}
+strong { float: right; }
+ +

Contoh ini menunjukkan bagaimana kalimat diubah menjadi huruf kecil.

+ +

{{ EmbedLiveSample('lowercase_(General)', '100%', '100px') }}

+ +

lowercase (Huruf Yunani Σ)

+ +
<p>Kalimat Awal
+  <strong>Σ IS A greek LETTER that appears SEVERAL TIMES IN ΟΔΥΣΣΕΥΣ.</strong>
+</p>
+<p>text-transform: lowercase
+  <strong><span>Σ IS A greek LETTER that appears SEVERAL TIMES IN ΟΔΥΣΣΕΥΣ.</span></strong>
+</p>
+ +
span {
+  text-transform: lowercase;
+}
+strong { float: right; }
+ +

Contoh ini menunjukkan bagaimana karakter bahasa Yunani sigma (Σ) diubah menjadi huruf kecil sigma biasa (σ) atau varian akhir-kata (ς), tergantung kepada konteksnya.

+ +

{{ EmbedLiveSample('lowercase_(Greek_Σ)', '100%', '100px') }}

+ +

full-width (Umum)

+ +
<p>Kalimat Awal
+  <strong>0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@{|}~</strong>
+</p>
+<p>text-transform: full-width
+  <strong><span>0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@{|}~</span></strong>
+</p>
+ +
span {
+  text-transform: full-width;
+}
+strong { width: 100%; float: right; }
+ +

Beberapa karakter mempunyai dua bentuk, yaitu lebar normal dan penuh, dengan kode nilai Unicode yang berbeda. Versi lebar-penuh digunakan untuk membuat penggabungan penulisan dengan karakter ideografi Asia dengan mulus.

+ +

{{ EmbedLiveSample('full-width_(General)', '100%', '175px') }}

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('CSS4 Text', '#text-transform', 'text-transform')}}{{Spec2('CSS4 Text')}}Dari {{SpecName('CSS3 Text', '#text-transform', 'text-transform')}}, menambahkan kata kunci full-size-kana dan membolehkan kata kunci full-width digunakan bersama dengan kata kunci lainnya.
{{SpecName('CSS3 Text', '#text-transform', 'text-transform')}}{{Spec2('CSS3 Text')}}Dari {{SpecName('CSS2.1', 'text.html#caps-prop', 'text-transform')}}, memperluas cakupan huruf ke semua karakter Unicode dalam kategori Angka dan Huruf umum. Mengubah penerapan  capitalize ke huruf pertama kata, mengabaikan tanda baca atau simbol di awal. Menambahkan kata kunci full-width untuk membuat penggabungan penulisan dengan karakter ideografi dan alfabet menjadi mulus.
{{SpecName('CSS2.1', 'text.html#caps-prop', 'text-transform')}}{{Spec2('CSS2.1')}}Dari {{SpecName('CSS1', '#text-transform', 'text-transform')}}, memperluas cakupan huruf dengan tulisan bikameral non-latin.
{{SpecName('CSS1', '#text-transform', 'text-transform')}}{{Spec2('CSS1')}}Definisi awal
+ +

Kompatibilitas Peramban

+ +

 

+ + + +

{{Compat("css.properties.text-transform")}}

+ +

 

+ +

Lihat juga

+ + diff --git a/files/id/web/css/type_selectors/index.html b/files/id/web/css/type_selectors/index.html new file mode 100644 index 0000000000..5302eef6eb --- /dev/null +++ b/files/id/web/css/type_selectors/index.html @@ -0,0 +1,121 @@ +--- +title: Type selectors +slug: Web/CSS/Type_selectors +translation_of: Web/CSS/Type_selectors +--- +
{{CSSRef("Selectors")}}
+ +

Rangkuman

+ +

Gaya seleksi CSS menampilkan elemen dengan nama node (bagian khusus nama elemen). Digunakan tersendiri, karenanya, sebuah tipe seleksi untuk sebuah nama node bagian terkecil menyeleksi seluruh bagian bagian dari tipe tersebut -- yang mana bahwa, dengan nama node tersebut -- didalam dokumen.

+ +

Bentuk Penulisan

+ +
element { style properties }
+
+ +

Contoh

+ +

CSS

+ +
span {
+  background-color: DodgerBlue;
+  color: #ffffff;
+}
+
+ +

HTML

+ +
<span>Here's a span with some text.</span>
+<p>Here's a p with some text.</p>
+
+ +

Hasil

+ +

{{EmbedLiveSample('Example', 200, 100)}}

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('CSS4 Selectors', '#type-selectors', 'Type (tag name) selector')}}{{Spec2('CSS4 Selectors')}}Tanpa Perubahan
{{SpecName('CSS3 Selectors', '#type-selectors', 'type selectors')}}{{Spec2('CSS3 Selectors')}}Tanpa Perubahan
{{SpecName('CSS2.1', 'selector.html#type-selectors', 'type selectors')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1', '#basic-concepts', 'type selectors')}}{{Spec2('CSS1')}}Defenisi Tanda
+ +

Dukungan Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/id/web/events/cached/index.html b/files/id/web/events/cached/index.html new file mode 100644 index 0000000000..195f18f846 --- /dev/null +++ b/files/id/web/events/cached/index.html @@ -0,0 +1,74 @@ +--- +title: cached +slug: Web/Events/cached +translation_of: Archive/Events/cached +--- +

Event cached dijalankan ketika resource pada daftar application cache manifest telah terunduh, dan aplikasi sekarang ter-cache.

+ +

Info Umum

+ +
+
Spesifikasi
+
Offline
+
Interface
+
Event
+
Bubbles
+
No
+
Cancelable
+
No
+
Target
+
applicationCache
+
Default Action
+
None
+
+ +

Properti

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertiTypeDeskripsi
targetEventTarget (DOM element)The event target (the topmost target in the DOM tree). Read Only.
typestringThe type of event. Read only.
canBubblebooleanDoes the event normally bubble? Read only.
cancelablebooleanIs it possible to cancel the event? Read only.
+ +

Event Terkait

+ + + +

Lihat juga

+ + diff --git a/files/id/web/events/error/index.html b/files/id/web/events/error/index.html new file mode 100644 index 0000000000..a5c531c19c --- /dev/null +++ b/files/id/web/events/error/index.html @@ -0,0 +1,71 @@ +--- +title: error +slug: Web/Events/error +translation_of: Web/API/Element/error_event +--- +

Event error ditampilkan ketika sumberdaya gagal dimuat.

+ +

Informasi umum

+ +
+
Spesifikasi
+
DOM L3
+
Antar muka
+
UIEvent jika digenerasikan dari antarmuka pengguna, event sebaliknya.
+
Bubbles
+
No
+
Cancelable
+
No
+
Target
+
Element
+
Default Action
+
None
+
+ +

Properti

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not.
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not.
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
+ +

Lihat Juga

+ +

{{domxref("GlobalEventHandlers.onerror")}} - window.onerror dan element.onerror.

diff --git a/files/id/web/events/index.html b/files/id/web/events/index.html new file mode 100644 index 0000000000..3560bde99a --- /dev/null +++ b/files/id/web/events/index.html @@ -0,0 +1,2310 @@ +--- +title: Event reference +slug: Web/Events +tags: + - NeedsTranslation + - TopicStub + - events +translation_of: Web/Events +--- +

DOM Events are sent to notify code of interesting things that have taken place. Each event is represented by an object which is based on the {{domxref("Event")}} interface, and may have additional custom fields and/or functions used to get additional information about what happened. Events can represent everything from basic user interactions to automated notifications of things happening in the rendering model.

+ +

This article offers a list of events that can be sent; some are standard events defined in official specifications, while others are events used internally by specific browsers; for example, Mozilla-specific events are listed so that add-ons can use them to interact with the browser.

+ +

Standard events

+ +

These events are defined in official Web specifications, and should be common across browsers. Each event is listed along with the interface representing the object sent to recipients of the event (so you can find information about what data is provided with each event) as well as a link to the specification or specifications that define the event.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Event NameEvent TypeSpecificationFired when...
{{event("abort")}}{{domxref("UIEvent")}}DOM L3The loading of a resource has been aborted.
abort{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been terminated (not due to an error).
abort{{domxref("Event")}}IndexedDBA transaction has been aborted.
{{event("afterprint")}}{{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document has started printing or the print preview has been closed.
{{event("animationend")}}{{domxref("AnimationEvent")}}CSS AnimationsA CSS animation has completed.
{{event("animationiteration")}}{{domxref("AnimationEvent")}}CSS AnimationsA CSS animation is repeated.
{{event("animationstart")}}{{domxref("AnimationEvent")}}CSS AnimationsA CSS animation has started.
{{event("audioprocess")}}{{domxref("AudioProcessingEvent")}}{{SpecName('Web Audio API', '#AudioProcessingEvent', 'audioprocess')}}The input buffer of a {{domxref("ScriptProcessorNode")}} is ready to be processed.
{{event("audioend")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The user agent has finished capturing audio for speech recognition.
{{event("audiostart")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The user agent has started to capture audio for speech recognition.
{{event("beforeprint")}} {{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document is about to be printed or previewed for printing.
{{event("beforeunload")}}{{domxref("BeforeUnloadEvent")}}HTML5  
{{event("beginEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element begins.
blocked IndexedDBAn open connection to a database is blocking a versionchange transaction on the same database.
{{event("blur")}}{{domxref("FocusEvent")}}DOM L3An element has lost focus (does not bubble).
{{event("boundary")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a word or sentence boundary
{{event("cached")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been downloaded, and the application is now cached.
{{event("canplay")}}{{domxref("Event")}}HTML5 mediaThe user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
{{event("canplaythrough")}}{{domxref("Event")}}HTML5 mediaThe user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
{{event("change")}}{{domxref("Event")}}DOM L2, HTML5The change event is fired for {{HTMLElement("input")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}} elements when a change to the element's value is committed by the user.
{{event("chargingchange")}}{{domxref("Event")}}Battery statusThe battery begins or stops charging.
{{event("chargingtimechange")}}{{domxref("Event")}}Battery statusThe chargingTime attribute has been updated.
{{event("checking")}}{{domxref("Event")}}OfflineThe user agent is checking for an update, or attempting to download the cache manifest for the first time.
{{event("click")}}{{domxref("MouseEvent")}}DOM L3A pointing device button has been pressed and released on an element.
close{{domxref("Event")}}WebSocketA WebSocket connection has been closed.
complete IndexedDB 
{{event("complete")}}{{domxref("OfflineAudioCompletionEvent")}}{{SpecName('Web Audio API', '#OfflineAudioCompletionEvent-section', 'OfflineAudioCompletionEvent')}}The rendering of an {{domxref("OfflineAudioContext")}} is terminated.
{{event("compositionend")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text has been completed or canceled.
{{event("compositionstart")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).
{{event("compositionupdate")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3A character is added to a passage of text being composed.
{{event("contextmenu")}}{{domxref("MouseEvent")}}HTML5The right button of the mouse is clicked (before the context menu is displayed).
{{event("copy")}}{{domxref("ClipboardEvent")}}ClipboardThe text selection has been added to the clipboard.
{{event("cut")}}{{domxref("ClipboardEvent")}}ClipboardThe text selection has been removed from the document and added to the clipboard.
{{event("dblclick")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is clicked twice on an element.
{{event("devicelight")}}{{domxref("DeviceLightEvent")}}Ambient Light EventsFresh data is available from a light sensor.
{{event("devicemotion")}}{{domxref("DeviceMotionEvent")}}Device Orientation EventsFresh data is available from a motion sensor.
{{event("deviceorientation")}}{{domxref("DeviceOrientationEvent")}}Device Orientation EventsFresh data is available from an orientation sensor.
{{event("deviceproximity")}}{{domxref("DeviceProximityEvent")}}Proximity EventsFresh data is available from a proximity sensor (indicates an approximated distance between the device and a nearby object).
{{event("dischargingtimechange")}}{{domxref("Event")}}Battery statusThe dischargingTime attribute has been updated.
DOMActivate {{deprecated_inline}}{{domxref("UIEvent")}}DOM L3A button, link or state changing element is activated (use {{event("click")}} instead).
DOMAttributeNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an attribute changed (use mutation observers instead).
DOMAttrModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3The value of an attribute has been modified (use mutation observers instead).
DOMCharacterDataModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A text or another CharacterData has changed (use mutation observers instead).
{{event("DOMContentLoaded")}}{{domxref("Event")}}HTML5The document has finished loading (but not its dependent resources).
DOMElementNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an element changed (use mutation observers instead).
DOMFocusIn {{deprecated_inline}}{{domxref("FocusEvent")}}DOM L3An element has received focus (use {{event("focus")}} or {{event("focusin")}} instead).
DOMFocusOut {{deprecated_inline}}{{domxref("FocusEvent")}}DOM L3An element has lost focus (use {{event("blur")}} or {{event("focusout")}} instead).
DOMNodeInserted {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been added as a child of another node (use mutation observers instead).
DOMNodeInsertedIntoDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been inserted into the document (use mutation observers instead).
DOMNodeRemoved {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from its parent node (use mutation observers instead).
DOMNodeRemovedFromDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from the document (use mutation observers instead).
DOMSubtreeModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A change happened in the document (use mutation observers instead).
{{event("downloading")}}{{domxref("Event")}}OfflineThe user agent has found an update and is fetching it, or is downloading the resources listed by the cache manifest for the first time.
{{event("drag")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged (every 350ms).
{{event("dragend")}}{{domxref("DragEvent")}}HTML5A drag operation is being ended (by releasing a mouse button or hitting the escape key).
{{event("dragenter")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection enters a valid drop target.
{{event("dragleave")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection leaves a valid drop target.
{{event("dragover")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged over a valid drop target (every 350ms).
{{event("dragstart")}}{{domxref("DragEvent")}}HTML5The user starts dragging an element or text selection.
{{event("drop")}}{{domxref("DragEvent")}}HTML5An element is dropped on a valid drop target.
{{event("durationchange")}}{{domxref("Event")}}HTML5 mediaThe duration attribute has been updated.
{{event("emptied")}}{{domxref("Event")}}HTML5 mediaThe media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
{{event("end_(SpeechRecognition)","end")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has disconnected.
{{event("end_(SpeechSynthesis)","end")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName("Web Speech API")}}The utterance has finished being spoken.
{{event("ended")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because the end of the media was reached.
{{event("ended_(Web_Audio)", "ended")}}{{domxref("Event")}}{{SpecName("Web Audio API")}} 
{{event("endEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element ends.
{{event("error")}}{{domxref("UIEvent")}}DOM L3A resource failed to load.
{{event("error")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has failed.
{{event("error")}}{{domxref("Event")}}OfflineAn error occurred while downloading the cache manifest or updating the content of the application.
{{event("error")}}{{domxref("Event")}}WebSocketA WebSocket connection has been closed with prejudice (some data couldn't be sent for example).
{{event("error")}}{{domxref("Event")}}Server Sent EventsAn event source connection has been failed.
{{event("error")}}{{domxref("Event")}}IndexedDBA request caused an error and failed.
{{event("error_(SpeechRecognitionError)","error")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}A speech recognition error occurs.
{{event("error_(SpeechSynthesisError)","error")}}{{domxref("SpeechSynthesisErrorEvent")}}{{SpecName('Web Speech API')}}An error occurs that prevents the utterance from being successfully spoken.
{{event("focus")}}{{domxref("FocusEvent")}}DOM L3An element has received focus (does not bubble).
{{event("focusin")}}{{domxref("FocusEvent")}}DOM L3An element is about to receive focus (bubbles).
{{event("focusout")}}{{domxref("FocusEvent")}}DOM L3An element is about to lose focus (bubbles).
{{event("fullscreenchange")}}{{gecko_minversion_inline("9")}}{{domxref("Event")}}Full ScreenAn element was turned to fullscreen mode or back to normal mode.
{{event("fullscreenerror")}}{{gecko_minversion_inline("9")}}{{domxref("Event")}}Full ScreenIt was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
{{event("gamepadconnected")}}{{domxref("GamepadEvent")}}GamepadA gamepad has been connected.
{{event("gamepaddisconnected")}}{{domxref("GamepadEvent")}}GamepadA gamepad has been disconnected.
{{event("gotpointercapture")}}{{domxref("PointerEvent")}}Pointer EventsElement receives pointer capture.
{{event("hashchange")}}{{domxref("HashChangeEvent")}}HTML5The fragment identifier of the URL has changed (the part of the URL after the #).
{{event("lostpointercapture")}}{{domxref("PointerEvent")}}Pointer EventsElement lost pointer capture.
{{event("input")}}{{domxref("Event")}}HTML5The value of an element changes or the content of an element with the attribute contenteditable is modified.
{{event("invalid")}}{{domxref("Event")}}HTML5A submittable element has been checked and doesn't satisfy its constraints.
{{event("keydown")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down.
{{event("keypress")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down and that key normally produces a character value (use input instead).
{{event("keyup")}}{{domxref("KeyboardEvent")}}DOM L3A key is released.
{{event("languagechange")}}{{domxref("Event")}}{{ SpecName('HTML5.1', '#dom-navigator-languages', 'NavigatorLanguage.languages') }} 
{{event("levelchange")}}{{domxref("Event")}}Battery statusThe level attribute has been updated.
{{event("load")}}{{domxref("UIEvent")}}DOM L3A resource and its dependent resources have finished loading.
load{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been successful.
{{event("loadeddata")}}{{domxref("Event")}}HTML5 mediaThe first frame of the media has finished loading.
{{event("loadedmetadata")}}{{domxref("Event")}}HTML5 mediaThe metadata has been loaded.
{{event("loadend")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgress has stopped (after "error", "abort" or "load" have been dispatched).
{{event("loadstart")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgress has begun.
{{event("mark")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a named SSML "mark" tag.
message{{domxref("MessageEvent")}}WebSocketA message is received through a WebSocket.
message{{domxref("MessageEvent")}}Web WorkersA message is received from a Web Worker.
message{{domxref("MessageEvent")}}Web MessagingA message is received from a child (i)frame or a parent window.
message{{domxref("MessageEvent")}}Server Sent EventsA message is received through an event source.
{{event("message_(ServiceWorker)","message")}}{{domxref("ServiceWorkerMessageEvent")}} or {{domxref("ExtendableMessageEvent")}}, depending on context.Service WorkersA message is received from a service worker, or a message is received in a service worker from another context.
{{event("mousedown")}}{{domxref("MouseEvent")}}DOM L3A pointing device button (usually a mouse) is pressed on an element.
{{event("mouseenter")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached.
{{event("mouseleave")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached.
{{event("mousemove")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved over an element.
{{event("mouseout")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached or off one of its children.
{{event("mouseover")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached or onto one of its children.
{{event("mouseup")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is released over an element.
{{event("nomatch")}}{{domxref("SpeechRecognitionEvent")}}{{SpecName('Web Speech API')}}The speech recognition service returns a final result with no significant recognition.
{{event("notificationclick")}}{{domxref("NotificationEvent")}}{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}A system notification spawned by {{domxref("ServiceWorkerRegistration.showNotification()")}} has been clicked.
{{event("noupdate")}}{{domxref("Event")}}OfflineThe manifest hadn't changed.
{{event("obsolete")}}{{domxref("Event")}}OfflineThe manifest was found to have become a 404 or 410 page, so the application cache is being deleted.
{{event("offline")}}{{domxref("Event")}}HTML5 offlineThe browser has lost access to the network.
{{event("online")}}{{domxref("Event")}}HTML5 offlineThe browser has gained access to the network (but particular websites might be unreachable).
open{{domxref("Event")}}WebSocketA WebSocket connection has been established.
open{{domxref("Event")}}Server Sent EventsAn event source connection has been established.
{{event("orientationchange")}}{{domxref("Event")}}Screen OrientationThe orientation of the device (portrait/landscape) has changed
{{event("pagehide")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed from.
{{event("pageshow")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed to.
{{event("paste")}}{{domxref("ClipboardEvent")}}ClipboardData has been transferred from the system clipboard to the document.
{{event("pause")}}{{domxref("Event")}}HTML5 mediaPlayback has been paused.
{{event("pause_(SpeechSynthesis)", "pause")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance is paused part way through.
{{event("pointercancel")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer is unlikely to produce any more events.
{{event("pointerdown")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer enters the active buttons state.
{{event("pointerenter")}}{{domxref("PointerEvent")}}Pointer EventsPointing device is moved inside the hit-testing boundary.
{{event("pointerleave")}}{{domxref("PointerEvent")}}Pointer EventsPointing device is moved out of the hit-testing boundary.
{{event("pointerlockchange")}}{{domxref("Event")}}Pointer LockThe pointer was locked or released.
{{event("pointerlockerror")}}{{domxref("Event")}}Pointer LockIt was impossible to lock the pointer for technical reasons or because the permission was denied.
{{event("pointermove")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer changed coordinates.
{{event("pointerout")}}{{domxref("PointerEvent")}}Pointer EventsThe pointing device moved out of hit-testing boundary or leaves detectable hover range.
{{event("pointerover")}}{{domxref("PointerEvent")}}Pointer EventsThe pointing device is moved into the hit-testing boundary.
{{event("pointerup")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer leaves the active buttons state.
{{event("play")}}{{domxref("Event")}}HTML5 mediaPlayback has begun.
{{event("playing")}}{{domxref("Event")}}HTML5 mediaPlayback is ready to start after having been paused or delayed due to lack of data.
{{event("popstate")}}{{domxref("PopStateEvent")}}HTML5A session history entry is being navigated to (in certain cases).
{{event("progress")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestIn progress.
progress{{domxref("ProgressEvent")}}OfflineThe user agent is downloading resources listed by the manifest.
{{event("push")}}{{domxref("PushEvent")}}{{SpecName("Push API")}}A Service Worker has received a push message.
{{event("pushsubscriptionchange")}}{{domxref("PushEvent")}}{{SpecName("Push API")}}A PushSubscription has expired.
{{event("ratechange")}}{{domxref("Event")}}HTML5 mediaThe playback rate has changed.
{{event("readystatechange")}}{{domxref("Event")}}HTML5 and XMLHttpRequestThe readyState attribute of a document has changed.
{{event("repeatEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element is repeated.
{{event("reset")}}{{domxref("Event")}}DOM L2, HTML5A form is reset.
{{event("resize")}}{{domxref("UIEvent")}}DOM L3The document view has been resized.
{{event("resourcetimingbufferfull")}}{{domxref("Performance")}}Resource TimingThe browser's resource timing buffer is full.
{{event("result")}}{{domxref("SpeechRecognitionEvent")}}{{SpecName('Web Speech API')}}The speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app.
{{event("resume")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}A paused utterance is resumed.
{{event("scroll")}}{{domxref("UIEvent")}}DOM L3The document view or an element has been scrolled.
{{event("seeked")}}{{domxref("Event")}}HTML5 mediaA seek operation completed.
{{event("seeking")}}{{domxref("Event")}}HTML5 mediaA seek operation began.
{{event("select")}}{{domxref("UIEvent")}}DOM L3Some text is being selected.
{{event("selectstart")}}{{domxref("Event")}}{{ SpecName('Selection API')}}A selection just started.
{{event("selectionchange")}}{{domxref("Event")}}{{ SpecName('Selection API')}}The selection in the document has been changed.
{{event("show")}}{{domxref("MouseEvent")}}HTML5A contextmenu event was fired on/bubbled to an element that has a contextmenu attribute
{{event("soundend")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has stopped being detected.
{{event("soundstart")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has been detected.
{{event("speechend")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Speech recognised by the speech recognition service has stopped being detected.
{{event("speechstart")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Sound that is recognised by the speech recognition service as speech has been detected.
{{event("stalled")}}{{domxref("Event")}}HTML5 mediaThe user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
{{event("start_(SpeechRecognition)","start")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition.
{{event("start_(SpeechSynthesis)","start")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance has begun to be spoken.
{{event("storage")}}{{domxref("StorageEvent")}}Web StorageA storage area (localStorage or sessionStorage) has changed.
{{event("submit")}}{{domxref("Event")}}DOM L2, HTML5A form is submitted.
success{{domxref("Event")}}IndexedDBA request successfully completed.
{{event("suspend")}}{{domxref("Event")}}HTML5 mediaMedia data loading has been suspended.
{{event("SVGAbort")}}{{domxref("SVGEvent")}}SVGPage loading has been stopped before the SVG was loaded.
{{event("SVGError")}}{{domxref("SVGEvent")}}SVGAn error has occurred before the SVG was loaded.
{{event("SVGLoad")}}{{domxref("SVGEvent")}}SVGAn SVG document has been loaded and parsed.
{{event("SVGResize")}}{{domxref("SVGEvent")}}SVGAn SVG document is being resized.
{{event("SVGScroll")}}{{domxref("SVGEvent")}}SVGAn SVG document is being scrolled.
{{event("SVGUnload")}}{{domxref("SVGEvent")}}SVGAn SVG document has been removed from a window or frame.
{{event("SVGZoom")}}{{domxref("SVGZoomEvent")}}SVGAn SVG document is being zoomed.
{{event("timeout")}}{{domxref("ProgressEvent")}}XMLHttpRequest 
{{event("timeupdate")}}{{domxref("Event")}}HTML5 mediaThe time indicated by the currentTime attribute has been updated.
{{event("touchcancel")}}{{domxref("TouchEvent")}}Touch EventsA touch point has been disrupted in an implementation-specific manners (too many touch points for example).
{{event("touchend")}}{{domxref("TouchEvent")}}Touch EventsA touch point is removed from the touch surface.
{{event("touchenter")}}{{domxref("TouchEvent")}}Touch Events RemovedA touch point is moved onto the interactive area of an element.
{{event("touchleave")}}{{domxref("TouchEvent")}}Touch Events RemovedA touch point is moved off the interactive area of an element.
{{event("touchmove")}}{{domxref("TouchEvent")}}Touch EventsA touch point is moved along the touch surface.
{{event("touchstart")}}{{domxref("TouchEvent")}}Touch EventsA touch point is placed on the touch surface.
{{event("transitionend")}}{{domxref("TransitionEvent")}}CSS TransitionsA CSS transition has completed.
{{event("unload")}}{{domxref("UIEvent")}}DOM L3The document or a dependent resource is being unloaded.
{{event("updateready")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been newly redownloaded, and the script can use swapCache() to switch to the new cache.
upgradeneeded IndexedDBAn attempt was made to open a database with a version number higher than its current version. A versionchange transaction has been created.
{{event("userproximity")}}{{domxref("UserProximityEvent")}}{{SpecName("Proximity Events")}}Fresh data is available from a proximity sensor (indicates whether the nearby object is near the device or not).
{{event("voiceschanged")}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed (when the {{event("voiceschanged")}} event fires.)
versionchange IndexedDBA versionchange transaction completed.
{{event("visibilitychange")}}{{domxref("Event")}}Page visibilityThe content of a tab has become visible or has been hidden.
{{event("volumechange")}}{{domxref("Event")}}HTML5 mediaThe volume has changed.
{{event("waiting")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because of a temporary lack of data.
{{event("wheel")}}{{gecko_minversion_inline("17")}}{{domxref("WheelEvent")}}DOM L3A wheel button of a pointing device is rotated in any direction.
+ +

Non-standard events

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Event NameEvent TypeSpecificationFired when...
{{event("afterscriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script has been executed.
{{event("beforescriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script is about to be executed.
{{event("beforeinstallprompt")}}{{domxref("Event")}}Chrome specificA user is prompted to save a web site to a home screen on mobile.
{{event("cardstatechange")}} Firefox OS specificThe {{domxref("MozMobileConnection.cardState")}} property changes value.
{{event("change")}}{{domxref("DeviceStorageChangeEvent")}}Firefox OS specificThis event is triggered each time a file is created, modified or deleted on a given storage area.
{{event("connectionInfoUpdate")}} Firefox OS specificThe informations about the signal strength and the link speed have been updated.
{{event("cfstatechange")}} Firefox OS specificThe call forwarding state changes.
{{event("datachange")}} Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object changes values.
{{event("dataerror")}} Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object receive an error from the RIL.
{{event("DOMMouseScroll")}}{{deprecated_inline}} Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of lines). (use {{event("wheel")}} instead)
dragdrop {{deprecated_inline}}DragEventMozilla specificAn element is dropped (use {{event("drop")}} instead).
dragexit {{deprecated_inline}}DragEventMozilla specificA drag operation is being ended(use {{event("dragend")}} instead).
draggesture {{deprecated_inline}}DragEventMozilla specificThe user starts dragging an element or text selection (use {{event("dragstart")}} instead).
{{event("icccardlockerror")}} Firefox OS specificthe {{domxref("MozMobileConnection.unlockCardLock()")}} or {{domxref("MozMobileConnection.setCardLock()")}} methods fails.
{{event("iccinfochange")}} Firefox OS specificThe {{domxref("MozMobileConnection.iccInfo")}} object changes.
{{event("localized")}} Mozilla SpecificThe page has been localized using data-l10n-* attributes.
{{event("mousewheel")}}{{deprecated_inline}} IE inventedThe wheel button of a pointing device is rotated.
{{event("MozAudioAvailable")}}{{domxref("Event")}}Mozilla specificThe audio buffer is full and the corresponding raw samples are available.
MozBeforeResize {{obsolete_inline}} Mozilla specificA window is about to be resized.
{{event("mozbrowseractivitydone")}} Firefox OS Browser API-specificSent when some activity has been completed (complete description TBD.)
{{event("mozbrowserasyncscroll")}} Firefox OS Browser API-specificSent when the scroll position within a browser {{HTMLElement("iframe")}} changes.
{{event("mozbrowseraudioplaybackchange")}} Firefox OS Browser API-specificSent when audio starts or stops playing within the browser {{HTMLElement("iframe")}} content.
{{event("mozbrowsercaretstatechanged")}} Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes.
{{event("mozbrowserclose")}} Firefox OS Browser API-specificSent when window.close() is called within a browser {{HTMLElement("iframe")}}.
{{event("mozbrowsercontextmenu")}} Firefox OS Browser API-specificSent when a browser {{HTMLElement("iframe")}} try to open a context menu.
{{event("mozbrowserdocumentfirstpaint")}} Firefox OS Browser API-specificSent when a new paint occurs on any document in the browser {{HTMLElement("iframe")}}.
{{event("mozbrowsererror")}} Firefox OS Browser API-specificSent when an error occured while trying to load a content within a browser iframe
{{event("mozbrowserfindchange")}} Firefox OS Browser API-specificSent when a search operation is performed on the browser {{HTMLElement("iframe")}} content (see HTMLIFrameElement search methods.)
{{event("mozbrowserfirstpaint")}} Firefox OS Browser API-specificSent when the {{HTMLElement("iframe")}} paints content for the first time (this doesn't include the initial paint from about:blank.)
{{event("mozbrowsericonchange")}} Firefox OS Browser API-specificSent when the favicon of a browser iframe changes.
{{event("mozbrowserlocationchange")}} Firefox OS Browser API-specificSent when an browser iframe's location changes.
{{event("mozbrowserloadend")}} Firefox OS Browser API-specificSent when the browser iframe has finished loading all its assets.
{{event("mozbrowserloadstart")}} Firefox OS Browser API-specificSent when the browser iframe starts to load a new page.
{{event("mozbrowsermanifestchange")}} Firefox OS Browser API-specificSent when a the path to the app manifest changes, in the case of a browser {{HTMLElement("iframe")}} with an open web app embedded in it.
{{event("mozbrowsermetachange")}} Firefox OS Browser API-specificSent when a {{htmlelement("meta")}} elelment is added to, removed from or changed in the browser {{HTMLElement("iframe")}}'s content.
{{event("mozbrowseropensearch")}} Firefox OS Browser API-specificSent when a link to a search engine is found.
{{event("mozbrowseropentab")}} Firefox OS Browser API-specificSent when a new tab is opened within a browser {{HTMLElement("iframe")}} as a result of the user issuing a command to open a link target in a new tab (for example ctrl/cmd + click.)
{{event("mozbrowseropenwindow")}} Firefox OS Browser API-specificSent when {{domxref("window.open()")}} is called within a browser iframe.
{{event("mozbrowserresize")}} Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}}'s window size has changed.
{{event("mozbrowserscroll")}} Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}} content scrolls.
{{event("mozbrowserscrollareachanged")}} Firefox OS Browser API-specificSent when the available scrolling area  in the browser {{HTMLElement("iframe")}} changes. This can occur on resize and when the page size changes (while loading for example.)
{{event("mozbrowserscrollviewchange")}} Firefox OS Browser API-specificSent when asynchronous scrolling (i.e. APCZ) starts or stops.
{{event("mozbrowsersecuritychange")}} Firefox OS Browser API-specificSent when the SSL state changes within a browser iframe.
{{event("mozbrowserselectionstatechanged")}} Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes. Note that this is deprecated, and newer implementations use {{event("mozbrowsercaretstatechanged")}} instead.
{{event("mozbrowsershowmodalprompt")}} Firefox OS Browser API-specificSent when {{domxref("window.alert","alert()")}}, {{domxref("window.confirm","confirm()")}} or {{domxref("window.prompt","prompt()")}} are called within a browser iframe
{{event("mozbrowsertitlechange")}} Firefox OS Browser API-specificSent when the document.title changes within a browser iframe.
{{event("mozbrowserusernameandpasswordrequired")}} Firefox OS Browser API-specificSent when an HTTP authentification is requested.
{{event("mozbrowservisibilitychange")}} Firefox OS Browser API-specificSent when the visibility state of the current browser iframe {{HTMLElement("iframe")}} changes, for example due to a call to {{domxref("HTMLIFrameElement.setVisible","setVisible()")}}.
{{event("MozGamepadButtonDown")}} To be specifiedA gamepad button is pressed down.
{{event("MozGamepadButtonUp")}} To be specifiedA gamepad button is released.
{{event("MozMousePixelScroll")}} {{deprecated_inline}} Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of pixels). (use wheel instead)
{{event("MozOrientation")}} {{deprecated_inline}} Mozilla specificFresh data is available from an orientation sensor (see deviceorientation).
{{event("MozScrolledAreaChanged")}}{{domxref("UIEvent")}}Mozilla specificThe document view has been scrolled or resized.
{{event("moztimechange")}} Mozilla specificThe time of the device has been changed.
MozTouchDown {{deprecated_inline}} Mozilla specificA touch point is placed on the touch surface (use touchstart instead).
MozTouchMove {{deprecated_inline}} Mozilla specificA touch point is moved along the touch surface (use touchmove instead).
MozTouchUp {{deprecated_inline}} Mozilla specificA touch point is removed from the touch surface (use touchend instead).
{{event("alerting")}}{{domxref("CallEvent")}}To be specifiedThe correspondent is being alerted (his/her phone is ringing).
{{event("busy")}}{{domxref("CallEvent")}}To be specifiedThe line of the correspondent is busy.
{{event("callschanged")}}{{domxref("CallEvent")}}To be specifiedA call has been added or removed from the list of current calls.
onconnected {{event("connected")}}{{domxref("CallEvent")}}To be specifiedA call has been connected.
{{event("connecting")}}{{domxref("CallEvent")}}To be specifiedA call is about to connect.
{{event("delivered")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been successfully delivered.
{{event("dialing")}}{{domxref("CallEvent")}}To be specifiedThe number of a correspondent has been dialed.
{{event("disabled")}} Firefox OS specificWifi has been disabled on the device.
{{event("disconnected")}}{{domxref("CallEvent")}}To be specifiedA call has been disconnected.
{{event("disconnecting")}}{{domxref("CallEvent")}}To be specifiedA call is about to disconnect.
{{event("enabled")}} Firefox OS specificWifi has been enabled on the device.
{{event("error_(Telephony)","error")}}{{domxref("CallEvent")}}To be specifiedAn error occurred.
{{event("held")}}{{domxref("CallEvent")}}To be specifiedA call has been held.
{{event("holding")}}{{domxref("CallEvent")}}To be specifiedA call is about to be held.
{{event("incoming")}}{{domxref("CallEvent")}}To be specifiedA call is being received.
{{event("received")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been received.
{{event("resuming")}}{{domxref("CallEvent")}}To be specifiedA call is about to resume.
{{event("sent")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been sent.
{{event("statechange")}}{{domxref("CallEvent")}}To be specifiedThe state of a call has changed.
{{event("statuschange")}} Firefox OS specificThe status of the Wifi connection changed.
{{event("overflow")}}{{domxref("UIEvent")}}Mozilla specificAn element has been overflowed by its content or has been rendered for the first time in this state (only works for elements styled with overflow != visible).
{{event("smartcard-insert")}} Mozilla specificA smartcard has been inserted.
{{event("smartcard-remove")}} Mozilla specificA smartcard has been removed.
{{event("stkcommand")}} Firefox OS specificThe STK Proactive Command is issued from ICC.
{{event("stksessionend")}} Firefox OS specificThe STK Session is terminated by ICC.
text Mozilla SpecificA generic composition event occurred.
{{event("underflow")}}{{domxref("UIEvent")}}Mozilla specificAn element is no longer overflowed by its content (only works for elements styled with overflow != visible).
uploadprogress {{deprecated_inline}}{{domxref("ProgressEvent")}}Mozilla SpecificUpload is in progress (see {{event("progress")}}).
+

{{event("ussdreceived")}}

+
 Firefox OS specificA new USSD message is received
{{event("voicechange")}} Firefox OS specificThe {{domxref("MozMobileConnection.voice")}} object changes values.
+ +

Mozilla-specific events

+ +
+

Note: those events are never exposed to web content and can only be used in chrome content context.

+
+ +

XUL events

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Event NameEvent TypeSpecificationFired when...
{{event("broadcast")}} XULAn observer noticed a change to the attributes of a watched broadcaster.
{{event("CheckboxStateChange")}} XULThe state of a checkbox has been changed either by a user action or by a script (useful for accessibility).
close XULThe close button of the window has been clicked.
{{event("command")}} XULAn element has been activated.
{{event("commandupdate")}} XULA command update occurred on a commandset element.
{{event("DOMMenuItemActive")}} XULA menu or menuitem has been hovered or highlighted.
{{event("DOMMenuItemInactive")}} XULA menu or menuitem is no longer hovered or highlighted.
{{event("popuphidden")}}PopupEventXULA menupopup, panel or tooltip has been hidden.
{{event("popuphiding")}}PopupEventXULA menupopup, panel or tooltip is about to be hidden.
{{event("popupshowing")}}PopupEventXULA menupopup, panel or tooltip is about to become visible.
{{event("popupshown")}}PopupEventXULA menupopup, panel or tooltip has become visible.
{{event("RadioStateChange")}} XULThe state of a radio has been changed either by a user action or by a script (useful for accessibility).
{{event("ValueChange")}} XULThe value of an element has changed (a progress bar for example, useful for accessibility).
+ +

Add-on-specific events

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Event NameEvent TypeSpecificationFired when...
MozSwipeGesture Addons specificA touch point is swiped across the touch surface
MozMagnifyGestureStart Addons specificTwo touch points start to move away from each other.
MozMagnifyGestureUpdate Addons specificTwo touch points move away from each other (after a MozMagnifyGestureStart).
MozMagnifyGesture Addons specificTwo touch points moved away from each other (after a sequence of MozMagnifyGestureUpdate).
MozRotateGestureStart Addons specificTwo touch points start to rotate around a point.
MozRotateGestureUpdate Addons specificTwo touch points rotate around a point (after a MozRotateGestureStart).
MozRotateGesture Addons specificTwo touch points rotate around a point (after a sequence of MozRotateGestureUpdate).
MozTapGesture Addons specificTwo touch points are tapped on the touch surface.
MozPressTapGesture Addons specificA "press-tap" gesture happened on the touch surface (first finger down, second finger down, second finger up, first finger up).
MozEdgeUIGesture Addons specificA touch point is swiped across the touch surface to invoke the edge UI (Win8 only).
MozAfterPaint Addons specificContent has been repainted.
DOMPopupBlocked Addons specificA popup has been blocked
DOMWindowCreated Addons specificA window has been created.
DOMWindowClose Addons specificA window is about to be closed.
DOMTitleChanged Addons specifcThe title of a window has changed.
DOMLinkAdded Addons specifcA link has been added a document.
DOMLinkRemoved Addons specifcA link has been removed inside from a document.
DOMMetaAdded Addons specificA meta element has been added to a document.
DOMMetaRemoved Addons specificA meta element has been removed from a document.
DOMWillOpenModalDialog Addons specificA modal dialog is about to open.
DOMModalDialogClosed Addons specificA modal dialog has been closed.
DOMAutoComplete Addons specificThe content of an element has been auto-completed.
DOMFrameContentLoaded Addons specificThe frame has finished loading (but not its dependent resources).
AlertActive Addons specificA notification element is shown.
AlertClose Addons specificA notification element is closed.
fullscreen Addons specificBrowser fullscreen mode has been entered or left.
sizemodechange Addons specificWindow has entered/left fullscreen mode, or has been minimized/unminimized.
MozEnteredDomFullscreen Addons specificDOM fullscreen mode has been entered.
SSWindowClosing Addons specificThe session store will stop tracking this window.
SSTabClosing Addons specificThe session store will stop tracking this tab.
SSTabRestoring Addons specificA tab is about to be restored.
SSTabRestored Addons specificA tab has been restored.
SSWindowStateReady Addons specificA window state has switched to "ready".
SSWindowStateBusy Addons specificA window state has switched to "busy".
tabviewsearchenabled Addons specificThe search feature of Panorama has been activated
tabviewsearchdisabled Addons specificThe search feature of Panorama has been deactivated
tabviewframeinitialized Addons specificThe frame container of Panorama has been initialized
tabviewshown Addons specificThe Panorama tab has been shown
tabviewhidden Addons specificThe Panorama tab has been hidden
TabOpen Addons specificA tab has been opened.
TabClose Addons specificA tab has been closed.
TabSelect Addons specificA tab has been selected.
TabShow Addons specificA tab has been shown.
TabHide Addons specificA tab has been hidden.
TabPinned Addons specificA tab has been pinned.
TabUnpinned Addons specificA tab has been unpinned.
+ +

Developer tool-specific events

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Event NameEvent TypeSpecificationFired when...
CssRuleViewRefreshed devtools specificThe "Rules" view of the style inspector has been updated.
CssRuleViewChanged devtools specificThe "Rules" view of the style inspector has been changed.
CssRuleViewCSSLinkClicked devtools specificA link to a CSS file has been clicked in the "Rules" view of the style inspector.
+ +

Categories

+ +

Animation events

+ +

{{event("animationend")}}, {{event("animationiteration")}}, {{event("animationstart")}}, {{event("beginEvent")}}, {{event("endEvent")}}, {{event("repeatEvent")}}

+ +

Battery events

+ +

{{event("chargingchange")}} {{event("chargingtimechange")}}, {{event("dischargingtimechange")}} {{event("levelchange")}}

+ +

Call events

+ +

{{event("alerting")}}, {{event("busy")}}, {{event("callschanged")}} {{event("cfstatechange")}}, {{event("connected")}}, {{event("connecting")}}, {{event("dialing")}}, {{event("disconnected")}}, {{event("disconnecting")}}, {{event("error_(Telephony)","error")}}, {{event("held")}}, {{event("holding")}}, {{event("incoming")}}, {{event("resuming")}}, {{event("statechange")}}, {{event("voicechange")}}

+ +

CSS events

+ +

CssRuleViewRefreshed, CssRuleViewChanged, CssRuleViewCSSLinkClicked, {{event("transitionend")}}

+ +

Database events

+ +

abort, blocked, complete, {{event("error")}} (link), success, upgradeneeded, versionchange

+ +

Document events

+ +

DOMLinkAdded, DOMLinkRemoved, DOMMetaAdded, DOMMetaRemoved, DOMWillOpenModalDialog, DOMModalDialogClosed, {{event("unload")}}

+ +

DOM mutation events

+ +

DOMAttributeNameChanged, DOMAttrModified, DOMCharacterDataModified, {{event("DOMContentLoaded")}}, DOMElementNameChanged, DOMNodeInserted, DOMNodeInsertedIntoDocument, DOMNodeRemoved, DOMNodeRemovedFromDocument, DOMSubtreeModified

+ +

Drag events

+ +

{{event("drag")}}, dragdrop, {{event("dragend")}}, {{event("dragenter")}}, dragexit, draggesture, {{event("dragleave")}}, {{event("dragover")}}, {{event("dragstart")}}, {{event("drop")}}

+ +

Element events

+ +

{{event("invalid")}}, {{event("overflow")}}, {{event("underflow")}}, DOMAutoComplete, {{event("command")}}, {{event("commandupdate")}}

+ +

Focus events

+ +

{{event("blur")}}, {{event("change")}}, DOMFocusIn, DOMFocusOut, {{event("focus")}}, {{event("focusin")}}, {{event("focusout")}}

+ +

Form events

+ +

{{event("reset")}}, {{event("submit")}}

+ +

Frame events

+ +

{{event("mozbrowserclose")}}, {{event("mozbrowsercontextmenu")}}, {{event("mozbrowsererror")}}, {{event("mozbrowsericonchange")}}, {{event("mozbrowserlocationchange")}}, {{event("mozbrowserloadend")}}, {{event("mozbrowserloadstart")}}, {{event("mozbrowseropenwindow")}}, {{event("mozbrowsersecuritychange")}}, {{event("mozbrowsershowmodalprompt")}} (link), {{event("mozbrowsertitlechange")}}, DOMFrameContentLoaded

+ +

Input device events

+ +

{{event("click")}}, {{event("contextmenu")}}, {{event("DOMMouseScroll")}}, {{event("dblclick")}}, {{event("gamepadconnected")}}, {{event("gamepaddisconnected")}}, {{event("keydown")}}, {{event("keypress")}}, {{event("keyup")}}, {{event("MozGamepadButtonDown")}}, {{event("MozGamepadButtonUp")}}, {{event("mousedown")}}, {{event("mouseenter")}}, {{event("mouseleave")}}, {{event("mousemove")}}, {{event("mouseout")}}, {{event("mouseover")}}, {{event("mouseup")}}, {{event("mousewheel")}}, {{event("MozMousePixelScroll")}}, {{event("pointerlockchange")}}, {{event("pointerlockerror")}},{{event("wheel")}}

+ +

Media events

+ +

{{event("audioprocess")}}, {{event("canplay")}}, {{event("canplaythrough")}}, {{event("durationchange")}}, {{event("emptied")}}, {{event("ended")}}, {{event("ended_(Web_Audio)", "ended")}}, {{event("loadeddata")}}, {{event("loadedmetadata")}}, {{event("MozAudioAvailable")}}, {{event("pause")}}, {{event("play")}}, {{event("playing")}}, {{event("ratechange")}}, {{event("seeked")}}, {{event("seeking")}}, {{event("stalled")}}, {{event("suspend")}}, {{event("timeupdate")}}, {{event("volumechange")}}, {{event("waiting")}}, {{event("complete")}}

+ + + +

{{event("DOMMenuItemActive")}}, {{event("DOMMenuItemInactive")}}

+ +

Network events

+ +

{{event("datachange")}}, {{event("dataerror")}}, {{event("disabled")}}, {{event("enabled")}}, {{event("offline")}}, {{event("online")}}, {{event("statuschange")}}, {{event("connectionInfoUpdate")}},

+ +

Notification events

+ +

AlertActive, AlertClose

+ +

Pointer events

+ +

{{event("pointerover")}}, {{event("pointerenter")}}, {{event("pointerdown")}}, {{event("pointermove")}}, {{event("pointerup")}}, {{event("pointercancel")}}, {{event("pointerout")}}, {{event("pointerleave")}}, {{event("gotpointercapture")}}, {{event("lostpointercapture")}}

+ + + +

{{event("popuphidden")}}, {{event("popuphiding")}}, {{event("popupshowing")}}, {{event("popupshown")}}, DOMPopupBlocked

+ +

Printing events

+ +

{{event("afterprint")}}, {{event("beforeprint")}}

+ +

Progress events

+ +

abort, {{event("error")}}, load, {{event("loadend")}}, {{event("loadstart")}}, {{event("progress")}}, progress, {{event("timeout")}}, uploadprogress

+ +

Resource events

+ +

{{event("abort")}}, {{event("cached")}}, {{event("error")}}, {{event("load")}}

+ +

Script events

+ +

{{event("afterscriptexecute")}}, {{event("beforescriptexecute")}}

+ +

Sensor events

+ +

{{event("compassneedscalibration")}}, {{event("devicelight")}}, {{event("devicemotion")}}, {{event("deviceorientation")}}, {{event("deviceproximity")}}, {{event("MozOrientation")}}, {{event("orientationchange")}}, {{event("userproximity")}}

+ +

Session history events

+ +

{{event("pagehide")}}, {{event("pageshow")}}, {{event("popstate")}}

+ +

Smartcard events

+ +

{{event("icccardlockerror")}}, {{event("iccinfochange")}}, {{event("smartcard-insert")}}, {{event("smartcard-remove")}}, {{event("stkcommand")}}, {{event("stksessionend")}}, {{event("cardstatechange")}}

+ +

SMS and USSD events

+ +

{{event("delivered")}}, {{event("received")}}, {{event("sent")}}, {{event("ussdreceived")}}

+ +

Storage events

+ +

{{event("change")}} (see {{anch("Non-standard events")}}), {{event("storage")}}

+ +

SVG events

+ +

{{event("SVGAbort")}}, {{event("SVGError")}}, {{event("SVGLoad")}}, {{event("SVGResize")}}, {{event("SVGScroll")}}, {{event("SVGUnload")}}, {{event("SVGZoom")}}

+ +

Tab events

+ +

tabviewsearchenabled, tabviewsearchdisabled, tabviewframeinitialized, tabviewshown, tabviewhidden, TabOpen, TabClose, TabSelect, TabShow, TabHide, TabPinned, TabUnpinned, SSTabClosing, SSTabRestoring, SSTabRestored, {{event("visibilitychange")}}

+ +

Text events

+ +

{{event("compositionend")}}, {{event("compositionstart")}}, {{event("compositionupdate")}}, {{event("copy")}}, {{event("cut")}}, {{event("paste")}}, {{event("select")}}, text

+ +

Touch events

+ +

MozEdgeUIGesture, MozMagnifyGesture, MozMagnifyGestureStart, MozMagnifyGestureUpdate, MozPressTapGesture, MozRotateGesture, MozRotateGestureStart, MozRotateGestureUpdate, MozSwipeGesture, MozTapGesture, MozTouchDown, MozTouchMove, MozTouchUp, {{event("touchcancel")}}, {{event("touchend")}}, {{event("touchenter")}}, {{event("touchleave")}}, {{event("touchmove")}}, {{event("touchstart")}}

+ +

Update events

+ +

{{event("checking")}}, {{event("downloading")}}, {{event("error")}}, {{event("noupdate")}}, {{event("obsolete")}}, {{event("updateready")}}

+ +

Value change events

+ +

{{event("broadcast")}}, {{event("CheckboxStateChange")}}, {{event("hashchange")}}, {{event("input")}}, {{event("RadioStateChange")}}, {{event("readystatechange")}}, {{event("ValueChange")}}

+ +

View events

+ +

fullscreen, {{event("fullscreenchange")}}, {{event("fullscreenerror")}}, MozEnteredDomFullscreen, {{event("MozScrolledAreaChanged")}}, {{event("resize")}}, {{event("scroll")}}, sizemodechange

+ +

Websocket events

+ +

close, {{event("error")}}, message, open

+ +

Window events

+ +

DOMWindowCreated, DOMWindowClose, DOMTitleChanged, MozBeforeResize {{obsolete_inline}}, SSWindowClosing, SSWindowStateReady, SSWindowStateBusy, close

+ +

Uncategorized events

+ +

{{event("beforeunload")}}, {{event("localized")}}, message, message, message, MozAfterPaint, {{event("moztimechange")}}, open, {{event("show")}}

+ +

See also

+ + diff --git a/files/id/web/guide/api/index.html b/files/id/web/guide/api/index.html new file mode 100644 index 0000000000..4e0e34c483 --- /dev/null +++ b/files/id/web/guide/api/index.html @@ -0,0 +1,26 @@ +--- +title: Guide to Web APIs +slug: Web/Guide/API +tags: + - API + - Guide + - Landing + - NeedsTranslation + - TopicStub + - Web +translation_of: Web/Guide/API +--- +

Here you'll find links to each of the guides introducing and explaining each of the APIs that make up the Web development architecture.

+ +

Web APIs from A to Z

+ +

{{ListGroups}}

+ +

See also

+ + diff --git a/files/id/web/guide/api/webrtc/index.html b/files/id/web/guide/api/webrtc/index.html new file mode 100644 index 0000000000..93c1a489eb --- /dev/null +++ b/files/id/web/guide/api/webrtc/index.html @@ -0,0 +1,34 @@ +--- +title: WebRTC +slug: Web/Guide/API/WebRTC +translation_of: Web/API/WebRTC_API +--- +

WebRTC (RTC mengacu pada Real-Time Communications) adalah sebuah teknologi yang memungkinkan pengiriman audio atau video serta berbagi data antar peramban web (peer). Sebagai sebuah standar, WebRTC menghadirkan fitur pada peramban web untuk berbagi data dan melakukan telekonferensi secara peer-to-peer, tanpa perlu memasang plugins atau aplikasi pihak ketiga.

+ +

Komponen WebRTC dapat diakses melalui JavaScript API, di antaranya: Nework Stream API, yang merepresentasikan audio atau video dalam bentuk data stream; PeerConnection API, yang memungkinkan dua atau lebih pengguna untuk berkomunikasi langsung melalui peramban web; dan DataChannel API, yang memungkinkan bentuk komunikasi lainnya secara real-time untuk gamingtext chatfile transfer, dan lainnya.

+ +
+

Catatan: Dokumentasi ini sedang dalam proses pemindahan ke laman baru.

+
+ +

Panduan

+ +
+
Komunikasi peer-to-peer pada WebRTC
+
Bagaimana cara melakukan komunikasi peer-to-peer menggunakan WebRTC API.
+
Pengantar arsitektur WebRTC
+
WebRTC memiliki banyak bagian di dalamnya, dan itu sangat membingungkan. Artikel ini bertujuan untuk menjelaskan bagian-bagian tersebut, dan bagaimana semuanya bekerja.
+
Dasar-dasar WebRTC
+
Setelah Anda memahami arsitektur WebRTC, Anda dapat melanjutkan ke artikel selanjutnya yang akan menjelaskan proses pengembangan aplikasi dasar RTC yang bekerja pada peramban web.
+
+ +

Referensi

+ +
+
Navigator.getUserMedia
+
API yang berfungsi untuk menangkap media (audio atau video).
+
RTCPeerConnection
+
Antarmuka yang berfungsi untuk menangani data streaming antar dua peer.
+
RTCDataChannel
+
Antarmuka yang berfungsi untuk mengirimkan data antar peer.
+
diff --git a/files/id/web/guide/css/getting_started/index.html b/files/id/web/guide/css/getting_started/index.html new file mode 100644 index 0000000000..c37ce973fa --- /dev/null +++ b/files/id/web/guide/css/getting_started/index.html @@ -0,0 +1,32 @@ +--- +title: Getting started with CSS +slug: Web/Guide/CSS/Getting_started +translation_of: Learn/CSS/First_steps +--- +

This tutorial introduces you to the basic features and language (the syntax) for Cascading Style Sheets (CSS). You use CSS to change the look of a structured document, such as a web page. The tutorial also includes sample exercises you can try on your own computer to see the effects of CSS and features that work in modern browsers.

+

The tutorial is for beginners and anyone who would like to review the basics of CSS. If you have more experience with CSS, the CSS main page lists more advanced resources.

+ +

What you need to get started

+ +

Although the exercises can help you learn, you are not required to complete them. You can simply read the tutorial and look at the pictures.

+

Note: The tutorial covers how CSS works with color. It will be easier to complete these sections with a color display and normal color vision.

+

How to use this tutorial

+

To use this tutorial, read the pages carefully and in sequence. If you skip a page, it may be difficult to understand pages later in the tutorial.

+

Part I: The Basics of CSS

+

On each page, use the Information section to understand how CSS works. Use the Action section to try using CSS on your own computer.

+

To test your understanding, take the challenge at the end of each page. Solutions to the challenges are linked under the challenges, so you don't need to look at them if you don't want to.

+

To understand CSS in more depth, read the information that you find in boxes captioned More details. Use the links there to find reference information about CSS.

+

Part II: The Scope of CSS

+

A second part of the tutorial provides examples, which show the scope of CSS with other web and Mozilla technologies.

+
    +
  1. JavaScript
  2. +
  3. SVG graphics
  4. +
  5. XML data
  6. +
  7. XBL bindings
  8. +
  9. XUL user interfaces
  10. +
diff --git a/files/id/web/guide/css/media_queries/index.html b/files/id/web/guide/css/media_queries/index.html new file mode 100644 index 0000000000..3fe883c5f6 --- /dev/null +++ b/files/id/web/guide/css/media_queries/index.html @@ -0,0 +1,630 @@ +--- +title: Media query CSS +slug: Web/Guide/CSS/Media_queries +translation_of: Web/CSS/Media_Queries/Using_media_queries +--- +

Media query terdiri dari jenis media dan paling sedikit satu ekspresi yang membatasi lingkup style sheets dengan menggunakan fitur media, seperti lebar, tinggi, dan warna. Media query, ditambahkan di CSS3, memungkinkan tampilan konten disesuaikan dengan alat penampil tertentu tanpa harus mengubah konten itu sendiri.

+ +

Sintaks

+ +

Media query terdiri dari jenis media (media type) dan dapat, sesuai dengan spesifikasi CSS3, mengandung satu atau lebih ekspresi, diekspresikan sebagai fitur media, baik benar (true) atau salah (false).  Hasil query adalah benar jika jenis media yang disebutkan dalam media query cocok dengan jenis alat yang digunakan untuk menampilkan dokumen dan semua ekspresi di dalam media query adalah benar.

+ +
<!-- Media query CSS pada elemen link -->
+<link rel="stylesheet" media="(max-width: 800px)" href="example.css" />
+
+<!-- Media query CSS di dalam style sheet -->
+<style>
+@media (max-width: 600px) {
+  .facet_sidebar {
+    display: none;
+  }
+}
+</style>
+ +

Ketika sebuah media query adalah benar, style sheet atau aturan style yang bersangkutan diterapkan, sesuai dengan aturan cascading normal. Style sheet dengan media query yang menempel pada tag <link> masih akan diunduh bahkan jika media query tersebut adalah salah (false) (namun tidak akan diterapkan).

+ +

Kecuali jika Anda menggunakan operator not atau only, jenis media adalah opsional dan jenis all akan diterapkan.

+ +

Operator logika

+ +

Anda dapat merancang media query kompleks menggunakan operator logika, termasuk not, and, dan only. Operator and digunakan untuk menggabungkan banyak fitur media (media features) ke dalam satu media query tunggal, setiap fitur terkait harus benar (true) agar query benar (true). Operator not digunakan untuk menegasikan keseluruhan media query. Operator only digunakan untuk menerapkan suatu style hanya jika keseluruhan query cocok, berguna untuk mencegah browser lama menerapkan style-style tertentu. Jika Anda menggunakan operator-operator not atau only, Anda harus menyebutkan jenis media secara eksplisit.

+ +

Anda juga dapat menggabungkan banyak media query dalam sebuah daftar terpisah koma; jika ada media query di dalam daftar yang benar (true), keseluruhan pernyataan media adalah benar (true). Hal ini setara dengan operator or.

+ +

and

+ +

Kata kunci and digunakan untuk menggabungkan banyak fitur media menjadi satu, seperti menggabungkan fitur media dengan jenis media. Media query dasar, sebuah fitur media tunggal dengan jenis media all secara implisit, dapat terlihat seperti ini:

+ +
@media (min-width: 700px) { ... }
+ +

Namun, jika, Anda menginginkan hal ini diterapkan hanya untuk tampilan lanskap, Anda dapat menggunakan operator and untuk menggabungkan fitur-fitur media tersebut.

+ +
@media (min-width: 700px) and (orientation: landscape) { ... }
+ +

Sekarang media query di atas hanya akan benar jika lebar viewport adalah 700px atau lebih dan dalam tampilan lanskap. Namun, jika, Anda hanya menginginkan hal ini untuk diterapkan jika jenis media tampilan adalah TV, Anda dapat menggabungkan fitur-fitur ini dengan jenis media menggunakan operator and.

+ +
@media tv and (min-width: 700px) and (orientation: landscape) { ... }
+ +

Sekarang, media query di atas hanya akan diterapkan jika jenis media adalah TV, lebar viewport adalah 700px atau lebih, dan tampilan adalah lanskap.

+ +

daftar terpisah koma

+ +

Daftar terpisah koma adalah seperti operator logika or ketika digunakan dalam media query. Ketika menggunakan daftar media query terpisah koma, jika ada media query yang benar (true), style or style sheet akan diterapkan. Setiap media query di dalam daftar terpisah koma diperlakukan sebagai query individual, dan setiap operator yang diterapkan pada satu media query tidak mempengaruhi yang lainnya. Ini berarti daftar media query terpisah koma dapat ditujukan  untuk fitur, jenis, dan kondisi media yang berbeda.

+ +

Sebagai contoh, seandainya Anda ingin menerapkan seperangkat style jika alat penampil memiliki lebar minimum 700px atau alat genggam dalam moda lanskap, Anda dapat menulis sebagai berikut:

+ +
@media (min-width: 700px), handheld and (orientation: landscape) { ... }
+ +

Pada contoh di atas, jika saya menggunakan perangkat screen dengan lebar viewport 800px, pernyataan media akan benar (true) karena bagian pertama, yang diinterpetasikan sebagai @media all and (min-width: 700px) akan berlaku pada perangkat saya dan oleh karena itu benar (true), terlepas dari fakta bahwa perangkat screen saya akan gagal dalam pengecekan jenis media handheld di media query kedua. Demikian pula, jika saya menggunakan perangkat genggam handheld dalam moda lanskap dengan lebar viewport 500px, walaupun media query pertama gagal karena lebar viewport tidak sesuai, media query kedua akan berhasil dan oleh karena itu pernyataan media akan menghasilkan nilai benar (true).

+ +

not

+ +

Kata kunci not berlaku pada keseluruhan media query dan memberikan nilai benar (true) jika media query akan sebaliknya memberikan nilai salah (false) (seperti fitur query monochrome pada warna tampilan atau lebar layar 600px dengan min-width: 700px). Sebuah not hanya akan menegasikan media query yang ditetapkan dan bukan setiap media query jika ada dalam daftar media query terpisah koma. Kata kunci not tidak dapat digunakan untuk menegasikan sebuah fitur query individual, hanya untuk media query secara keseluruhan. Sebagai contoh, not dievaluasi paling akhir dalam query berikut ini:

+ +
@media not all and (monochrome) { ... }
+
+ +

Ini berarti bahwa query tersebut dievaluasi seperti ini:

+ +
@media not (all and (monochrome)) { ... }
+
+ +

... bukan seperti ini:

+ +
@media (not all) and (monochrome) { ... }
+ +

Sebagai contoh lain, lihat media query berikut ini:

+ +
@media not screen and (color), print and (color)
+
+ +

Yang dievaluasi seperti ini:

+ +
@media (not (screen and (color))), print and (color)
+ +

only

+ +

Kata kunci only mencegah browser lama yang tidak mendukung media query dengan fitur media menerapkan style yang disediakan:

+ +
<link rel="stylesheet" media="only screen and (color)" href="example.css" />
+
+ +

Pseudo-BNF (untuk Anda yang gemar hal seperti ini)

+ +
media_query_list: <media_query> [, <media_query> ]*
+media_query: [[only | not]? <media_type> [ and <expression> ]*]
+  | <expression> [ and <expression> ]*
+expression: ( <media_feature> [: <value>]? )
+media_type: all | aural | braille | handheld | print |
+  projection | screen | tty | tv | embossed
+media_feature: width | min-width | max-width
+  | height | min-height | max-height
+  | device-width | min-device-width | max-device-width
+  | device-height | min-device-height | max-device-height
+  | aspect-ratio | min-aspect-ratio | max-aspect-ratio
+  | device-aspect-ratio | min-device-aspect-ratio | max-device-aspect-ratio
+  | color | min-color | max-color
+  | color-index | min-color-index | max-color-index
+  | monochrome | min-monochrome | max-monochrome
+  | resolution | min-resolution | max-resolution
+  | scan | grid
+ +

Media query adalah case insensitive.  Media query yang melibatkan jenis media yang tidak diketahui selalu salah (false).

+ +
Catatan: Tanda kurung wajib digunakan di sekitar ekspresi; jika tidak digunakan akan mengakibatkan kesalahan.
+ +

Fitur media

+ +

Sebagian besar fitur media dapat diawali dengan "min-" atau "max-" untuk mengekspresikan batasan "lebih dari atau sama dengan" atau "kurang dari atau sama dengan".  Hal ini menghindari penggunaan simbol "<" dan ">", yang mungkin akan menyebabkan konflik dengan HTML dan XML.  Jika Anda  menggunakan fitur media tanpa nilai tertentu, ekspresi tersebut akan bernilai benar (true) jika nilai fitur adalah bukan-nol.

+ +
Catatan: Jika sebuah fitur media tidak sesuai untuk alat di mana browser dijalankan, ekspresi yang melibatkan fitur media tersebut adalah selalu salah (false).  Sebagai contoh, meng-query rasio aspek dari suatu alat aural selalu bernilai salah (false).
+ +

color

+ +

Nilai: {{cssxref("<color>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Menerima prefiks min/max prefixes: ya

+ +

Menunjukkan jumlah per komponen warna dari alat penampil.  Jika alat tersebut bukan alat yang memiliki warna, nilai ini adalah nol.

+ +
Catatan: Jika komponen warna memiliki jumlah bit yang berbeda per komponen warna, angka yang paling kecillah yang digunakan.  Sebagai contoh, jika sebuat layar menggunakan 5 bit untuk biru dan merah dan 6 bit untuk hijau, maka alat tersebut dianggap menggunakan 5 bit per komponen warna.  Jika suat alat menggunakan warna terindeks, jumlah bit minimum per komponen warna dalam tabel warna yang digunakan.
+ +

Contoh

+ +

Untuk menerapkan style sheet pada semua alat berwarna:

+ +
@media all and (color) { ... }
+
+ +

Untuk menerapkan style sheet pada alat yang memiliki paling sedikit 4 bit per komponen warna:

+ +
@media all and (min-color: 4) { ... }
+
+ +

color-index

+ +

Nila: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Menerima prefiks min/max: ya

+ +

Menunjukkan jumlah entri dalam tabel pencarian warna untuk alat penampil.

+ +

Contoh

+ +

Untuk menunjukkan bahwa suatu style sheet harus diterapkan pada semua alat yang menggunakan warna terindeks, Anda dapat melakukan:

+ +
@media all and (color-index) { ... }
+
+ +

Untuk menerapkan style sheet pada alat berwarna terindeks dengan paling sedikit 256 warna:

+ +
<link rel="stylesheet" media="all and (min-color-index: 256)" href="http://foo.bar.com/stylesheet.css" />
+
+ +

aspect-ratio

+ +

Nilai: {{cssxref("<ratio>")}}
+ Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
+ Menerima prefiks min/max: ya

+ +

Menggambarkan rasio aspek daerah tampilan dari alat penampil.  Nilai ini terdiri dari dua integer positif dipisahkan oleh karakter garis miring ("/").  Ini menunjukkan rasio piksel horisontal (angka pertama) terhadap piksel vertikal (angka kedua).

+ +

Contoh

+ +

Berikut ini memilih style sheet khusus untuk digunakan ketika daerah tampilan paling tidak selebar tingginya.

+ +
@media screen and (min-aspect-ratio: 1/1) { ... }
+ +

Ini memilih style ketika rasio aspek adalah 1:1 atau lebih. Dengan kata lain, style-style ini hanya akan diterapkan ketika area penampil adalah bujursangkar atau lanskap.

+ +

device-aspect-ratio

+ +

Nilai: {{cssxref("<ratio>")}}
+ Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
+ Menerima prefiks min/max: ya

+ +

Menggambarkan rasio aspek dari alat penampil.  Nilai ini terdiri dari dua integer positif dipisahkan oleh karakter garis miring ("/").  Hal ini menunjukkan rasio piksel horisontal (yang pertama) terhadap piksel vertikal (yang kedua).

+ +

Contoh

+ +

Berikut ini memilih style sheet khusus yang digunakan untuk tampilan layar lebar.

+ +
@media screen and (device-aspect-ratio: 16/9), screen and (device-aspect-ratio: 16/10) { ... }
+ +

Ini memilih style ketika rasio aspek adalah 16:9 atau 16:10.

+ +

device-height

+ +

Nilai: {{cssxref("<length>")}}
+ Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
+ Menerima prefiks min/max: ya

+ +

Menggambarkan tinggi alat penampil (berarti keseluruhan layar atau halaman, bukan hanya area render, seperti jendela dokumen).

+ +

Contoh

+ +

Untuk menerapkan style sheet pada sebuah dokument ketika ditampilkan pada layar yang memiliki panjang kurang dari 800 piksel, Anda dapat menggunakan ini:

+ +
<link rel="stylesheet" media="screen and (max-device-height: 799px)" />
+
+ +

device-width

+ +

Nilai: {{cssxref("<length>")}}
+ Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
+ Menerima prefiks min/max: ya

+ +

Menggambarkan lebar alat penampil (berarti keseluruhan layar atau halaman, bukan hanya area render, seperti jendela dokumen).

+ +

Contoh

+ +

Untuk menerapkan style sheet pada sebuah dokumen ketika ditampilkan pada layar yang memiliki lebar kurang dari 800 piksel wide, Anda dapat menggunakan ini:

+ +
<link rel="stylesheet" media="screen and (max-device-width: 799px)" />
+ +

grid

+ +

Nilai: {{cssxref("<integer>")}}
+ Media: all
+ Menerima prefiks min/max: tidak

+ +

Menentukan apakah alat penampil adalah sebuah alat grid atau bitmap.  Jika alat tersebut berbasis grid (seperti terminal TTY atau layar telepon dengan hanya satu font), nilai adalah 1.  Jika tidak, nilai adalah nol.

+ +

Contoh

+ +

Untuk menerapkan suatu style pada alat genggam dengan layar selebar 15-karakter atau kurang:

+ +
@media handheld and (grid) and (max-width: 15em) { ... }
+
+ +
Catatan: Unit "em" memiliki arti khusus untuk alat grid; karena lebar pasti "em" tidak dapat ditentukan, 1em diasumsikan selebar satu sel grid secara horisontal, dan tingginya satu sell secara vertikal.
+ +

height

+ +

Nilai: {{cssxref("<length>")}}
+ Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
+ Menerima prefiks min/max: ya

+ +

Fitur media height (tinggi) menggambarkan tinggi permukaan rendering alat penampil (seperti tinggi viewport atau kotak halaman pada sebuah printer).

+ +
Catatan: Ketika user mengubah ukuran window, Firefox mengganti style sheets dengan yang paling sesuai berdasarkan media query menggunakan fitur media width dan height.
+ +

monochrome

+ +

Nilai: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Menerima prefiks min/max: ya

+ +

Menunjukkan jumlah bit per piksel pada alat monokrom (keabuan).  Jika alat tersebut bukan monokrom, nilai alat tersebut adalah 0.

+ +

Contoh

+ +

Untuk menerapkan style sheet pada semua alat monokrom:

+ +
@media all and (monochrome) { ... }
+
+ +

Untuk menerapkan style sheet pada alat monokrom dengan paling sedikit 8 bit per piksel:

+ +
@media all and (min-monochrome: 8) { ... }
+
+ +

orientation

+ +

Nilai: landscape | portrait
+ Media: {{cssxref("Media/Visual")}}
+ Menerima prefiks min/max: tidak

+ +

Menunjukkan apakah viewport dalam mode lanskap (tampilan lebih lebar daripada tingginya) atau potret (tampilan lebih tinggi daripada lebarnya).

+ +

Contoh

+ +

Untuk menerapkan style sheet hanya pada orientasi potret:

+ +
@media all and (orientation: portrait) { ... }
+ +

resolution

+ +

Nilai: {{cssxref("<resolution>")}}
+ Media: {{cssxref("Media/Bitmap", "bitmap")}}
+ Menerima prefiks min/max: ya

+ +

Menunjukkan resolusi (kepadatan piksel) alat penampil. Resolution mungkin disebutkan dalam dots per inch (dpi - titik per inci) atau dots per centimeter (dpcm - titik per sentimeter).

+ +

Contoh

+ +

Untuk menerapkan style sheet pada alat dengan resolusi paling sedikit 300 dpi:

+ +
@media print and (min-resolution: 300dpi) { ... }
+
+ +

Untuk mengganti sintaks lama (min-device-pixel-ratio: 2):

+ +
@media screen and (min-resolution: 2dppx) { ... }
+ +

scan

+ +

Nilai: progressiveinterlace
+ Media: {{cssxref("Media/TV")}}
+ Menerima prefiks min/max: tidak

+ +

Menggambarkan proses pemindaian alat penampil televisi.

+ +

Contoh

+ +

Untuk menerapkan style sheet hanya pada televisi pemindai progresif:

+ +
@media tv and (scan: progressive) { ... }
+
+ +

width

+ +

Nilai: {{cssxref("<length>")}}
+ Media: {{cssxref("Media/Visual")}}, {{cssxref("Media/Tactile")}}
+ Menerima prefiks min/max: ya

+ +

Fitur media width menggambarkan lebar permukaan rendering alat penampil (seperti lebar jendela dokumen, atau lebar kotak halaman sebuah printer).

+ +
Catatan: Ketika user mengubah ukuran jendela, Firefox mengganti style sheets yang sesuai berdasarkan media query menggunakan fitur media width dan height.
+ +

Contoh

+ +

Jika Anda ingin menentukan sebuah style sheet untuk perangkat genggam, atau perangkat layar dengan lebar lebih besar dari 20em, Anda dapat menggunakan query ini:

+ +
@media handheld and (min-width: 20em), screen and (min-width: 20em) { ... }
+
+ +

Query Media ini menentukan style sheet yang berlaku untuk media cetak lebih lebar dari 8,5 inci:

+ +
<link rel="stylesheet" media="print and (min-width: 8.5in)"
+    href="http://foo.com/mystyle.css" />
+
+ +

Query ini menentukan style sheet yang digunakan saat lebar viewport adalah antara 500 dan 800 pixel:

+ +
@media screen and (min-width: 500px) and (max-width: 800px) { ... }
+
+ +

Fitur Media Spesifik Mozilla

+ +

Mozilla menawarkan beberapa fitur media spesifik Gecko. Beberapa di antaranya mungkin diusulkan sebagai fitur media resmi.

+ +

{{ h3_gecko_minversion("-moz-images-in-menus", "1.9.2") }}

+ +

Nilai: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Meneriman prefiks min/max: tidak

+ +

Jika perangkat memungkinkan gambar untuk muncul dalam menu, ini adalah 1; jika tidak, nilainya adalah 0. Ini berhubungan dengan pseudo-class CSS {{ cssxref(":-moz-system-metric(images-in-menus)") }}.

+ +

{{ h3_gecko_minversion("-moz-mac-graphite-theme", "1.9.2") }}

+ +

Nilai: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Menerima prefiks min/max: no

+ +

Jika user telah mengkonfigurasi perangkat mereka untuk menggunakan tampilan "Graphite" pada Mac OS X, ini adalah 1. Jika pengguna menggunakan tampilan biru standar, atau bukan pada Mac OS X, ini adalah 0.

+ +

Ini berkaitan dengan pseudo-class CSS {{ cssxref(":-moz-system-metric(mac-graphite-theme)") }}.

+ +

{{ h3_gecko_minversion("-moz-maemo-classic", "1.9.2") }}

+ +

Nilai: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Menerima prefiks min/max: tidak

+ +

Jika user menggunakan Maemo dengan tema asli, ini adalah 1; jika menggunakan tema Fremantle yang lebih baru, ini adalah 0.

+ +

Ini berkaitan dengan pseudo-class CSS {{ cssxref(":-moz-system-metric(maemo-classic)") }}.

+ +

{{ h3_gecko_minversion("-moz-device-pixel-ratio", "2.0") }} {{ deprecated_inline("gecko&16") }}

+ +

Nilai: {{cssxref("<number>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Menerima prefiks min/max: ya

+ +

Memberikan jumlah piksel perangkat per piksel CSS.

+ +
+

Jangan gunakan fitur ini.

+ +

Tapi gunakanlah fitur resolution dengan unit dppx.

+ +


+ -moz-device-pixel-ratio mungkin digunakan sebagai kompatibilitas dengan Firefox lebih tua daripada 16 dan -webkit-device-pixel-ratio dengan browser-browser berbasis WebKit yang tidak mendukung dppx.

+ +

Contoh:

+ +
@media (-webkit-min-device-pixel-ratio: 2), /* Browsers berbasis Webkit */
+       (min--moz-device-pixel-ratio: 2),    /* Browsers yang lebih tua (sebelum Firefox 16) */
+       (min-resolution: 2dppx),             /* Cara standar */
+       (min-resolution: 192dpi)             /* fallback dppx */ 
+ +

Lihat artikel CSSWG ini untuk praktek kompatibilitas yang baik terkait resolution dan dppx.

+
+ +
Catatan: Fitur media ini juga diimplementasikan oleh Webkit sebagai -webkit-device-pixel-ratio. Prefiks min dan max seperti diimplementasikan oleh Gecko dinamakan min--moz-device-pixel-ratio dan max--moz-device-pixel-ratio; tetapi prefiks yang sama seperti yang diimplementasikan oleh Webkit dinamakan -webkit-min-device-pixel-ratio dan -webkit-max-device-pixel-ratio.
+ +

{{ h3_gecko_minversion("-moz-os-version", "25.0") }}

+ +

Nilai: windows-xp | windows-vista | windows-win7 | windows-win8
+ Media: {{cssxref("Media/Visual")}}
+ Menerima prefiks min/max: tidak

+ +

Menunjukkan versi sistem operasi mana yang sedang digunakan saat ini. Saat ini hanya diimplementasikan pada Windows. Nilai-nilai yang mungkin adalah:

+ + + +

Ini disediakan untuk aplikasi skins dan kode chrome lainnya agar dapat beradaptasi untuk bekerja dengan baik dengan versi sistem operasi saat ini.

+ +

{{ h3_gecko_minversion("-moz-scrollbar-end-backward", "1.9.2") }}

+ +

Nilai: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Menerima prefiks min/max: no

+ +

Jika user interface perangkat menampilkan tombol panah kembali di akhir scrollbar, ini adalah 1. Jika tidak, bernilai 0.

+ +

Ini berkaitan dengan pseudo-class CSS {{ cssxref(":-moz-system-metric(scrollbar-end-backward)") }}.

+ +

{{ h3_gecko_minversion("-moz-scrollbar-end-forward", "1.9.2") }}

+ +

Nilai: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Menerima prefiks min/max: tidak

+ +

If the device's user interface displays a forward arrow button at the end of scrollbars, this is 1. Otherwise it's 0.

+ +

This corresponds to the {{ cssxref(":-moz-system-metric(scrollbar-end-forward)") }} CSS pseudo-class.

+ +

{{ h3_gecko_minversion("-moz-scrollbar-start-backward", "1.9.2") }}

+ +

Value: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Accepts min/max prefixes: no

+ +

If the device's user interface displays a backward arrow button at the beginning of scrollbars, this is 1. Otherwise it's 0.

+ +

This corresponds to the {{ cssxref(":-moz-system-metric(scrollbar-start-backward)") }} CSS pseudo-class.

+ +

{{ h3_gecko_minversion("-moz-scrollbar-start-forward", "1.9.2") }}

+ +

Value: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Accepts min/max prefixes: no

+ +

If the device's user interface displays a forward arrow button at the beginning of scrollbars, this is 1. Otherwise it's 0.

+ +

This corresponds to the {{ cssxref(":-moz-system-metric(scrollbar-start-forward)") }} CSS pseudo-class.

+ +

{{ h3_gecko_minversion("-moz-scrollbar-thumb-proportional", "1.9.2") }}

+ +

Value: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Accepts min/max prefixes: no

+ +

If the device's user interface displays the thumb of scrollbars proportionally (that is, sized based on the percentage of the document that is visible), this is 1. Otherwise it's 0.

+ +

This corresponds to the {{ cssxref(":-moz-system-metric(scrollbar-thumb-proportional)") }} CSS pseudo-class.

+ +

{{ h3_gecko_minversion("-moz-touch-enabled", "1.9.2") }}

+ +

Value: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Accepts min/max prefixes: no

+ +

If the device supports touch events (for a touch screen), this is 1. Otherwise it's 0.

+ +

This corresponds to the {{ cssxref(":-moz-system-metric(touch-enabled)") }} CSS pseudo-class.

+ +

Example

+ +

You might use this to render your buttons slightly larger, for example, if the user is on a touch-screen device, to make them more finger-friendly.

+ +

{{ h3_gecko_minversion("-moz-windows-classic", "1.9.2") }}

+ +

Value: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Accepts min/max prefixes: no

+ +

If the user is using Windows unthemed (in classic mode instead of using uxtheme), this is 1; otherwise it's 0.

+ +

This corresponds to the {{ cssxref(":-moz-system-metric(windows-classic)") }} CSS pseudo-class.

+ +

{{ h3_gecko_minversion("-moz-windows-compositor", "1.9.2") }}

+ +

Value: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Accepts min/max prefixes: no

+ +

If the user is using Windows with the DWM compositor, this is 1; otherwise it's 0.

+ +

This corresponds to the {{ cssxref(":-moz-system-metric(windows-compositor)") }} CSS pseudo-class.

+ +

{{ h3_gecko_minversion("-moz-windows-default-theme", "1.9.2") }}

+ +

Value: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Accepts min/max prefixes: no

+ +

If the user is currently using one of the default Windows themes (Luna, Royale, Zune, or Aero (including Vista Basic, Vista Advanced, and Aero Glass), this is 1. Otherwise it's 0.

+ +

This corresponds to the {{ cssxref(":-moz-system-metric(windows-default-theme)") }} CSS pseudo-class.

+ +

{{ h3_gecko_minversion("-moz-windows-glass", "21.0") }}

+ +

Value: {{cssxref("<integer>")}}
+ Media: {{cssxref("Media/Visual")}}
+ Accepts min/max prefixes: no

+ +

If the user is using Windows Glass theme, this is 1; otherwise it's 0. Note that this only exists for Windows 7 and earlier.

+ +

{{ h3_gecko_minversion("-moz-windows-theme", "2.0") }}

+ +

Value: aero | luna-blue | luna-olive | luna-silver | royale | generic | zune
+ Media: {{cssxref("Media/Visual")}}
+ Accepts min/max prefixes: no

+ +

Indicates which Windows theme is currently being used. Only available on Windows. Possible values are:

+ + + +

This is provided for application skins and other chrome code to be able to adapt to work well with the current Windows theme.

+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome("21") }}{{ CompatGeckoDesktop("1.9.1") }}{{ CompatIE("9.0") }}{{ CompatOpera("9") }}{{ CompatSafari("4") }}
grid{{ CompatUnknown() }}{{ CompatNo() }} (grid media type is not supported){{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
resolution{{ CompatChrome("29") }}{{ CompatGeckoDesktop("1.9.1") }} supports {{cssxref("<integer>")}} values;
+ {{ CompatGeckoDesktop("8.0") }} supports {{cssxref("<number>")}} values, as per the spec.
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
scan{{ CompatUnknown() }}{{ CompatNo() }} (tv media type is not supported){{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

See also

+ + diff --git a/files/id/web/guide/grafis/index.html b/files/id/web/guide/grafis/index.html new file mode 100644 index 0000000000..43fb9b5954 --- /dev/null +++ b/files/id/web/guide/grafis/index.html @@ -0,0 +1,48 @@ +--- +title: Grafis dalam web +slug: Web/Guide/Grafis +tags: + - 2D + - 3D + - Canvas + - Grafik + - MDN + - OpenGL + - Web + - WebRTC +translation_of: Web/Guide/Graphics +--- +

Situs web moderen dan aplikasi sering membutuhkan tampilan grafis. Gambar statis dapat dengan mudah ditamilkan dengan menggunakan elemen {{HTMLElement("img")}} , atau mengatur tampilan background dari elemen HTML dengan menggunakan properti css {{cssxref("background-image")}}. anda sering menginginkan tampilan grafis melayang, atau memanipulasi gambar dari gambar nyatanya. Artikel ini memberikan wawasan tentang bagaimana anda dapat melakukannya

+ +
+
+

Grafik 2D

+ +
+
Canvas
+
Elemen {{HTMLElement("canvas")}} menyediakan API untuk menggambar grafik 2D menggunakan javascript.
+
SVG
+
Scalable Vector Graphics (SVG) memungkinkan anda menggunakan garis, kurva, dan bentuk geometris lain untuk membuat grafik. Dengan menghindari penggunaan bitmap, Anda dapat membuat gambar yang bersih dengan skala berbagai ukuran.
+
+ +

Lihat Semua... 

+
+ +
+

Grafik 3D

+ +
+
WebGL
+
Sebuah panduan untuk memulai menggunakan WebGL, API grafis 3D untuk Web. Teknologi ini memungkinkan anda menggunakan standar OpenGL ES dalam konten Web.
+
+ +

Video

+ +
+
Menggunakan HTML5 audio dan video
+
Embedding video dan / atau audio di halaman web dan mengendalikan pemutaran nya.
+
WebRTC
+
RTC pada WebRTC artinya Real-Time Communications, teknologi yang memungkinkan streaming audio/video serta berbagi data antar browser pengguna (peers).
+
+
+
diff --git a/files/id/web/guide/html/forms/index.html b/files/id/web/guide/html/forms/index.html new file mode 100644 index 0000000000..9daf1d6077 --- /dev/null +++ b/files/id/web/guide/html/forms/index.html @@ -0,0 +1,340 @@ +--- +title: HTML forms guide +slug: Web/Guide/HTML/Forms +translation_of: Learn/Forms +--- +

Panduan ini adalah seri dari artikel-artikel yang akan membantu anda menguasai form HTML. Form HTML adalah tool yang paling poweful untuk berinteraksi dengan para pengguna; namun, karena beberapa alasan sejarah dan teknis, tidak jelas bagaimana cara menggunakannya hingga pontensi penuhnya. Dalam panduan ini, kita akan membahas seluruh aspek dari form HTML, struktur form untuk pemberian style, mulai dari penanganan data sampai widget buatan. Anda akan mempelajari bagaimana menikmati kekuatan yang mereka miliki!

+

Articles

+
    +
  1. Form HTML pertama saya
  2. +
  3. Cara membuat struktur form HTML
  4. +
  5. Form Widget native
  6. +
  7. CSS dengan form HTML +
      +
    1. Pemberian style form HTML
    2. +
    3. Pemberian style form HTML Lanjut
    4. +
    5. Tabel kompatibilitas property widget form
    6. +
    +
  8. +
  9. Mengirim dan menerima data form
  10. +
  11. Validasi data form
  12. +
  13. Bagaimana cara membuat gidget form buatan
  14. +
  15. Mengirimkan form melalui JavaScript  +
      +
    1. Menggunakan object FormData
    2. +
    +
  16. +
  17. HTML forms in legacy browsers
  18. +
+

Dokumentasi HTML

+

Elemen-elemen HTML

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ElementRelated DOM interfaceDescription
{{HTMLElement("button")}}{{domxref("HTMLButtonElement")}}Elemen button menampilkan tombol yang dapat diklik.
{{HTMLElement("datalist")}}{{domxref("HTMLDataListElement")}}Elemen datalist menampung kumpulan dari elemen {{ HTMLElement("option") }} yang merepresentasikan pilihan-pilihan yang mungkin untuk nilai dari elemen form lainnya.
{{HTMLElement("fieldset")}}{{domxref("HTMLFieldSetElement")}}fieldset digunakan untuk menggabungkan beberapa elemen form dalam sebuah form.
{{HTMLElement("form")}}{{domxref("HTMLFormElement")}}Elemen form merepresentasikan bagian dari dokumen yang memiliki elemen interaktif yang memungkinkan pengguna mengirimkan informasi ke web server.
{{HTMLElement("input")}}{{domxref("HTMLInputElement")}}Elemen input digunakan untuk membuat kontrol interaktif untuk form.
{{HTMLElement("keygen")}}{{domxref("HTMLKeygenElement")}}Elemen keygen memfasilitasi pembuatan key secara otomatis dan pengiriman public ke sebagai bagian dari form HTML.
{{HTMLElement("label")}}{{domxref("HTMLLabelElement")}}Elemen label merepresentasikan judul dari sebuah item dalam antar muka user
{{HTMLElement("legend")}}{{domxref("HTMLLegendElement")}}Elemen legend merepresentasikan judul utama dari konten parentnya {{ HTMLElement("fieldset") }}.
{{HTMLElement("meter")}}{{domxref("HTMLMeterElement")}}Elemen meter merepresentasikan nilai skalar dalam jangkauan yang diketahui atau nilai fraksi.
{{HTMLElement("optgroup")}}{{domxref("HTMLOptGroupElement")}}Elemen optgroup membuat grup dari pilihan-pilihan dalam sebuah elemen {{ HTMLElement("select") }}.
{{HTMLElement("option")}}{{domxref("HTMLOptionElement")}}Elemen HTML option digunakan untuk membuat kontrol yang merepresentasikan item yang terdapat dalam sebuah elemen {{ HTMLElement("select") }}, {{ HTMLElement("optgroup") }} atau {{ HTMLElement("datalist") }}.
{{HTMLElement("output")}}{{domxref("HTMLOutputElement")}}Element output merepresentasikan hasil dari sebuah kalkulasi.
{{HTMLElement("progress")}}{{domxref("HTMLProgressElement")}}Element progress digunakan untuk menampilkan progress dari sebuah tugas.
{{HTMLElement("select")}}{{domxref("HTMLSelectElement")}}Elemen select merepresentasikan kontrol yang menyajikan pilihan-pilihan menu.
{{HTMLElement("textarea")}}{{domxref("HTMLTextAreaElement")}}Elemen textarea merepresentasikan sebuah kontrol edit dengan multi baris.
+
+

Note: All form elements, as all HTML elements, support the {{domxref("HTMLElement")}} DOM interface.

+
+

HTML Attributes

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Attribute NameElementsDescription
accept{{ HTMLElement("form") }}, {{ HTMLElement("input") }}List of types the server accepts, typically a file type.
accept-charset{{ HTMLElement("form") }}List of supported charsets.
action{{ HTMLElement("form") }}The URI of a program that processes the information submitted via the form.
autocomplete{{ HTMLElement("form") }}, {{ HTMLElement("input") }}Indicates whether controls in this form can by default have their values automatically completed by the browser.
autofocus{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}The element should be automatically focused after the page loaded.
challenge{{ HTMLElement("keygen") }}A challenge string that is submitted along with the public key.
checked{{ HTMLElement("input") }}Indicates whether the element should be checked on page load.
cols{{ HTMLElement("textarea") }}Defines the number of columns in a textarea.
data{{ HTMLElement("object") }}Specifies the URL of the resource.
dirname{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} 
disabled{{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates whether the user can interact with the element.
enctype{{ HTMLElement("form") }}Defines the content type of the form date when the method is POST.
for{{ HTMLElement("label") }}, {{ HTMLElement("output") }}Describes elements which belongs to this one.
form{{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("label") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates the form that is the owner of the element.
high{{ HTMLElement("meter") }}Indicates the lower bound of the upper range.
keytype{{ HTMLElement("keygen") }}Specifies the type of key generated.
list{{ HTMLElement("input") }}Identifies a list of pre-defined options to suggest to the user.
low{{ HTMLElement("meter") }}Indicates the upper bound of the lower range.
max{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}Indicates the maximum value allowed.
maxlength{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Defines the maximum number of characters allowed in the element.
method{{ HTMLElement("form") }}Defines which HTTP method to use when submitting the form. Can be GET (default) or POST.
min{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}Indicates the minimum value allowed.
multiple{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Indicates whether multiple values can be entered in an input of the type email or file.
name{{ HTMLElement("button") }}, {{ HTMLElement("form") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("output") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Name of the element. For example used by the server to identify the fields in form submits.
novalidate{{ HTMLElement("form") }}This attribute indicates that the form shouldn't be validated when submitted.
optimum{{ HTMLElement("meter") }}Indicates the optimal numeric value.
pattern{{ HTMLElement("input") }}Defines a regular expression which the element's value will be validated against.
placeholder{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Provides a hint to the user of what can be entered in the field.
readonly{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Indicates whether the element can be edited.
required{{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates whether this element is required to fill out or not.
rows{{ HTMLElement("textarea") }}Defines the number of rows in a textarea.
selected{{ HTMLElement("option") }}Defines a value which will be selected on page load.
size{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Defines the width of the element (in pixels). If the element's type attribute is text or password then it's the number of characters.
src{{ HTMLElement("input") }}The URL of the embeddable content.
step{{ HTMLElement("input") }} 
target{{ HTMLElement("form") }} 
type{{ HTMLElement("button") }}, {{ HTMLElement("input") }}Defines the type of the element.
usemap{{ HTMLElement("input") }} 
value{{ HTMLElement("button") }}, {{ HTMLElement("option") }}, {{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}Defines a default value which will be displayed in the element on page load.
wrap{{ HTMLElement("textarea") }}Indicates whether the text should be wrapped.
+

Normative reference

+ diff --git a/files/id/web/guide/html/html5/index.html b/files/id/web/guide/html/html5/index.html new file mode 100644 index 0000000000..48e2349af7 --- /dev/null +++ b/files/id/web/guide/html/html5/index.html @@ -0,0 +1,179 @@ +--- +title: HTML5 +slug: Web/Guide/HTML/HTML5 +tags: + - HTML + - HTML5 + - NeedsTranslation + - References + - TopicStub + - Web Development +translation_of: Web/Guide/HTML/HTML5 +--- +

HTML5 adalah evolusi terbaru dari standard yang mendefinisikan HTML. Istilah ini merepresentasikan dua konsep yang berbeda:

+ + + +

Dirancang untuk dapat digunakan oleh semua pengembang Web Terbuka, Berikut ini adalah tautan halaman referensi ke beberapa resource tentang teknologi HTML5, diklasifikasikan ke dalam beberapa kelompok berdasarkan fungsinya masing-masing.

+ + + +
+
+

Semantik

+ +
+
"Sections" dan "outlines" pada HTML5
+
Sebuah tampilan pada elemen baru yaitu outline dan section pada HTML5: {{HTMLElement("section")}}, {{HTMLElement("article")}}, {{HTMLElement("nav")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}} and {{HTMLElement("aside")}}.
+
Menggunakan fungsi "audio"  dan "video" pada HTML5
+
Elemen {{HTMLElement("audio")}} dan {{HTMLElement("video")}} ditanamkan sehingga kita dapat memanipulasi sebuah konten multimedia.
+
"Forms" pada HTML5
+
Perbaikan pada form di HTML5: the constraint validation API, beberapa attribute baru, nilai baru untuk {{HTMLElement("input")}} atribut {{htmlattrxref("type", "input")}} dan elemen baru yaitu {{HTMLElement("output")}}.
+
Elemen-elemen baru Semantik
+
Disamping section, media dan form elements, there are numerous new elements, like {{HTMLElement("mark")}}, {{HTMLElement("figure")}}, {{HTMLElement("figcaption")}}, {{HTMLElement("data")}}, {{HTMLElement("time")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, or {{HTMLElement("meter")}} and {{HTMLElement("main")}}, increasing the amount of valid HTML5 elements.
+
Perbaikan pada {{HTMLElement("iframe")}}
+
Using the {{htmlattrxref("sandbox", "iframe")}}, {{htmlattrxref("seamless", "iframe")}}, and {{htmlattrxref("srcdoc", "iframe")}} attributes, authors can now be precise about the level of security and the wished rendering of an {{HTMLElement("iframe")}} element.
+
MathML
+
Allows directly embedding mathematical formulas.
+
Introduction to HTML5
+
This article introduces how to indicate to the problem that you are using HTML5 in your web design or web application.
+
HTML5-compliant parser
+
The parser, which turns the bytes of an HTML document into a DOM, has been extended and now precisely defines the behavior to use in all cases, even when faced with invalid HTML. This leads to far greater predictability and interoperability between HTML5-compliant browsers.
+
+ +

Connectivity

+ +
+
Web Sockets
+
Allows creating a permanent connection between the page and the server and to exchange non-HTML data through that means.
+
Server-sent events
+
Allows a server to push events to a client, rather than the classical paradigm where the server could send data only in response to a client's request.
+
WebRTC
+
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
+
+ +

Offline & storage

+ +
+
Offline resources: the application cache
+
Firefox fully supports the HTML5 offline resource specification. Most others have offline resource support at some level.
+
Online and offline events
+
Firefox 3 supports WHATWG online and offline events, which let applications and extensions detect whether or not there's an active Internet connection, as well as to detect when the connection goes up and down.
+
WHATWG client-side session and persistent storage (aka DOM Storage)
+
Client-side session and persistent storage allows web applications to store structured data on the client side.
+
IndexedDB
+
IndexedDB is a web standard for the storage of significant amounts of structured data in the browser and for high performance searches on this data using indexes.
+
Using files from web applications
+
Support for the new HTML5 File API has been added to Gecko, making it possible for web applications to access local files selected by the user. This includes support for selecting multiple files using the {{HTMLElement("input")}} of type file HTML element's new multiple attribute. There also is FileReader.
+
+ +

Multimedia

+ +
+
Using HTML5 audio and video
+
The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.
+
WebRTC
+
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
+
Using the Camera API
+
Allows using, manipulating, and storing an image from the computer's camera.
+
Track and WebVTT
+
The {{HTMLElement("track")}} element allows subtitles and chapters. WebVTT is a text track format.
+
+ +

3D, graphics & effects

+ +
+
Canvas Tutorial
+
Learn about the new {{HTMLElement("canvas")}} element and how to draw graphs and other objects in Firefox.
+
HTML5 text API for <canvas> elements
+
The HTML5 text API is now supported by {{HTMLElement("canvas")}} elements.
+
WebGL
+
WebGL brings 3D graphics to the Web by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 {{HTMLElement("canvas")}} elements.
+
SVG
+
An XML-based format of vectorial images that can directly be embedded in the HTML.
+
 
+
+
+ +
+

Performance & integration

+ +
+
Web Workers
+
Allows delegation of JavaScript evaluation to background threads, allowing these activities to prevent slowing down interactive events.
+
XMLHttpRequest Level 2
+
Allows fetching asynchronously some parts of the page, allowing it to display dynamic content, varying according to the time and user actions. This is the technology behind Ajax.
+
JIT-compiling JavaScript engines
+
The new generation of JavaScript engines is much more powerful, leading to greater performance.
+
History API
+
Allows the manipulation of the browser history. This is especially useful for pages loading interactively new information.
+
The contentEditable attribute: transform your website to a wiki!
+
HTML5 has standardized the contentEditable attribute. Learn more about this feature.
+
Drag and drop
+
The HTML5 drag and drop API allows support for dragging and dropping items within and between web sites. This also provides a simpler API for use by extensions and Mozilla-based applications.
+
Focus management in HTML
+
The new HTML5 activeElement and hasFocus attributes are supported.
+
Web-based protocol handlers
+
You can now register web applications as protocol handlers using the navigator.registerProtocolHandler() method.
+
requestAnimationFrame
+
Allows control of animations rendering to obtain optimal performance.
+
Fullscreen API
+
Controls the usage of the whole screen for a Web page or application, without the browser UI displayed.
+
Pointer Lock API
+
Allows locking the pointer to the content, so games and similar applications don't lose focus when the pointer reaches the window limit.
+
Online and offline events
+
In order to build a good offline-capable web application, you need to know when your application is actually offline. Incidentally, you also need to know when your application has returned to an online status again.
+
+ +

Device access

+ +
+
Using the Camera API
+
Allows using, manipulating, and storing an image from the computer's camera.
+
Touch events
+
Handlers to react to events created by a user pressing touch screens.
+
Using geolocation
+
Let browsers locate the position of the user using geolocation.
+
Detecting device orientation
+
Get the information when the device on which the browser runs changes orientation. This can be used as an input device (e.g., to make games that react to the position of the device) or to adapt the layout of a page to the orientation of the screen (portrait or landscape).
+
Pointer Lock API
+
Allows locking the pointer to the content, so games and similar application don't lose focus when the pointer reaches the window limit.
+
+ +

Styling

+ +

CSS has been extended to be able to style elements in a much more complex way. This is often referred as CSS3, though CSS is not a monolithic specification any more and the different modules are not all at level 3: some are at level 1 and others at level 4, with all the intermediate levels covered.

+ +
+
New background styling features
+
It is now possible to put a shadow to a box, using {{cssxref("box-shadow")}} and multiple backgrounds can be set.
+
More fancy borders
+
Not only it is now possible to use images to style borders, using {{cssxref("border-image")}} and its associated longhand properties, but rounded borders are supported via the {{cssxref("border-radius")}} property.
+
Animating your style
+
Using CSS Transitions to animate between different states or using CSS Animations to animate parts of the page without a triggering event, you can now control mobile elements on your page.
+
Typography improvement
+
Authors have better control to reach better typography. They can control {{cssxref("text-overflow")}} and hyphenation, but also can add a shadow to it or control more precisely its decorations. Custom typefaces can be downloaded and applied thanks to the new {{cssxref("@font-face")}} at-rule.
+
New presentational layouts
+
In order to improve the flexibility of designs, two new layouts have been added: the CSS multi-column layout, and the CSS flexible box layout.
+
+
+
+ +

External References
+
+ Html5 Tutorial
+  

+ +

 

diff --git a/files/id/web/guide/index.html b/files/id/web/guide/index.html new file mode 100644 index 0000000000..5e7889fa77 --- /dev/null +++ b/files/id/web/guide/index.html @@ -0,0 +1,55 @@ +--- +title: Paduan Pengembang Web +slug: Web/Guide +tags: + - Landing + - Paduan + - TopicStub + - Web +translation_of: Web/Guide +--- +

Artikel ini memberikan informasi untuk membantu anda menggunakan teknologi dan API secara spesifik.

+ +
+
+
+
Area Belajar HTML
+
HyperText Markup Language (HTML) merupakan inti bahasa untuk hampir semua konten Web. Hampir keseluruhan yang anda lihat di layar browser, pada dasarnya, menggunakan HTML.
+
Area Belajar CSS
+
Cascading Style Sheets (CSS) adalah bahasa stylesheet yang digunakan untuk mendeskripsikan tampilan dokumen yang ditulis di HTML.
+
Paduan pegembang Event
+
Events mengacu baik pada pola desain yang digunakan untuk penanganan secara asynchronous pada berbagai peristiwa di halaman web dan penamaan, karakterisasi, dan penggunaan sejumlah besar peristiwa dari berbagai tipe.
+
Grafis di Web
+
Website modern dan aplikasi sering memerlukan menyajikan grafis dari berbagai kecanggihan.
+
Paduan Web API
+
Daftar semua Web API dan apa yang dihasilkan.
+
JavaScript
+
JavaScript adalah bahasa scripting yang ampuh digunakan untuk membuat aplikasi Web.
+
Lokalisasi dan pengkodean karakter
+
Browser memproses teks sebagai Unicode secara internal. Namun, cara merepresentasikan karakter dalam bentuk bytes (character encoding) yang digunakan untuk mengirim teks melalui jaringan ke browser.  Spesifikasi HTML menyarankan penggunaan UTF-8 encoding (dimana mewakili semua Unicode), dan terlepas dari pengkode-an yang digunakan, dibutuhkan konten Web untuk mendeklarasikan pengkode-an tersebut.
+
Pengembangan Mobile Web
+
Halaman ini memberikan gambaran dari beberapa teknik utama yang dibutuhkan desain Website sehingga berjalan dengan baik di perangkat mobile. Jika anda mencari informasi di proyek Mozilla's Firefox OS, lihat halaman Firefox OS. Atau anda mungkin tertarik pada detail tentang Firefox for Android.
+
+
+ +
+
+
Optimasi dan kinerja
+
Ketika membangun modern Web apps dan situs, sangat penting untuk membuat konten yang bekerja dengan cepat dan efisien. Ini memungkinkan situs bekerja dengan baik pada keduanya, sistem Desktop yang kuat dan perngkat genggam yang lemah.
+
Parsing and serializing XML
+
Platform Web menyediakan metode yang berbeda dari parsing and serializing XML, dengan masing-masing pro dan kontra.
+
Open Web Font Format (WOFF)
+
WOFF (Web Open Font Format) adalah file format font yang gratis untuk semua pengguna di web.
+
Menggunakan Objek FormData
+
Objek FormData memungkinkan anda menkompilasi serangkaian key/value pairs untuk dikirim menggunakan XMLHttpRequest. Utamanya ditujukan untuk mengirim format data, namun dapat digunakan secara terpisah dari format dengan tujuan untuk mengirim keyed data. Pengiriman dengan format yang sama dengan bentuk method submit() digunakan untuk mengirim data jika bentuk tipe encoding ditetapkan ke "multipart/form-data".
+
Glosarium
+
Menjelaskan berbagai istilah teknis terkait Web dan Internet.
+
+
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/html/element/base/index.html b/files/id/web/html/element/base/index.html new file mode 100644 index 0000000000..6b4a556381 --- /dev/null +++ b/files/id/web/html/element/base/index.html @@ -0,0 +1,154 @@ +--- +title: +slug: Web/HTML/Element/base +translation_of: Web/HTML/Element/base +--- +

{{HTMLRef}}

+ +

The HTML <base> element specifies the base URL to use for all relative URLs contained within a document. There can be only one <base> element in a document. 

+ +

The base URL of a document can be queried from a script using {{domxref('document.baseURI')}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Content categoriesMetadata content.
Permitted contentNone, it is an {{Glossary("empty element")}}.
Tag omissionThere must be no closing tag.
Permitted parentsAny {{HTMLElement("head")}} that doesn't contain any other {{HTMLElement("base")}} element
Permitted ARIA rolesNone
DOM interface{{domxref("HTMLBaseElement")}}
+ +

Attributes

+ +

This element's attributes include the global attributes.

+ +
+
{{htmlattrdef("href")}}
+
The base URL to be used throughout the document for relative URL addresses. If this attribute is specified, this element must come before any other elements with attributes whose values are URLs. Absolute and relative URLs are allowed.
+
{{htmlattrdef("target")}}
+
A name or keyword indicating the default location to display the result when hyperlinks or forms cause navigation, for elements that do not have an explicit target reference. It is a name of, or keyword for, a browsing context (for example: tab, window, or inline frame). The following keywords have special meanings: +
    +
  • _self: Load the result into the same browsing context as the current one. This value is the default if the attribute is not specified.
  • +
  • _blank: Load the result into a new unnamed browsing context.
  • +
  • _parent: Load the result into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self.
  • +
  • _top: Load the result into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self.
  • +
+
+
+ +

Usage notes

+ +

If multiple <base> elements are specified, only the first href and first target value are used; all others are ignored.

+ +

Examples

+ +
<base href="http://www.example.com/page.html">
+<base target="_blank" href="http://www.example.com/page.html">
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'semantics.html#the-base-element', '<base>')}}{{Spec2('HTML WHATWG')}}No change since last snapshot.
{{SpecName('HTML5 W3C', 'document-metadata#the-base-element', '<base>')}}{{Spec2('HTML5 W3C')}}Specified the behavior of target
{{SpecName('HTML4.01', 'struct/links.html#h-12.4', '<base>')}}{{Spec2('HTML4.01')}}Added the target attribute
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}} [1]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}} [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Support of relative URIs for href was added in Gecko 2.0 (Firefox 4.0)

+ +

[2] Before Internet Explorer 7, <base> could be positioned anywhere in the document and the nearest value of <base> was used. Support for relative URLs has been removed in Internet Explorer 8

diff --git a/files/id/web/html/element/dialog/index.html b/files/id/web/html/element/dialog/index.html new file mode 100644 index 0000000000..ac51fecd40 --- /dev/null +++ b/files/id/web/html/element/dialog/index.html @@ -0,0 +1,165 @@ +--- +title: ': The Dialog element' +slug: Web/HTML/Element/dialog +translation_of: Web/HTML/Element/dialog +--- +

Elemen <dialog> menampilkan sebuah kotak dialog atau komponen interaktif lainnya seperti halnya inspektor atau jendela.

+ +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Kategori kontenAlur Konten, bagian akar
Konten yang diijinkanAlur konten
Penanda kesalahan{{no_tag_omission}}
Tingkatan yang diijinkanSetiap elemen yang menerima alur konten
Peran Aria yang diijinkan{{ARIARole("alertdialog")}}
Antarmuka DOM{{domxref("HTMLDialogElement")}}
+ +

Atribut

+ +

Elemen ini memiliki atribut global. Penggunaan atribut tabindex harus dihindari pada elemen <dialog> .

+ +
+
{{htmlattrdef("open")}}
+
Menandakan bahwa dialog telah aktif dan dapat digunakan. Ketika atribut open belum diatur, maka dialog tidak akan tampil kepada pengguna.
+
+ +

Catatan penggunaan

+ +

 

+ + + +

Contoh

+ +

Contoh sederhana

+ +
<dialog open>
+  <p>Greetings, one and all!</p>
+</dialog>
+
+ +

Contoh lanjutan

+ +

Pada contoh ini akan terbuka kotak dialog saat tombol "Update details" diklik.

+ +

HTML

+ +
<!-- Simple pop-up dialog box, containing a form -->
+<dialog open id="favDialog">
+  <form method="dialog">
+    <section>
+      <p><label for="favAnimal">Favorite animal:</label>
+      <select id="favAnimal">
+        <option></option>
+        <option>Brine shrimp</option>
+        <option>Red panda</option>
+        <option>Spider monkey</option>
+      </select></p>
+    </section>
+    <menu>
+      <button id="cancel" type="reset">Cancel</button>
+      <button type="submit">Confirm</button>
+    </menu>
+  </form>
+</dialog>
+
+<menu>
+  <button id="updateDetails">Update details</button>
+</menu>
+
+ +

JavaScript

+ +
(function() {
+  var updateButton = document.getElementById('updateDetails');
+  var cancelButton = document.getElementById('cancel');
+  var favDialog = document.getElementById('favDialog');
+
+  // Update button opens a modal dialog
+  updateButton.addEventListener('click', function() {
+    favDialog.showModal();
+  });
+
+  // Form cancel button closes the dialog box
+  cancelButton.addEventListener('click', function() {
+    favDialog.close();
+  });
+})();
+
+ +

Hasil

+ +

{{EmbedLiveSample("Contoh_lanjutan", "100%", 300)}}

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKeterangan
{{SpecName('HTML WHATWG', 'forms.html#the-dialog-element', '<dialog>')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.2', 'interactive-elements.html#the-dialog-element', '<dialog>')}}{{Spec2('HTML5.2')}}Initial definition
+ +

Kompatibilitas browser

+ + + +

{{Compat("html.elements.dialog")}}

+ +

Polyfills

+ +

Sertakan polyfill ini untuk menyediakan dukungan terhadap browser lawas

+ +

dialog-polyfill

+ +

Lihat juga

+ + + +
{{HTMLRef}}
diff --git a/files/id/web/html/element/image/index.html b/files/id/web/html/element/image/index.html new file mode 100644 index 0000000000..047ac8f8b4 --- /dev/null +++ b/files/id/web/html/element/image/index.html @@ -0,0 +1,16 @@ +--- +title: +slug: Web/HTML/Element/image +translation_of: Web/HTML/Element/image +--- +
{{non-standard_header}}
+ +

Ringkasan

+ +

Elemen HTML <image> adalah elemen eksperimental yang dirancang untuk menampilkan gambar. Ini tidak pernah di implementasikan dan standar elemen {{HTMLElement ("img")}} harus digunakan.

+ +
+

Jangan Gunakan! Untuk menampilkan gambar, gunakan standar elemen {{HTMLElement ("img")}} .

+
+ +

Catatan sampai Firefox 22, meskipun tidak didukung, elemen <image> diasosiasikan dengan {{domxref ("HTMLSpanElement")}}. Kemudian diperbaiki dan sekarang diasosiasikan dengan {{domxref ("HTMLElement")}} mengikuti spesifikasi yang diminta.

diff --git a/files/id/web/html/element/index.html b/files/id/web/html/element/index.html new file mode 100644 index 0000000000..6651addc38 --- /dev/null +++ b/files/id/web/html/element/index.html @@ -0,0 +1,106 @@ +--- +title: HTML element reference +slug: Web/HTML/Element +tags: + - Elemen + - HTML + - Referensi + - Web + - dasar +translation_of: Web/HTML/Element +--- +
{{HTMLSidebar("Elements")}}
+ +

Halaman ini menampilkan semua daftar {{Glossary("HTML")}} {{Glossary("Element","elements")}}, yang dibuat menggunakan {{Glossary("Tag", "tags")}}. Ini dikelompokkan berdasarkan fungsi untuk membantu Anda mengingat lebih mudah. Daftar abjad semua element tersedia di sidebar pada setiap halaman element seperti yang ini.

+ +
+

Untuk informasi lebih tentang dasar-dasar element HTML dan attribut, lihat artikel bagian pengenalan HTML.

+
+ +

Akar Utama

+ +

{{HTMLRefTable("HTML Root Element")}}

+ +

Document metadata

+ +

Metadata mengandung informasi halaman. Ini terdapat informasi tentang styles, scripts dan data untuk membantu perangkat lunak ({{Glossary("search engine", "search engines")}}, {{Glossary("Browser","browsers")}}, dsb.) gunakan dan alihkan halaman. Metadata untuk style dan script bisa didefinisikan di halaman atau link untuk berkas lainnya yabg memiliki informasinya.

+ +

{{HTMLRefTable("HTML Document Metadata")}}

+ +

Bagian Dasar

+ +

{{HTMLRefTable("Sectioning Root Element")}}

+ +

Kontent Bagian

+ +

Element konten bagian memungkinkan Ansa mengatur konten dokumen menjadi kepingan-kepingan logis. Gunakan element bagian untuk membuat sebagian besar konten halaman Anda, termasuk navigasi header dan footer, dan judul element untuk mengidentifikasi bagian kontent.

+ +

{{HTMLRefTable("HTML Sections")}}

+ +

Konten kalimat

+ +

Kegunaan element teks konten HTML mengatur blok atau bagian konten yang ditempatkan antara tag pembuka {{HTMLElement("body")}} dan penutup </body> . Penting untuk {{Glossary("accessibility")}} and {{Glossary("SEO")}}, element-element ini mengenali tujuan atau struktur kontennya.

+ +

{{HTMLRefTable("HTML Grouping Content")}}

+ +

Teks semantik dalam baris

+ +

Kegunaan teks semantik dalam baris HTML untuk memberikan tujuan, struktur, atau gaya kata, baris, atau potongan kata sembarang.

+ +

{{HTMLRefTable("HTML Text-Level Semantics")}}

+ +

Gambar dan multimedia

+ +

HTML mendukung beragam sumber multimedia seperti gambar, audio, dan vidio.

+ +

{{HTMLRefTable("multimedia")}}

+ +

Embedded content

+ +

Selain konten multimedia biasa, HTML dapat menyertakan konten lainnya, walaupun tidak selalu mudah menyertakannya.

+ +

{{HTMLRefTable({"include":["HTML embedded content"], "exclude":["multimedia"]})}}

+ +

Scripting

+ +

Untuk membuat konten dinamis dan aplikasi web, HTML mendukung penggunaan bahasa skripsi, secara paling jelas JavaScript. Element tertentu mendukung kemampuan ini.

+ +

{{HTMLRefTable("HTML Scripting")}}

+ +

Batas Pengubahan

+ +

Element ini memungkinkan Anda menyediakan indikasi bagian spesifik bagian kalimat yang telah diubah.

+ +

{{HTMLRefTable("HTML Edits")}}

+ +

Konten tabel

+ +

Element ini digunakan untuk membuat dan menangani data tabular.

+ +

{{HTMLRefTable("HTML tabular data")}}

+ +

Formulir

+ +

HTML menyediakan beberapa element yang dapat digunakan bersama untuk membuat formulir, dimana pengguna dapat mengisi dan memasukan ke situs web atau aplikasi. Terdapat banyak informasi ini tersedia di panduan formulir HTML.

+ +

{{HTMLRefTable({"include": ["HTML forms"], "exclude":["Deprecated"]})}}

+ +

Element interaktif

+ +

HTML menawarkan pilihan element yang membantu untuk membuat pengguna interaktif berhadapan dengan objek.

+ +

{{HTMLRefTable("HTML interactive elements")}}

+ +

Komponen Web

+ +

Komponen Web adalah teknologi HTML terhubung yang memungkinkan untuk, secara inti, membuat dan menggunakan element khusus seperti itu HTML umum. Selain itu, Anda dapat membuat versi khusus element HTML standar.

+ +

{{HTMLRefTable({"include":["Web Components"],"elements":["shadow"]})}}

+ +

Element Usang dan Dihilangkan

+ +
+

Peringatan: Ini adalah element HTML lama yang dihilangkan dan seharusnya tidak digunakan. Anda harus tidak pernah menggunakannya pada proyek baru, dan harus mengubahnya pada proyek lama secepat yang Anda bisa. Berikut ini adalah daftarnya, hanya untuk informasi saja.

+
+ +

{{HTMLRefTable({"include":["Deprecated","Obsolete"]})}}

diff --git a/files/id/web/html/index.html b/files/id/web/html/index.html new file mode 100644 index 0000000000..11a63d028d --- /dev/null +++ b/files/id/web/html/index.html @@ -0,0 +1,97 @@ +--- +title: HTML +slug: Web/HTML +translation_of: Web/HTML +--- +
{{HTMLSidebar}}
+ +

HTML (HyperText Markup Language) merupakan building block web paling dasar. Ini memberikan arti dan struktur konten web. Teknologi-teknologi lainnya disamping HTML umumnya digunakan untuk menggambarkan penampilan/gambaran (CSS) atau fungsionalitas/tingkah laku (JavaScript).

+ +

"Hypertext" merujuk ke link yang menghubungkan halaman web satu dengan lainnya, baik dalam satu situs maupun antar situs web. Dengan mengunggah konten ke internet dan menghubungkannya ke halaman yang dibuat oleh orang lain, Anda menjadi pertisipasi aktif di World Wide Web.

+ +

HTML menggunakan "markup" untuk anotasi teks, gambar, dan konten lainnya untuk ditampilkan dalam peramban Web. Markip HTML terdapat "elements" khusus seperti {{HTMLElement("head")}}, {{HTMLElement("title")}}, {{HTMLElement("body")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}}, {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("p")}}, {{HTMLElement("div")}}, {{HTMLElement("span")}}, {{HTMLElement("img")}}, {{HTMLElement("aside")}}, {{HTMLElement("audio")}}, {{HTMLElement("canvas")}}, {{HTMLElement("datalist")}}, {{HTMLElement("details")}}, {{HTMLElement("embed")}}, {{HTMLElement("nav")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("video")}}, {{HTMLElement("ul")}}, {{HTMLElement("ol")}}, {{HTMLElement("li")}} dan masih banyak lagi.

+ +

Elemen HTML dibedakan dari teks lain dalam dokumen dengan "tags", yang terdiri dari nama elemen yang dikelilingi oleh "<" dan ">". Nama elemen dalam tag itu insensitif. Yakni, dapat ditulis dengan huruf besar, huruf kecil, atau gabungan. Contohnya tag <title> dapat ditulis sebagai <Title>, <TITLE>, atau dengan cara lainnya.

+ +

Artikel-artikel dibawah dalat membantu Amda belajar lebih banyak tentang HTML.

+ +
+
    +
  • Pengenalan HTML + +

    Jika kamu baru di pengembangan Web, pastima untum membaca artikel Dasar-dasar HTML kami untuk belajar apa HTML itu dan cara menggunakannya.

    +
  • +
  • Tutorial HTML +

    Untuk artikel tentang cara menggunakan HTML, tutorial yang bagus dan dipenuhi contoh, periksa artikel Ruang Belajar HTML.

    +
  • +
  • Referensi HTML +

    Di bagian Referensi HTML yang luas, Anda akan menemukan setiap detail elemen dan attribut dalam HTML.

    +
  • +
+ +
+
+

Tutorial Pemula

+ +

Fitur-fitur modul ganda Ruang Belajar HTML yang mengajari HTML dari bawah ke atas — tanpa dibutuhkan pengetahuan sebelumnya.

+ +
+
Pengenalan pada HTML
+
Tahap kumpulan modul ini, membuat Anda terbiasa menggunakan konsep dan sintaks penting seperti melihat pengaplikasian HTML pada teks, cara untuk membuat hyperlink, dan cara menggunakan HTML untuk struktur halaman web.
+
Multimedia and embedding
+
This module explores how to use HTML to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire other webpages.
+
Tabel-tabel HTML
+
Mewakili data tabular di halaman web yang dapat dimengerti, cara keaksesan dapat menantang. Modul ini mencangkup markup dasar tabel, bersama dengan fitur lebih  kompleks seperti keterangan implementasi dan ringkasan.
+
Formulir HTML
+
Formulir merupakan bagian sangat penting di Web — ini menyediakan banyak kegunaan yang Anda butuhkan untuk berinteraksi dengan situs-situs web, msl. pendaftaran dan masuk, pengiriman masukan, pembelian produk, dan lainnya. Modul ini membantu Anda dengan membuat formulir sisi klien/bagian awal hingga akhir.
+
Pakai HTML untuk memperbaiki kesalahan umum.
+
Menyediakan link ke bagian-bagian konten menjelaskan cara menggubakan HTML untuk menyelesaikan masalah sangat umum ketika membuat halaman web: mengatur judul, menambahkan gambar atau vidio, penekanan konten, pembuatan formulir dasar, dsb.
+
+ +

Topik Lanjut

+ +
+
Gambar diaktifkan CORS
+
Attribut {{htmlattrxref("crossorigin", "img")}}, di kombinasikan dengan bagian kepala {{glossary("CORS")}} yang sesuai, memungkinkan gambar didefinisikan dengan elemen {{HTMLElement("img")}} untuk dimuat dari origin asing dan digunakan di elemen {{HTMLElement("canvas")}} seolah sedang dimuat dari asal saat ini.
+
CORS mengatur atribut
+
Beberapa elemen HTML mendukung CORS, seperti {{HTMLElement("img")}} atau {{HTMLElement("video")}}, memiliki atribut crossorigin (properti crossOrigin), yang memungkinkan Anda mengkonfigurasikan permintaan CORS untuk mengambil data elemen.
+
Fokus manajemen di HTML
+
Metode Atribut DOM activeElement dan DOM hasFocus() membantu Anda melacak dan mengendalikan interaksi pengguna dengan elemen di halaman web.
+
Mem-preloading konten dengan rel="preload"
+
The preload value of the {{htmlelement("link")}} element's {{htmlattrxref("rel", "link")}} attribute allows you to write declarative fetch requests in your HTML {{htmlelement("head")}}, specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. This ensures that they are made available earlier and are less likely to block the page's first render, leading to performance improvements. This article provides a basic guide to how preload works.
+
+
+ +
+

Referensi

+ +
+
Refensi HTML
+
HTML terdiri dari elemen, setiap elemen mugkin dimofikasi dengan beberapa atribut. Dokumen HTML terhubung satu sama lain dengan link.
+
Referensi elemen HTML
+
Kunjungi semua daftar {{glossary("HTML")}} {{glossary("Element", "elements")}}.
+
Referensi atribut HTML
+
Elemen HTML memiliki atribut. Ini adalah nilai tambahan yang mengkonfigurasikan elemen atau menyesuaikan tingkah lakunya di berbagai cara.
+
Atribut Global
+
Global attributes may be specified on all HTML elements, even those not specified in the standard. This means that any non-standard elements must still permit these attributes, even though those elements make the document HTML5-noncompliant.
+
Inline elements and block-level elements
+
Elemen HTML elements biasanya elemen "inline" atau "block-level". Inline elemen hanya menempati ruang yang terikat dengan elemen yang didefinisikan. Block-level menempati seluruh ruang elemen orang tuanya (parent element) (container), dengan demikian membuat sebuah "block."
+
Jenis-jenis Link
+
Di HTML, beragam jenis link dapat digunakan untuk membangun dan mendefinisikan hubungan antara dua dokumen. Elemen link yang jenisnya dapat diatur ke dalam {{HTMLElement("a")}}, {{HTMLElement("area")}} dan {{HTMLElement("link")}}.
+
Panduan jenis-jenis media dan format pada web
+
Elemen {{HTMLElement("audio")}} dan {{HTMLElement("video")}} memungkinkan Anda memutar media audio dan vidio secara langsung di konten Anda tidan perlu dukungan perangkat lunak tambahan.
+
Jenis-jenis konten HTML
+
HTML is comprised of several kinds of content, each of which is allowed to be used in certain contexts and is disallowed in others. Similarly, each has a set of other content categories they can contain and elements which can or can't be used in them. This is a guide to these categories.
+
Quirks mode and standards mode
+
Historical information on quirks mode and standards mode.
+
+ +

Topik-topik berhubungan

+ +
+
Mengaplikasikan warna ke elemen HTML menggunakan CSS
+
Artikel ini mencakup sebagian besar cara Anda menggunakan CSS untuk memberikan warna pada konten HTML, daftar bagian dokumen apa yang dapat diwarnai dan properti CSS yang digunakan untuk melakukannya. Termasuk contoh, peralatan tempat palet, dan lainnya.
+
+
+
+Lihat semua...
diff --git a/files/id/web/http/basics_of_http/index.html b/files/id/web/http/basics_of_http/index.html new file mode 100644 index 0000000000..a00d7fe410 --- /dev/null +++ b/files/id/web/http/basics_of_http/index.html @@ -0,0 +1,51 @@ +--- +title: Basics of HTTP +slug: Web/HTTP/Basics_of_HTTP +tags: + - Guide + - HTTP + - NeedsTranslation + - Overview + - TopicStub +translation_of: Web/HTTP/Basics_of_HTTP +--- +
{{HTTPSidebar}}
+ +

HTTP adalah sebuah protokol yang dapat diperluas. HTTP bergantung pada beberapa konsep dasar seperti the notion of resources and URIs, a simple structure of messages, and a client-server structure for the communication flow. On top of these basic concepts, numerous extensions have appeared over the years, adding new functionality and new semantics by creating new HTTP methods or headers.

+ +

Articles

+ +
+
Overview of HTTP
+
Describes what HTTP is and its role in the Web architecture, its position in the protocol stack.
+
Evolution of HTTP
+
HTTP was created in the early 1990s and has been extended several times. This article goes through its history and describes HTTP/0.9, HTTP/1.0, HTTP/1.1, and the modern HTTP/2 as well as minor novelties introduced over the years.
+
Negotiating an HTTP version
+
Explains how a client and a server can negotiate a specific HTTP version and eventually upgrade the protocol version used.
+
Resources and URIs
+
A brief introduction of the notion of resources, identifiers, and locations on the Web.
+
Identifying resources on the Web
+
Describes how Web resources are referenced and how to locate them.
+
Data URIs
+
A specific kind of URIs that directly embeds the resource it represents. Data URIs are very convenient, but have some caveats.
+
Resource URLs {{Non-standard_Inline}}
+
Resource URLs, URLs prefixed with the resource: scheme, are used by Firefox and Firefox browser extensions to load resources internally, but some of the information is available to sites the browser connects to as well.
+
Separating identity and location of a resource: the Alt-Svc HTTP header
+
Most of the time identity and location of a Web resource are shared, this can be changed with the {{HTTPHeader("Alt-Svc")}} header.
+
MIME types
+
Since HTTP/1.0, different types of content can be transmitted. This article explains how this is done using the {{HTTPHeader("Content-Type")}} header and the MIME standard.
+
Choosing between www and non-www URLs
+
Advice on using a www-prefixed domain or not, this article explains the consequences of the choice as well as how to make it.
+
Flow of an HTTP session
+
This fundamental article describes a typical HTTP session: what happens under the hood when you click on a link in your browser…
+
HTTP Messages
+
HTTP Messages transmitted during requests or responses have a very clear structure; this introductory article describes this structure, its purpose and its possibilities.
+
Frame and message structure in HTTP/2
+
HTTP/2 encapsulates and represents HTTP/1.x messages in a binary frame. This article explains the frame structure, its purpose and the way it is encoded.
+
Connection management in HTTP/1.x
+
HTTP/1.1 was the first version of HTTP to support persistent connection and pipelining. This article explains these two concepts.
+
Connection management in HTTP/2
+
HTTP/2 completely revisited how connections are created and maintained: this article explains how HTTP frames allow multiplexing and solve the 'head-of-line' blocking problem of former HTTP versions.
+
Content Negotiation
+
HTTP introduces a set of headers, starting with Accept- as a way for a browser to announce the format, language, or encoding it prefers. This article explains how this advertisement happens, how the server is expected to react and how it will choose the most adequate response.
+
diff --git a/files/id/web/http/gambaran/index.html b/files/id/web/http/gambaran/index.html new file mode 100644 index 0000000000..b06d42ac23 --- /dev/null +++ b/files/id/web/http/gambaran/index.html @@ -0,0 +1,173 @@ +--- +title: Gambaran HTTP +slug: Web/HTTP/Gambaran +translation_of: Web/HTTP/Overview +--- +
{{HTTPSidebar}}
+ +

HTTP adalah sebuah {{Glossary("protocol")}} yang memungkinkan pengambilan sumber daya, seperti dokumen HTML. Ini adalah dasar dari pertukaran data apa pun di Web dan itu adalah protokol client-server, yang berarti permintaan diprakarsai oleh penerima (Client), biasanya browser Web. Dokumen lengkap direkonstruksi dari berbagai sub-dokumen yang diambil, misalnya teks, deskripsi tata letak, gambar, video, skrip, dan banyak lagi.

+ +

A Web document is the composition of different resources

+ +

Client dan Server berkomunikasi dengan bertukar pesan individual (sebagai lawan aliran data). Pesan yang dikirim oleh Client, biasanya browser Web, disebut permintaan (requests) dan pesan yang dikirim oleh server sebagai jawaban disebut respons (responses)

+ +

HTTP as an application layer protocol, on top of TCP (transport layer) and IP (network layer) and below the presentation layer.Dirancang pada awal 1990-an, HTTP adalah protokol yang dapat diperluas, yang telah berevolusi dari waktu ke waktu. Ini adalah lapisan aplikasi protokol yang dikirim melalui {{Glossary("TCP")}}, atau melalui koneksi TCP yang terenkripsi {{Glossary("TLS")}} meskipun begitu semua transportasi protokol yang terpercaya secara teori juga dapat digunakan. Karena sifatnya yang dapat diperluas, protokol ini digunakan tidak hanya untuk mengambil dokumen hiperteks, tetapi juga gambar dan video atau untuk memposting konten ke server, sama seperti hasil sebuah form HTML. HTTP juga dapat digunakan untuk mengambil bagian dokumen untuk memperbarui halaman Web sesuai permintaan.

+ +

Components of HTTP-based systems

+ +

HTTP is a client-server protocol: requests are sent by one entity, the user-agent (or a proxy on behalf of it). Most of the time the user-agent is a Web browser, but it can be anything, for example a robot that crawls the Web to populate and maintain a search engine index.

+ +

Each individual request is sent to a server, which handles it and provides an answer, called the response. Between the client and the server there are numerous entities, collectively called {{Glossary("Proxy_server", "proxies")}}, which perform different operations and act as gateways or {{Glossary("Cache", "caches")}}, for example.

+ +

Client server chain

+ +

In reality, there are more computers between a browser and the server handling the request: there are routers, modems, and more. Thanks to the layered design of the Web, these are hidden in the network and transport layers. HTTP is on top, at the application layer. Although important to diagnose network problems, the underlying layers are mostly irrelevant to the description of HTTP.

+ +

Client: the user-agent

+ +

The user-agent is any tool that acts on the behalf of the user. This role is primarily performed by the Web browser; other possibilities are programs used by engineers and Web developers to debug their applications.

+ +

The browser is always the entity initiating the request. It is never the server (though some mechanisms have been added over the years to simulate server-initiated messages).

+ +

To present a Web page, the browser sends an original request to fetch the HTML document that represents the page. It then parses this file, making additional requests corresponding to execution scripts, layout information (CSS) to display, and sub-resources contained within the page (usually images and videos). The Web browser then mixes these resources to present to the user a complete document, the Web page. Scripts executed by the browser can fetch more resources in later phases and the browser updates the Web page accordingly.

+ +

A Web page is a hypertext document. This means some parts of displayed text are links which can be activated (usually by a click of the mouse) to fetch a new Web page, allowing the user to direct their user-agent and navigate through the Web. The browser translates these directions in HTTP requests, and further interprets the HTTP responses to present the user with a clear response.

+ +

The Web server

+ +

On the opposite side of the communication channel, is the server, which serves the document as requested by the client. A server appears as only a single machine virtually: this is because it may actually be a collection of servers, sharing the load (load balancing) or a complex piece of software interrogating other computers (like cache, a DB server, or e-commerce servers), totally or partially generating the document on demand.

+ +

A server is not necessarily a single machine, but several server software instances can be hosted on the same machine. With HTTP/1.1 and the {{HTTPHeader("Host")}} header, they may even share the same IP address.

+ +

Proxies

+ +

Between the Web browser and the server, numerous computers and machines relay the HTTP messages. Due to the layered structure of the Web stack, most of these operate at the transport, network or physical levels, becoming transparent at the HTTP layer and potentially making a significant impact on performance. Those operating at the application layers are generally called proxies. These can be transparent, forwarding on the requests they receive without altering them in any way, or non-transparent, in which case they will change the request in some way before passing it along to the server. Proxies may perform numerous functions:

+ + + +

Basic aspects of HTTP

+ +

HTTP is simple

+ +

HTTP is generally designed to be simple and human readable, even with the added complexity introduced in HTTP/2 by encapsulating HTTP messages into frames. HTTP messages can be read and understood by humans, providing easier testing for developers, and reduced complexity for newcomers.

+ +

HTTP is extensible

+ +

Introduced in HTTP/1.0, HTTP headers make this protocol easy to extend and experiment with. New functionality can even be introduced by a simple agreement between a client and a server about a new header's semantics.

+ +

HTTP is stateless, but not sessionless

+ +

HTTP is stateless: there is no link between two requests being successively carried out on the same connection. This immediately has the prospect of being problematic for users attempting to interact with certain pages coherently, for example, using e-commerce shopping baskets. But while the core of HTTP itself is stateless, HTTP cookies allow the use of stateful sessions. Using header extensibility, HTTP Cookies are added to the workflow, allowing session creation on each HTTP request to share the same context, or the same state.

+ +

HTTP and connections

+ +

A connection is controlled at the transport layer, and therefore fundamentally out of scope for HTTP. Though HTTP doesn't require the underlying transport protocol to be connection-based; only requiring it to be reliable, or not lose messages (so at minimum presenting an error). Among the two most common transport protocols on the Internet, TCP is reliable and UDP isn't. HTTP therefore relies on the TCP standard, which is connection-based.

+ +

Before a client and server can exchange an HTTP request/response pair, they must establish a TCP connection, a process which requires several round-trips. The default behavior of HTTP/1.0 is to open a separate TCP connection for each HTTP request/response pair. This is less efficient than sharing a single TCP connection when multiple requests are sent in close succession.

+ +

In order to mitigate this flaw, HTTP/1.1 introduced pipelining (which proved difficult to implement) and persistent connections: the underlying TCP connection can be partially controlled using the {{HTTPHeader("Connection")}} header. HTTP/2 went a step further by multiplexing messages over a single connection, helping keep the connection warm and more efficient.

+ +

Experiments are in progress to design a better transport protocol more suited to HTTP. For example, Google is experimenting with QUIC which builds on UDP to provide a more reliable and efficient transport protocol.

+ +

What can be controlled by HTTP

+ +

This extensible nature of HTTP has, over time, allowed for more control and functionality of the Web. Cache or authentication methods were functions handled early in HTTP history. The ability to relax the origin constraint, by contrast, has only been added in the 2010s.

+ +

Here is a list of common features controllable with HTTP.

+ + + +

HTTP flow

+ +

When a client wants to communicate with a server, either the final server or an intermediate proxy, it performs the following steps:

+ +
    +
  1. Open a TCP connection: The TCP connection is used to send a request, or several, and receive an answer. The client may open a new connection, reuse an existing connection, or open several TCP connections to the servers.
  2. +
  3. Send an HTTP message: HTTP messages (before HTTP/2) are human-readable. With HTTP/2, these simple messages are encapsulated in frames, making them impossible to read directly, but the principle remains the same. For example: +
    GET / HTTP/1.1
    +Host: developer.mozilla.org
    +Accept-Language: fr
    +
  4. +
  5. Read the response sent by the server, such as: +
    HTTP/1.1 200 OK
    +Date: Sat, 09 Oct 2010 14:28:02 GMT
    +Server: Apache
    +Last-Modified: Tue, 01 Dec 2009 20:18:22 GMT
    +ETag: "51142bc1-7449-479b075b2891b"
    +Accept-Ranges: bytes
    +Content-Length: 29769
    +Content-Type: text/html
    +
    +<!DOCTYPE html... (here comes the 29769 bytes of the requested web page)
    +
  6. +
  7. Close or reuse the connection for further requests.
  8. +
+ +

If HTTP pipelining is activated, several requests can be sent without waiting for the first response to be fully received. HTTP pipelining has proven difficult to implement in existing networks, where old pieces of software coexist with modern versions. HTTP pipelining has been superseded in HTTP/2 with more robust multiplexing requests within a frame.

+ +

HTTP Messages

+ +

HTTP messages, as defined in HTTP/1.1 and earlier, are human-readable. In HTTP/2, these messages are embedded into a binary structure, a frame, allowing optimizations like compression of headers and multiplexing. Even if only part of the original HTTP message is sent in this version of HTTP, the semantics of each message is unchanged and the client reconstitutes (virtually) the original HTTP/1.1 request. It is therefore useful to comprehend HTTP/2 messages in the HTTP/1.1 format.

+ +

There are two types of HTTP messages, requests and responses, each with its own format.

+ +

Requests

+ +

An example HTTP request:

+ +

A basic HTTP request

+ +

Requests consists of the following elements:

+ + + +

Responses

+ +

An example response:

+ +

+ +

Responses consist of the following elements:

+ + + +

APIs based on HTTP

+ +

The most commonly used API based on HTTP is the {{domxref("XMLHttpRequest")}} API, which can be used to exchange data between a {{Glossary("user agent")}} and a server. The modern {{domxref("Fetch API")}} provides the same features with a more powerful and flexible feature set.

+ +

Another API, server-sent events, is a one-way service that allows a server to send events to the client, using HTTP as a transport mechanism. Using the {{domxref("EventSource")}} interface, the client opens a connection and establishes event handlers. The client browser automatically converts the messages that arrive on the HTTP stream into appropriate {{domxref("Event")}} objects, delivering them to the event handlers that have been registered for the events' {{domxref("Event.type", "type")}} if known, or to the {{domxref("EventSource.onmessage", "onmessage")}} event handler if no type-specific event handler was established.

+ +

Conclusion

+ +

HTTP is an extensible protocol that is easy to use. The client-server structure, combined with the ability to simply add headers, allows HTTP to advance along with the extended capabilities of the Web.

+ +

Though HTTP/2 adds some complexity, by embedding HTTP messages in frames to improve performance, the basic structure of messages has stayed the same since HTTP/1.0. Session flow remains simple, allowing it to be investigated, and debugged with a simple HTTP message monitor.

diff --git a/files/id/web/http/index.html b/files/id/web/http/index.html new file mode 100644 index 0000000000..3e2144fb57 --- /dev/null +++ b/files/id/web/http/index.html @@ -0,0 +1,81 @@ +--- +title: HTTP +slug: Web/HTTP +tags: + - HTTP + - Referensi + - Web +translation_of: Web/HTTP +--- +
{{HTTPSidebar}}
+ +

Hypertext Transfer Protocol (HTTP) adalah sebuah protokol lapisan-aplikasi untuk mentransmisi dokumen hypermedia, seperti HTML. Ini dirancang untuk komunikasi antara peramban web dan server web, meskipun bisa digunakan untuk keperluan lain juga. Ini mengikuti sebuah model klien-server klasik, dengan sebuah klien membuka sebuah koneksi, membuat sebuah permintaan (request), dan menunggu hingga mendapatkan sebuah respon. Ini juga sebuah protokol tanpa-keadaan, maksudnya server tidak menyimpan data (keadaan) antara kedua permintaan. Meskipun kadang berdasarkan pada sebuah lapisan TCP/IP, bisa digunakan pada lapisan transport andal apa saja;  berarti sebuah protokol tidak kehilangan pesan secara diam-diam, seperti UDP.

+ +
+
+

Tutorial

+ +

Belajar bagaimana untuk menggunakan HTTP dengan panduan dan tutorial.

+ +
+
Ikhtisan dari HTTP
+
Fitur dasar dari protokol klien-server: apa yang bisa digunakan dan penggunaannya.
+
HTTP Cache
+
Caching sangat penting untuk mempercepat situs web. Artikel ini menjelaskan perbedaan metode dalam caching  dan bagaimana menggunakan HTTP Headers untuk mengendalikannya.
+
HTTP Kuki
+
Bagaimana kuki bekerja didefinisi oleh RFC 6265. Pada penerimaan sebuah permintaan HTTP, sebuah server bisa mengirim sebuah header Set-Cookie dengan responnya. Klien kemudian mengembalikan nilai kuki dengan setiap permintaan ke server yang sama dalam bentuk header permintaan Cookie. Kuki juga dapat ditetapkan untuk kadaluarsa pada tanggal tertentu, atau pembatasan pada domain dan jalur tertentu.
+
Cross-Origin Resource Sharing (CORS)
+
Permintaan Cross-site HTTP adalah permintaan HTTP untuk sumber daya dari domain lain kemduian domain dari sumberdaya membuat permintaan. Contohnya, sebuah laman HTML dari Domain A (http://domaina.example/), membuat sebuah permintaan untuk sebuah gambar pada Domain B (http://domainb.foo/image.jpg) malalui elemen img. Laman situs saat ini sangat biasa memuat sumber daya cross-site, termasuk CSS sytlesheets, gambar, skrip, dan sumber daya lainnya. CORS memungkinkan pengembang web untuk mengendaikan bagaimana situs mereka bereaksi kepada permintaan cross-site.
+
+ +
+
Perkembangan dari HTTP
+
Sebuah deskripsi  dari perubahan antara HTTP veri awal, ke HTTP/2 moderen dan seterusnya.
+
Panduan keamanan situs Mozilla
+
Sebuah koleksi dari tip untuk membantu tim operasional dengan membuat aplikasi web yang aman.
+
Pesan HTTP (HTTP Messages)
+
Penjelasan tipe dan struktur dari berbagai jenis dan struktur dari HTTP/1.x dan HTTP/2.
+
Sebuah sesi HTTP yang khas
+
Menunjukan dan menjelaskan alur dari sebuah sesi HTTP biasa.
+
 
+
Manajemen koneksi pada HTTP/1.x
+
Menjelaskan tiga model manajemen koneksi yang tersedia pada HTTP/1.x, serta kelebihan dan kekurangan mereka.
+
+
+ +
+

Referensi

+ +

Jelajahi dokumentasi referensi HTTP yang terperinci.

+ +
+
HTTP Headers
+
Pesan HTTP digunakan untuk menjelaskan secara tepat sumber daya atau perilaku dari server atau klien. header kepemilikan khusus bisa ditambahkan dengan menggunakan awalan X-; yang lain pada sebuah registri IANA, yang konten aslinya didefiniskan di RFC 4229. IANA juga mengelola registri dari usulan baru header pesan HTTP.
+
Metode Permintaan HTTP
+
Berbagai operasi yang bisa dilakukan dengan HTTP: {{HTTPMethod("GET")}}, {{HTTPMethod("POST")}}, tetapi juga permintaan yang kurang umum seperti {{HTTPMethod("OPTIONS")}}, {{HTTPMethod("DELETE")}} atau {{HTTPMethod("TRACE")}}.
+
Kode Status Respon HTTP
+
Kode respon HTTP menunjukan apakah permintaan HTTP tertentu berhasil diselesaikan. Respon dikelompokan dalam lima kelas: respon informasi, respon sukses, pengaihan, kesalahan klien, dan kealahan server.
+
Petunjuk CSP (CSP directives)
+
Bidang header respon {{HTTPHeader("Content-Security-Policy")}} memungkinkan administrator situs web untuk mengendalikan sumber daya user agent yang memungkinkan untuk dimuat pada halaman tertentu. Dengan beberapa pengecualian, sebagian besar kebijakan melibatkan penentuan asal server dan skrip titik-akhir (endpoints). 
+
+ +

Alat & sumber daya

+ +

Alat dan sumber daya yang berguna untuk memahami dan debugging HTTP.

+ +
+
Firefox Developer Tools
+
Network monitor
+
Mozilla Observatory
+
+

Sebuah proyek yang dideain untuk membantu pengembang, administrator sistem, dan keamanan profesional mengkonfigurasi situs mereka secara aman.

+
+
RedBot
+
Alat untuk memeriksa header terkati-cache Anda.
+
Bagaimana Peramban Bekerja
+
Sebuah artikel yang sangat komprehensif tentang internal peramban dan alur permintaan melalui protokol HTTP. Sebuah artikel yang HARUS-DIBACA oleh tiap pengembang web.
+
+ +

 

+
+
diff --git a/files/id/web/http/methods/get/index.html b/files/id/web/http/methods/get/index.html new file mode 100644 index 0000000000..ff8f8cdbab --- /dev/null +++ b/files/id/web/http/methods/get/index.html @@ -0,0 +1,73 @@ +--- +title: GET +slug: Web/HTTP/Methods/GET +tags: + - HTTP + - Referensi + - Request method +translation_of: Web/HTTP/Methods/GET +--- +
{{HTTPSidebar}}
+ +

Request HTTP GET method merupakan representasi dari resource spesifik. Request menggunakan GET hanya menerima data.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Request has bodyNo
Successful response has bodyYes
{{Glossary("Safe")}}Yes
{{Glossary("Idempotent")}}Yes
{{Glossary("Cacheable")}}Yes
Allowed in HTML formsYes
+ +

Sintaks

+ +
GET /index.html
+
+ +

Spesifikasi

+ + + + + + + + + + + + +
SpesifikasiJudul
{{RFC("7231", "GET", "4.3.1")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Kompabilitas Browser

+ + + +

{{Compat("http.methods.GET")}}

+ +

Lihat Juga

+ + diff --git a/files/id/web/http/methods/index.html b/files/id/web/http/methods/index.html new file mode 100644 index 0000000000..1045732cc2 --- /dev/null +++ b/files/id/web/http/methods/index.html @@ -0,0 +1,76 @@ +--- +title: HTTP request methods +slug: Web/HTTP/Methods +tags: + - HTTP + - Methods + - Reference + - TopicStub +translation_of: Web/HTTP/Methods +--- +
{{HTTPSidebar}}
+ +
HTTP mendefinisikan seperangkat metode permintaan untuk menunjukkan tindakan yang diinginkan yang akan dilakukan untuk sumber daya tertentu. Meskipun mereka juga bisa menjadi kata benda, metode permintaan ini kadang-kadang disebut sebagai verba HTTP. Masing-masing menerapkan semantik yang berbeda, namun beberapa fitur umum digunakan bersama oleh mereka: mis. Metode permintaan dapat berupa {{glossary("safe")}}, {{glossary("idempotent")}}, atau {{glossary("cacheable")}}.
+ +
 
+ +
+
GET
+
Metode GET meminta representasi sumber daya yang ditentukan. Permintaan menggunakan GET seharusnya hanya mengambil data..
+
HEAD
+
Metode HEAD meminta tanggapan yang identik dengan permintaan GET, namun tanpa respon body.
+
POST
+
Metode POST digunakan untuk mengirimkan entitas ke sumber daya yang ditentukan, sering menyebabkan perubahan pada keadaan atau efek samping pada server.
+
PUT
+
+

Metode PUT menggantikan semua representasi terkini dari sumber target dengan muatan permintaan.

+
+
DELETE
+
Metode DELETE akan menghapus sumber daya yang ditentukan.
+
CONNECT
+
+

Metode CONNECT menetapkan terowongan ke server yang diidentifikasi oleh sumber target.

+
+
OPTIONS
+
Metode OPTIONS digunakan untuk menggambarkan opsi komunikasi untuk sumber target.
+
TRACE
+
+

Metode TRACE melakukan tes pesan loop-back di sepanjang jalan menuju sumber daya target.

+
+
PATCH
+
Metode PATCH digunakan untuk menerapkan modifikasi sebagian pada sumber daya.
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiJudulKomentar
{{RFC("7231", "Request methods", "4")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and ContentSpecifies GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE.
{{RFC("5789", "Patch method", "2")}}PATCH Method for HTTPSpecifies PATCH.
+ +

Kompabilitas Browser

+ + + +

{{Compat("http.methods")}}

+ +

Lihat Juga

+ + diff --git a/files/id/web/http/proxy_servers_and_tunneling/index.html b/files/id/web/http/proxy_servers_and_tunneling/index.html new file mode 100644 index 0000000000..f035225649 --- /dev/null +++ b/files/id/web/http/proxy_servers_and_tunneling/index.html @@ -0,0 +1,100 @@ +--- +title: Proxy servers and tunneling +slug: Web/HTTP/Proxy_servers_and_tunneling +tags: + - HTTP + - HTTP Tunneling + - NeedsTranslation + - Proxies + - Proxy + - TopicStub +translation_of: Web/HTTP/Proxy_servers_and_tunneling +--- +
{{HTTPSidebar}}
+ +

When navigating through different networks of the Internet, proxy servers and HTTP tunnels are facilitating access to content on the World Wide Web. A proxy can be on the user's local computer, or anywhere between the user's computer and a destination server on the Internet. This page outlines some basics about proxies and introduces a few configuration options.

+ +

There are two types of proxies: forward proxies (or tunnel, or gateway) and reverse proxies (used to control and protect access to a server for load-balancing, authentication, decryption or caching).

+ +

Forward proxies

+ +

A forward proxy, or gateway, or just "proxy" provides proxy services to a client or a group of clients. There are likely hundreds of thousands of open forward proxies on the Internet. They store and forward Internet services (like the DNS, or web pages) to reduce and control the bandwidth used by the group.

+ +

Forward proxies can also be anonymous proxies and allow users to hide their IP address while browsing the Web or using other Internet services. TOR (The Onion Router), routes internet traffic through multiple proxies for anonymity.

+ +

Reverse proxies

+ +

As the name implies, a reverse proxy does the opposite of what a forward proxy does: A forward proxy acts on behalf of clients (or requesting hosts). Forward proxies can hide the identities of clients whereas reverse proxies can hide the identities of servers. Reverse proxies have several use cases, a few are:

+ + + +

Forwarding client information through proxies

+ +

Proxies can make requests appear as if they originated from the proxy's IP address. This can be useful if a proxy is used to provide client anonymity, but in other cases information from the original request is lost. The IP address of the original client is often used for debugging, statistics, or generating location-dependent content. A common way to disclose this information is by using the following HTTP headers:

+ +

The standardized header:

+ +
+
{{HTTPHeader("Forwarded")}}
+
Contains information from the client-facing side of proxy servers that is altered or lost when a proxy is involved in the path of the request.
+
+ +

Or the de-facto standard versions:

+ +
+
{{HTTPHeader("X-Forwarded-For")}} {{non-standard_inline}}
+
Identifies the originating IP addresses of a client connecting to a web server through an HTTP proxy or a load balancer.
+
{{HTTPHeader("X-Forwarded-Host")}} {{non-standard_inline}}
+
Identifies the original host requested that a client used to connect to your proxy or load balancer.
+
{{HTTPHeader("X-Forwarded-Proto")}} {{non-standard_inline}}
+
identifies the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer.
+
+ +

To provide information about the proxy itself (not about the client connecting to it), the Via header can be used.

+ +
+
{{HTTPHeader("Via")}}
+
Added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers.
+
+ +

HTTP tunneling

+ +

Tunneling transmits private network data and protocol information through public network by encapsulating the data. HTTP tunneling is using a protocol of higher level (HTTP) to transport a lower level protocol (TCP).

+ +

The HTTP protocol specifies a request method called {{HTTPMethod("CONNECT")}}. It starts two-way communications with the requested resource and can be used to open a tunnel. This is how a client behind an HTTP proxy can access websites using SSL (i.e. HTTPS, port 443). Note, however, that not all proxy servers support the CONNECT method or limit it to port 443 only.

+ +

See also the HTTP tunnel article on Wikipedia.

+ +

Proxy Auto-Configuration (PAC)

+ +

A Proxy Auto-Configuration (PAC) file is a JavaScript function that determines whether web browser requests (HTTP, HTTPS, and FTP) go directly to the destination or are forwarded to a web proxy server. The JavaScript function contained in the PAC file defines the function:

+ +

The auto-config file should be saved to a file with a .pac filename extension:

+ +
proxy.pac
+ +

And the MIME type set to:

+ +
application/x-ns-proxy-autoconfig
+ +

The file consists of a function called FindProxyForURL. The example below will work in an environment where the internal DNS server is set up so that it can only resolve internal host names, and the goal is to use a proxy only for hosts that aren't resolvable:

+ +
function FindProxyForURL(url, host) {
+  if (isResolvable(host))
+    return "DIRECT";
+  else
+    return "PROXY proxy.mydomain.com:8080";
+}
+ +

See Proxy Auto-Configuration (PAC) for more examples.

+ +

See also

+ + diff --git a/files/id/web/http/proxy_servers_and_tunneling/proxy_auto-configuration_(pac)_file/index.html b/files/id/web/http/proxy_servers_and_tunneling/proxy_auto-configuration_(pac)_file/index.html new file mode 100644 index 0000000000..c470d2fe27 --- /dev/null +++ b/files/id/web/http/proxy_servers_and_tunneling/proxy_auto-configuration_(pac)_file/index.html @@ -0,0 +1,727 @@ +--- +title: Proxy Auto-Configuration (PAC) file +slug: Web/HTTP/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_(PAC)_file +translation_of: Web/HTTP/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_(PAC)_file +--- +
{{HTTPSidebar}}
+ +

File Proxy Auto-Configuration (PAC) adalah fungsi JavaScript yang menentukan apakah permintaan browser web (HTTP, HTTPS, dan FTP) langsung ke tujuan atau diteruskan ke server proxy web. Fungsi JavaScript yang terdapat dalam file PAC mendefinisikan fungsi tersebut:

+ +
function FindProxyForURL(url, host) {
+  // ...
+}
+ +

Sintaksis

+ +
function FindProxyForURL(url, host)
+ +

Parameter

+ +
+
url
+
URL sedang diakses. Jalur dan komponen kueri https://URL dihilangkan. Di Chrome (versi 52 hingga 73), Anda dapat menonaktifkan ini dengan menyetel PacHttpsUrlStrippingEnabledke falsedalam kebijakan atau dengan meluncurkan dengan --unsafe-pac-urlbendera baris perintah (di Chrome 74, hanya bendera yang berfungsi, dan dari 75 dan seterusnya, tidak ada cara untuk menonaktifkan jalur- pengupasan; mulai Chrome 81, pengupasan jalur tidak berlaku untuk URL HTTP, tetapi ada minat untuk mengubah perilaku ini agar cocok dengan HTTPS); di Firefox, preferensinya adalah network.proxy.autoconfig_url.include_path.
+
host
+
Nama host diekstrak dari URL. Ini hanya untuk kenyamanan; itu adalah string yang sama seperti antara ://dan yang pertama :atau /setelah itu. Nomor port tidak termasuk dalam parameter ini. Ini dapat diekstrak dari URL bila perlu.
+
+ +

Deskripsi

+ +

Mengembalikan string yang menjelaskan konfigurasi. Format string ini ditentukan dalam format nilai pengembalian di bawah ini.

+ +

Format nilai pengembalian

+ + + +
+
DIRECT
+
Koneksi harus dibuat secara langsung, tanpa proxy apa pun
+
PROXY host:port
+
Proksi yang ditentukan harus digunakan
+
SOCKS host:port
+
Server SOCKS yang ditentukan harus digunakan
+
+ +

Versi terbaru Firefox juga mendukung:

+ +
+
HTTP host:port
+
Proksi yang ditentukan harus digunakan
+
HTTPS host:port
+
Proksi HTTPS yang ditentukan harus digunakan
+
SOCKS4 host:port
+
SOCKS5 host:port
+
Server SOCKS yang ditentukan (dengan versi SOCK yang ditentukan) harus digunakan
+
+ +

Jika ada beberapa pengaturan yang dipisahkan titik koma, pengaturan paling kiri akan digunakan, sampai Firefox gagal membuat sambungan ke proxy. Dalam hal ini, nilai selanjutnya akan digunakan, dll.

+ +

Browser akan secara otomatis mencoba proxy yang sebelumnya tidak merespons setelah 30 menit. Upaya tambahan akan berlanjut mulai dari satu jam, selalu menambahkan 30 menit ke waktu yang telah berlalu di antara upaya.

+ +

Jika semua proxy sedang down, dan tidak ada opsi LANGSUNG yang ditentukan, browser akan menanyakan apakah proxy harus diabaikan untuk sementara, dan koneksi langsung diupayakan. Setelah 20 menit, browser akan menanyakan apakah proxy harus dicoba lagi, menanyakan lagi setelah 40 menit tambahan. Kueri akan berlanjut, selalu menambahkan 20 menit ke waktu yang telah berlalu di antara kueri.

+ +

Contoh

+ +
+
PROXY w3proxy.netscape.com:8080; PROXY mozilla.netscape.com:8081
+
Proksi utama adalah w3proxy: 8080; jika turun, mulailah menggunakan mozilla: 8081 hingga proxy utama muncul lagi.
+
PROXY w3proxy.netscape.com:8080; PROXY mozilla.netscape.com:8081; DIRECT
+
Sama seperti di atas, tetapi jika kedua proxy turun, secara otomatis mulai membuat koneksi langsung. (Pada contoh pertama di atas, Netscape akan menanyakan konfirmasi pengguna tentang membuat koneksi langsung; dalam hal ini, tidak ada intervensi pengguna.)
+
PROXY w3proxy.netscape.com:8080; SOCKS socks:1080
+
Gunakan SOCKS jika proxy utama mati.
+
+ +

File konfigurasi otomatis harus disimpan ke file dengan ekstensi nama file .pac:

+ +
proxy.pac
+ +

Dan tipe MIME harus disetel ke:

+ +
application/x-ns-proxy-autoconfig
+ +

Selanjutnya, Anda harus mengkonfigurasi server Anda untuk memetakan ekstensi nama file .pac ke jenis MIME.

+ +
+

Catatan:

+ +
    +
  • Fungsi JavaScript harus selalu disimpan ke file dengan sendirinya tetapi tidak disematkan dalam file HTML atau file lainnya.
  • +
  • Contoh-contoh di akhir dokumen ini lengkap. Tidak ada sintaks tambahan yang diperlukan untuk menyimpannya ke dalam file dan menggunakannya. (Tentu saja, JavaScripts harus diedit untuk mencerminkan nama domain dan / atau subnet situs Anda.)
  • +
+
+ +

Fungsi dan lingkungan yang telah ditentukan sebelumnya

+ +

Fungsi-fungsi ini dapat digunakan untuk membuat file PAC:

+ + + +
+

Catatan: pactester (bagian dari paket pacparser ) digunakan untuk menguji contoh sintaks berikut.

+ +
    +
  • File PAC diberi nama proxy.pac
  • +
  • Baris perintah: pactester -p ~/pacparser-master/tests/proxy.pac -u http://www.mozilla.org(melewati hostparameter www.mozilla.orgdan urlparameter http://www.mozilla.org)
  • +
+
+ +

isPlainHostName ()

+ +

Sintaksis

+ +
isPlainHostName(host)
+ +

Parameter

+ +
+
tuan rumah
+
Nama host dari URL (tidak termasuk nomor port).
+
+ +

Deskripsi

+ +

Benar jika dan hanya jika tidak ada nama domain di nama host (tidak ada titik).

+ +

Contoh

+ +
isPlainHostName("www.mozilla.org") // false
+isPlainHostName("www") // true
+
+ +

dnsDomainIs()

+ +

Sintaksis

+ +
dnsDomainIs(host, domain)
+ +

Parameter

+ +
+
tuan rumah
+
Apakah nama host dari URL.
+
domain
+
Apakah nama domain untuk menguji nama host.
+
+ +

Deskripsi

+ +

Mengembalikan nilai benar jika dan hanya jika domain nama host cocok.

+ +

Contoh

+ +
dnsDomainIs("www.mozilla.org", ".mozilla.org") // true
+dnsDomainIs("www", ".mozilla.org") // false
+
+ +

localHostOrDomainIs ()

+ +

Sintaksis

+ +
localHostOrDomainIs(host, hostdom)
+ +

Parameter

+ +
+
tuan rumah
+
Nama host dari URL.
+
tuan rumah
+
Nama host yang sepenuhnya memenuhi syarat untuk dicocokkan.
+
+ +

Deskripsi

+ +

Benar jika nama host sama persis dengan nama host yang ditentukan, atau jika tidak ada bagian nama domain dalam nama host, tetapi nama host yang tidak memenuhi syarat cocok.

+ +

Contoh

+ +
localHostOrDomainIs("www.mozilla.org" , "www.mozilla.org") // true (exact match)
+localHostOrDomainIs("www"             , "www.mozilla.org") // true (hostname match, domain not specified)
+localHostOrDomainIs("www.google.com"  , "www.mozilla.org") // false (domain name mismatch)
+localHostOrDomainIs("home.mozilla.org", "www.mozilla.org") // false (hostname mismatch)
+ +

isResolvable ()

+ +

Sintaksis

+ +
isResolvable(host)
+ +

Parameter

+ +
+
tuan rumah
+
adalah nama host dari URL.
+
+ +

Mencoba menyelesaikan nama host. Mengembalikan nilai benar jika berhasil.

+ +

Contoh:

+ +
isResolvable("www.mozilla.org") // true
+
+ +

isInNet ()

+ +

Sintaksis

+ +
isInNet(host, pattern, mask)
+ +

Parameter

+ +
+
tuan rumah
+
nama host DNS, atau alamat IP. Jika nama host dilewatkan, itu akan diselesaikan menjadi alamat IP dengan fungsi ini.
+
pola
+
pola alamat IP dalam format yang dipisahkan titik.
+
topeng
+
mask untuk pola alamat IP yang menginformasikan bagian mana dari alamat IP yang harus dicocokkan. 0 berarti abaikan, 255 berarti cocok.
+
+ +

True jika dan hanya jika alamat IP dari host cocok dengan pola alamat IP yang ditentukan.

+ +

Spesifikasi pola dan topeng dilakukan dengan cara yang sama seperti untuk konfigurasi SOCKS.

+ +

Contoh:

+ +
function alert_eval(str) { alert(str + ' is ' + eval(str)) }
+function FindProxyForURL(url, host) {
+  alert_eval('isInNet(host, "63.245.213.24", "255.255.255.255")')
+  // "PAC-alert: isInNet(host, "63.245.213.24", "255.255.255.255") is true"
+}
+
+ +

dnsResolve ()

+ +
dnsResolve(host)
+ +

Parameter

+ +
+
tuan rumah
+
nama host untuk diselesaikan.
+
+ +

Menyelesaikan nama host DNS yang diberikan menjadi alamat IP, dan mengembalikannya dalam format yang dipisahkan titik sebagai string.

+ +

Contoh

+ +
dnsResolve("www.mozilla.org"); // returns the string "104.16.41.2"
+ +

convert_addr ()

+ +

Sintaksis

+ +
convert_addr(ipaddr)
+ +

Parameter

+ +
+
ipaddr
+
Alamat bertitik apa pun seperti alamat IP atau topeng.
+
+ +

Menggabungkan empat byte yang dipisahkan titik menjadi satu kata 4-byte dan mengubahnya menjadi desimal.

+ +

Contoh

+ +
convert_addr("104.16.41.2"); // returns the decimal number 1745889538
+ +

myIpAddress ()

+ +

Sintaksis

+ +
myIpAddress()
+ +

Parameter

+ +

(tidak ada)

+ +

Mengembalikan alamat IP server dari mesin tempat Firefox dijalankan, sebagai string dalam format bilangan bulat yang dipisahkan titik.

+ +
+

myIpAddress () mengembalikan alamat IP yang sama dengan alamat server yang dikembalikan oleh nslookup localhost mesin Linux. Itu tidak mengembalikan alamat IP publik.

+
+ +

Contoh

+ +
myIpAddress() //returns the string "127.0.1.1" if you were running Firefox on that localhost
+ +

dnsDomainLevels ()

+ +

Sintaksis

+ +
dnsDomainLevels(host)
+ +

Parameter

+ +
+
tuan rumah
+
adalah nama host dari URL.
+
+ +

Mengembalikan angka (bilangan bulat) dari level domain DNS (jumlah titik) di nama host.

+ +

Contoh:

+ +
dnsDomainLevels("www");             // 0
+dnsDomainLevels("mozilla.org");     // 1
+dnsDomainLevels("www.mozilla.org"); // 2
+
+ +

shExpMatch ()

+ +

Sintaksis

+ +
shExpMatch(str, shexp)
+ +

Parameter

+ +
+
str
+
adalah sembarang string untuk dibandingkan (mis. URL, atau nama host).
+
shexp
+
adalah ekspresi shell untuk dibandingkan.
+
+ +

Mengembalikan nilai benar jika string cocok dengan ekspresi shell yang ditentukan.

+ +

Perhatikan bahwa polanya adalah ekspresi shell glob , bukan ekspresi reguler. *dan ?selalu didukung, sementara [characters]dan [^characters]didukung oleh beberapa implementasi termasuk Firefox. Ini terutama karena ekspresi diterjemahkan ke RegExp melalui subsitusi [.*?]. Untuk cara yang dapat diandalkan untuk menggunakan sintaks RegExp ini, cukup gunakan RegExp sebagai gantinya.

+ +

Contoh

+ +
shExpMatch("http://home.netscape.com/people/ari/index.html"     , "*/ari/*"); // returns true
+shExpMatch("http://home.netscape.com/people/montulli/index.html", "*/ari/*"); // returns false
+ +

weekdayRange ()

+ +

Sintaksis

+ +
weekdayRange(wd1, wd2, [gmt])
+ +
+

Catatan: (Sebelum Firefox 49) wd1 harus lebih kecil dari wd2 jika Anda ingin fungsi mengevaluasi parameter ini sebagai rentang. Lihat peringatan di bawah.

+
+ +

Parameter

+ +
+
wd1 dan wd2
+
Salah satu string hari kerja yang dipesan:
+
+
"SUN"|"MON"|"TUE"|"WED"|"THU"|"FRI"|"SAT"
+
+
waktu Greenwich
+
Apakah string "GMT" atau ditinggalkan.
+
+ +

Hanya parameter pertama yang wajib diisi. Entah yang kedua, ketiga, atau keduanya mungkin ditinggalkan.

+ +

Jika hanya satu parameter yang ada, fungsi mengembalikan nilai true pada hari kerja yang diwakili oleh parameter. Jika string "GMT" ditetapkan sebagai parameter kedua, waktu dianggap dalam GMT. Jika tidak, mereka diasumsikan berada dalam zona waktu lokal.

+ +

Jika wd1 dan wd1 ditentukan, kondisinya benar jika hari kerja saat ini berada di antara dua hari kerja yang dipesan . Batas bersifat inklusif, tetapi batasnya teratur . Jika parameter "GMT" ditentukan, waktu dianggap dalam GMT. Jika tidak, zona waktu lokal digunakan.

+ +
+

Urutan hari penting ; Sebelum Firefox 49, akan selalu bernilai true. Sekarang hanya akan mengevaluasi benar jika hari ini adalah Rabu atau Minggu.weekdayRange("SUN", "SAT")weekdayRange("WED", "SUN")

+
+ +

Contoh

+ +
weekdayRange("MON", "FRI");        // returns true Monday through Friday (local timezone)
+weekdayRange("MON", "FRI", "GMT"); // returns true Monday through Friday (GMT timezone)
+weekdayRange("SAT");               // returns true on Saturdays local time
+weekdayRange("SAT", "GMT");        // returns true on Saturdays GMT time
+weekdayRange("FRI", "MON");        // returns true Friday and Monday only (note, order does matter!)
+ +

dateRange()

+ +

Syntax

+ +
dateRange(<day> | <month> | <year>, [gmt])  // ambiguity is resolved by assuming year is greater than 31
+dateRange(<day1>, <day2>, [gmt])
+dateRange(<month1>, <month2>, [gmt])
+dateRange(<year1>, <year2>, [gmt])
+dateRange(<day1>, <month1>, <day2>, <month2>, [gmt])
+dateRange(<month1>, <year1>, <month2>, <year2>, [gmt])
+dateRange(<day1>, <month1>, <year1>, <day2>, <month2>, <year2>, [gmt])
+ +
+

Note: (Before Firefox 49) day1 must be less than day2, month1 must be less than month2, and year1 must be less than year2 if you want the function to evaluate these parameters as a range. See the warning below.

+
+ +

Parameters

+ +
+
day
+
Is the ordered day of the month between 1 and 31 (as an integer).
+
+ +
1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31
+ +
+
month
+
Is one of the ordered month strings below.
+
+ +
"JAN"|"FEB"|"MAR"|"APR"|"MAY"|"JUN"|"JUL"|"AUG"|"SEP"|"OCT"|"NOV"|"DEC"
+ +
+
year
+
Is the ordered full year integer number. For example, 2016 (not 16).
+
gmt
+
Is either the string "GMT", which makes time comparison occur in GMT timezone, or is left out. If left unspecified, times are taken to be in the local timezone.
+
+ +

Jika hanya satu nilai yang ditentukan (dari setiap kategori: hari, bulan, tahun), fungsi mengembalikan nilai sebenarnya hanya pada hari yang cocok dengan spesifikasi tersebut. Jika kedua nilai ditentukan, hasilnya adalah benar di antara waktu-waktu tersebut, termasuk batas, tetapi batasnya diurutkan .

+ +
+

Urutan hari, bulan, dan tahun penting ; Sebelum Firefox 49, akan selalu mengevaluasi ke . Sekarang hanya akan mengevaluasi benar jika bulan ini adalah Desember atau Januari.dateRange("JAN", "DEC")truedateRange("DEC", "JAN")

+
+ +

Contoh

+ +
dateRange(1);            // returns true on the first day of each month, local timezone
+dateRange(1, "GMT")      // returns true on the first day of each month, GMT timezone
+dateRange(1, 15);        // returns true on the first half of each month
+dateRange(24, "DEC");    // returns true on 24th of December each year
+dateRange("JAN", "MAR"); // returns true on the first quarter of the year
+
+dateRange(1, "JUN", 15, "AUG");
+// returns true from June 1st until August 15th, each year
+// (including June 1st and August 15th)
+
+dateRange(1, "JUN", 1995, 15, "AUG", 1995);
+// returns true from June 1st, 1995, until August 15th, same year
+
+dateRange("OCT", 1995, "MAR", 1996);
+// returns true from October 1995 until March 1996
+// (including the entire month of October 1995 and March 1996)
+
+dateRange(1995);
+// returns true during the entire year of 1995
+
+dateRange(1995, 1997);
+// returns true from beginning of year 1995 until the end of year 1997
+ +

rentang waktu()

+ +

Sintaksis

+ +
// The full range of expansions is analogous to dateRange.
+timeRange(<hour1>, <min1>, <sec1>, <hour2>, <min2>, <sec2>, [gmt])
+ +
+

Catatan: (Sebelum Firefox 49) kategori hour1, min1, sec1 harus kurang dari kategori hour2, min2, sec2 jika Anda ingin fungsi mengevaluasi parameter ini sebagai rentang. Lihat peringatan di bawah.

+
+ +

Parameter

+ +
+
jam
+
Adalah jam dari 0 hingga 23. (0 adalah tengah malam, 23 adalah 11 malam.)
+
min
+
Menit dari 0 hingga 59.
+
detik
+
Detik dari 0 hingga 59.
+
waktu Greenwich
+
Baik string "GMT" untuk zona waktu GMT, atau tidak ditentukan, untuk zona waktu lokal.
+
+ +

Jika hanya satu nilai yang ditentukan (dari setiap kategori: jam, menit, detik), fungsi mengembalikan nilai sebenarnya hanya pada waktu yang sesuai dengan spesifikasi tersebut. Jika kedua nilai ditentukan, hasilnya adalah benar di antara waktu-waktu tersebut, termasuk batas, tetapi batasnya diurutkan .

+ +
+

Urutan jam, menit, materi kedua ; Sebelum Firefox 49, akan selalu bernilai true. Sekarang hanya akan mengevaluasi benar jika jam saat ini adalah 23:00 atau tengah malam.timeRange(0, 23)timeRange(23, 0)

+
+ +

Contoh

+ +
timerange(12);                // returns true from noon to 1pm
+timerange(12, 13);            // returns true from noon to 1pm
+timerange(12, "GMT");         // returns true from noon to 1pm, in GMT timezone
+timerange(9, 17);             // returns true from 9am to 5pm
+timerange(8, 30, 17, 00);     // returns true from 8:30am to 5:00pm
+timerange(0, 0, 0, 0, 0, 30); // returns true between midnight and 30 seconds past midnight
+ +

Contoh 1

+ +

Gunakan proxy untuk semuanya kecuali host lokal

+ +
+

Catatan: Karena semua contoh berikut sangat spesifik, mereka belum diuji.

+
+ +

All hosts which aren't fully qualified, or the ones that are in local domain, will be connected to directly. Everything else will go through w3proxy.mozilla.org:8080. If the proxy goes down, connections become direct automatically:

+ +
function FindProxyForURL(url, host) {
+  if (isPlainHostName(host) || dnsDomainIs(host, ".mozilla.org")) {
+    return "DIRECT";
+  } else {
+    return "PROXY w3proxy.mozilla.org:8080; DIRECT";
+  }
+}
+ +
+

Note: This is the simplest and most efficient autoconfig file for cases where there's only one proxy.

+
+ +

Example 2

+ +

As above, but use proxy for local servers which are outside the firewall

+ +

If there are hosts (such as the main Web server) that belong to the local domain but are outside the firewall and are only reachable through the proxy server, those exceptions can be handled using the localHostOrDomainIs() function:

+ +
function FindProxyForURL(url, host) {
+  if (
+    (isPlainHostName(host) || dnsDomainIs(host, ".mozilla.org")) &&
+    !localHostOrDomainIs(host, "www.mozilla.org") &&
+    !localHostOrDoaminIs(host, "merchant.mozilla.org")
+  ) {
+    return "DIRECT";
+  } else {
+    return "PROXY w3proxy.mozilla.org:8080; DIRECT";
+  }
+}
+ +

The above example will use the proxy for everything except local hosts in the mozilla.org domain, with the further exception that hosts www.mozilla.org and merchant.mozilla.org will go through the proxy.

+ +
+

Note the order of the above exceptions for efficiency: localHostOrDomainIs() functions only get executed for URLs that are in local domain, not for every URL. Be careful to note the parentheses around the or expression before the and expression to achieve the above-mentioned efficient behaviour.

+
+ +

Example 3

+ +

Use proxy only if cannot resolve host

+ +

This example will work in an environment where the internal DNS server is set up so that it can only resolve internal host names, and the goal is to use a proxy only for hosts that aren't resolvable:

+ +
function FindProxyForURL(url, host) {
+  if (isResolvable(host))
+    return "DIRECT";
+  else
+    return "PROXY proxy.mydomain.com:8080";
+}
+ +

The above requires consulting the DNS every time; it can be grouped intelligently with other rules so that DNS is consulted only if other rules do not yield a result:

+ +
function FindProxyForURL(url, host) {
+  if (
+    isPlainHostName(host) ||
+    dnsDomainIs(host, ".mydomain.com") ||
+    isResolvable(host)
+  ) {
+    return "DIRECT";
+  } else {
+    return "PROXY proxy.mydomain.com:8080";
+  }
+}
+ +

Example 4

+ +

Subnet based decisions

+ +

In this example all of the hosts in a given subnet are connected-to directly, others are connected through the proxy:

+ +
function FindProxyForURL(url, host) {
+  if (isInNet(host, "198.95.0.0", "255.255.0.0"))
+    return "DIRECT";
+  else
+    return "PROXY proxy.mydomain.com:8080";
+}
+ +

Again, use of the DNS server in the above can be minimized by adding redundant rules in the beginning:

+ +
function FindProxyForURL(url, host) {
+  if (
+    isPlainHostName(host) ||
+    dnsDomainIs(host, ".mydomain.com") ||
+    isInNet(host, "198.95.0.0", "255.255.0.0")
+  ) {
+    return "DIRECT";
+  } else {
+    return "PROXY proxy.mydomain.com:8080";
+  }
+}
+ +

Example 5

+ +

Load balancing/routing based on URL patterns

+ +

This example is more sophisticated. There are four (4) proxy servers; one of them is a hot stand-by for all of the other ones, so if any of the remaining three goes down the fourth one will take over. Furthermore, the three remaining proxy servers share the load based on URL patterns, which makes their caching more effective (there is only one copy of any document on the three servers - as opposed to one copy on each of them). The load is distributed like this:

+ + + + + + + + + + + + + + + + + + + + + + + + +
ProxyPurpose
#1.com domain
#2.edu domain
#3all other domains
#4hot stand-by
+ +

All local accesses are desired to be direct. All proxy servers run on the port 8080 (they don't need to, you can just change your port but remember to modify your configuations on both side). Note how strings can be concatenated with the + operator in JavaScript.

+ +
function FindProxyForURL(url, host) {
+
+  if (isPlainHostName(host) || dnsDomainIs(host, ".mydomain.com"))
+    return "DIRECT";
+
+  else if (shExpMatch(host, "*.com"))
+    return "PROXY proxy1.mydomain.com:8080; " +
+           "PROXY proxy4.mydomain.com:8080";
+
+  else if (shExpMatch(host, "*.edu"))
+    return "PROXY proxy2.mydomain.com:8080; " +
+           "PROXY proxy4.mydomain.com:8080";
+
+  else
+    return "PROXY proxy3.mydomain.com:8080; " +
+           "PROXY proxy4.mydomain.com:8080";
+}
+ +

Example 6

+ +

Setting a proxy for a specific protocol

+ +

Most of the standard JavaScript functionality is available for use in the FindProxyForURL() function. As an example, to set different proxies based on the protocol the {{jsxref("String.prototype.startsWith()", "startsWith()")}} function can be used:

+ +
function FindProxyForURL(url, host) {
+
+  if (url.startsWith("http:"))
+    return "PROXY http-proxy.mydomain.com:8080";
+
+  else if (url.startsWith("ftp:"))
+    return "PROXY ftp-proxy.mydomain.com:8080";
+
+  else if (url.startsWith(“gopher:"))
+    return "PROXY gopher-proxy.mydomain.com:8080";
+
+  else if (url.startsWith("https:") || url.startsWith("snews:"))
+    return "PROXY security-proxy.mydomain.com:8080";
+
+  else
+    return "DIRECT";
+
+}
+ +
+

Note: The same can be accomplished using the shExpMatch() function described earlier.

+
+ +

For example:

+ +
// ...
+if (shExpMatch(url, "http:*")) {
+  return "PROXY http-proxy.mydomain.com:8080";
+}
+// ...
+ +
+

The autoconfig file can be output by a CGI script. This is useful, for example, when making the autoconfig file act differently based on the client IP address (the REMOTE_ADDR environment variable in CGI).

+ +

Usage of isInNet(), isResolvable() and dnsResolve() functions should be carefully considered, as they require the DNS server to be consulted. All the other autoconfig-related functions are mere string-matching functions that don't require the use of a DNS server. If a proxy is used, the proxy will perform its DNS lookup which would double the impact on the DNS server. Most of the time these functions are not necessary to achieve the desired result.

+
+ +

History and implementation

+ +

Proxy auto-config was introduced into Netscape Navigator 2.0 in the late 1990s, at the same time when JavaScript was introduced. Open-sourcing Netscape eventually lead to Firefox itself.

+ +

Oleh karena itu, implementasi PAC yang paling "asli" dan pustaka JavaScript-nya nsProxyAutoConfig.jsditemukan di versi awal Firefox. Utilitas ini ditemukan di banyak sistem sumber terbuka lainnya termasuk Chromium . Firefox kemudian mengintegrasikan file tersebut menjadi ProxyAutoConfig.cppliteral string C ++. Untuk mengekstraknya ke dalam filenya sendiri, cukup dengan menyalin potongan ke JavaScript dengan console.logperintah untuk mencetaknya.

+ +

Microsoft secara umum membuat implementasinya sendiri. Dulu ada beberapa masalah dengan pustaka mereka , tetapi sebagian besar telah diselesaikan sekarang. Mereka telah mendefinisikan beberapa fungsi sufiks "Ex" baru di sekitar bagian penanganan alamat untuk mendukung IPv6. Fitur ini didukung oleh Chromium, tetapi belum didukung oleh Firefox ( bugzilla # 558253 ).

diff --git a/files/id/web/http/status/100/index.html b/files/id/web/http/status/100/index.html new file mode 100644 index 0000000000..3f2f0db1d2 --- /dev/null +++ b/files/id/web/http/status/100/index.html @@ -0,0 +1,46 @@ +--- +title: 100 Continue +slug: Web/HTTP/Status/100 +tags: + - HTTP + - Informasi + - Status code +translation_of: Web/HTTP/Status/100 +--- +
{{HTTPSidebar}}
+ +

HTTP 100 Continue menginformasikan status kode respon yang menandakan bahwa semuanya OK dan klien dapat melanjutkan dengan permintaan atau mengabaikan jika telah terselesaikan.

+ +

Untuk bisa mendapatkan server check pada header permintaan, klien harus mengirim Expect: 100-continue sebagai header pada permintaan inisial dan mendapatan kode status respon 100 Continue sebelum mengirim konten atau body.

+ +

Status

+ +
100 Continue
+ +

Spesifikasi

+ + + + + + + + + + + + +
SpesifikasiTitle
{{RFC("7231", "100 Continue" , "6.2.1")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Kompabilitas Browser

+ + + +

{{Compat("http/status", "100")}}

+ +

Lihat Juga

+ + diff --git a/files/id/web/http/status/200/index.html b/files/id/web/http/status/200/index.html new file mode 100644 index 0000000000..76c06a3e1e --- /dev/null +++ b/files/id/web/http/status/200/index.html @@ -0,0 +1,50 @@ +--- +title: 200 OK +slug: Web/HTTP/Status/200 +translation_of: Web/HTTP/Status/200 +--- +
{{HTTPSidebar}}
+ +

HTTP 200 OK respon status sukses merupakan kode respon yang menandakan bahwa request sukses. respon 200 dapat dichace secara default.

+ +

Arti dari sukses tergantung pada fungsi request HTTP:

+ + + +

Kesuksesan hasil dari {{HTTPMethod("PUT")}} atau {{HTTPMethod("DELETE")}} biasanya bukan 200 OK tapi {{HTTPStatus("204")}} No Content (atau {{HTTPStatus("201")}} Created ketika resource diunggah pertama kali).

+ +

Status

+ +
200 OK
+ +

Spesifikasi

+ + + + + + + + + + + + +
SpesifikasiJudul
{{RFC("7231", "200 OK" , "6.3.1")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Kompabilitas Browser

+ + + +

{{Compat("http.status.200")}}

+ +

Lihat Juga

+ + diff --git a/files/id/web/http/status/400/index.html b/files/id/web/http/status/400/index.html new file mode 100644 index 0000000000..3d98750338 --- /dev/null +++ b/files/id/web/http/status/400/index.html @@ -0,0 +1,39 @@ +--- +title: 400 Bad Request +slug: Web/HTTP/Status/400 +tags: + - Galat Klien + - HTTP + - Kode status + - Referensi + - Status kode HTTP +translation_of: Web/HTTP/Status/400 +--- +
{{HTTPSidebar}}
+ +

Kode Respon HTTP 400 Bad Request mengindikasikan bahwa server tidak bisa atau tidak akan memproses permintaan karena sesuatu yang dianggap sebagai kesalahan klien (seperti sintaks permintaan yang jelek, pesan request yang tidak valid, atau permintaan yang menipu.

+ +
+

Klien seharusnya tidak mengulangi permintaan yang sama tanpa perubahan.

+
+ +

Status

+ +
400 Bad Request 
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpecificationTitle
{{RFC("7231", "400 Bad Request" , "6.5.1")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
diff --git a/files/id/web/http/status/403/index.html b/files/id/web/http/status/403/index.html new file mode 100644 index 0000000000..71dc858a2f --- /dev/null +++ b/files/id/web/http/status/403/index.html @@ -0,0 +1,56 @@ +--- +title: 403 Forbidden +slug: Web/HTTP/Status/403 +tags: + - Galat Klien + - HTTP + - Kode status + - Referensi +translation_of: Web/HTTP/Status/403 +--- +
{{HTTPSidebar}}
+ +

Kode respon HTTP 403 Forbidden mengindikasikan bahwa server memahami permintaan tetapi menolak untuk mengesahkannya.

+ +

Kode status ini mirip dengan {{HTTPStatus("401")}}, tetapi dalam kasus ini, autentikasi ulang tidak akan memberi perubahan. Aksesnya dilarang secara permanen dan diikat pada logika aplikasi, seperti kurangnya hak akses untuk mendapatkan sumber daya.

+ +

Status

+ +
403 Forbidden
+ +

Contoh respon

+ +
HTTP/1.1 403 Forbidden
+Date: Wed, 21 Oct 2015 07:28:00 GMT
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpecificationTitle
{{RFC("7231", "403 Forbidden" , "6.5.3")}}HTTP/1.1: Semantics and Content
+ +

Dukungan peramban

+ + + +

{{Compat("http.status.403")}}

+ +

Lihat juga

+ + diff --git a/files/id/web/http/status/404/index.html b/files/id/web/http/status/404/index.html new file mode 100644 index 0000000000..10c1e4e0a5 --- /dev/null +++ b/files/id/web/http/status/404/index.html @@ -0,0 +1,63 @@ +--- +title: 404 Not Found +slug: Web/HTTP/Status/404 +tags: + - Galat Klien + - HTTP + - Kode status + - Peramban +translation_of: Web/HTTP/Status/404 +--- +
{{HTTPSidebar}}
+ +

Kode respon HTTP 404 Not Found mengindikasikan bahwa server tidak dapat menemukan sumber daya yang diminta. Link yang menuju halaman 404 biasanya disebut dengan broken atau dead links, dan bisa menjadi subjek kepada link rot.

+ +

Status kode 404 tidak mengindikasikan bahwa sumber daya tidak ditemukan sementara atau secara permanen. Apabila sumber daya dihapus secara permanen, {{HTTPStatus("410")}} (Gone) harus digunakan dibandingkan status 404.

+ +

Status

+ +
404 Not Found
+ +

Halaman galat khusus

+ +

Banyak web sites menyesuaikan tampilan dari halaman 404 supaya lebih membantu pengguna dan memberikan petunjuk apa yang harus dilakukan seterusnya. Server Apache dapat dikonfigurasi dengan file .htaccess dengan potongan kode berikut.

+ +
ErrorDocument 404 /notfound.html
+ +

Untuk contoh dari halaman 404 khusus, lihat Halaman 404 MDN.

+ +
+

Desain khusus merupakan hal yang baik. Buat halaman 404 Anda menjadi lucu dan manusiawi, tetapi jangan membuat bingung pengguna.

+
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpecificationTitle
{{RFC("7231", "404 Not Found" , "6.5.4")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Dukungan Peramban

+ + + +

{{Compat("http.status.404")}}

+ +

Lihat Juga

+ + diff --git a/files/id/web/http/status/405/index.html b/files/id/web/http/status/405/index.html new file mode 100644 index 0000000000..651db0f858 --- /dev/null +++ b/files/id/web/http/status/405/index.html @@ -0,0 +1,44 @@ +--- +title: 405 Metode tidak Diizinkan +slug: Web/HTTP/Status/405 +tags: + - Galat Klien + - HTTP + - Referensi + - Status kode + - Status kode HTTP +translation_of: Web/HTTP/Status/405 +--- +
{{HTTPSidebar}}
+ +

Kode respon HTTP 405 Method Not Allowed mengindikasikan bahwa metode permintaan dikenali oleh server tetapi tidak didukung oleh target sumber daya. Server harus menyematkan Allow header field di dalam respon 405 berisi daftar dari metode permintaan yang didukung oleh target sumber daya.

+ +

Status

+ +
405 Method Not Allowed
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpecificationTitle
{{RFC("7231", "405 Method Not Allowed" , "6.5.5")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Lihat juga

+ + diff --git a/files/id/web/http/status/410/index.html b/files/id/web/http/status/410/index.html new file mode 100644 index 0000000000..42ac089598 --- /dev/null +++ b/files/id/web/http/status/410/index.html @@ -0,0 +1,54 @@ +--- +title: 410 Gone +slug: Web/HTTP/Status/410 +tags: + - Galat Klien + - HTTP + - Kode status + - Referensi +translation_of: Web/HTTP/Status/410 +--- +
{{HTTPSidebar}}
+ +

Kode respon HTTP 410 Gone mengindikasikan bahwa akses ke sumber daya tidak lagi tersedia di server asal dengan kondisi akan tidak tersedia secara permanen.

+ +

Apabila Anda tidak tahu apakah kondisi ini hanya sementara atau permanen, kode error {{HTTPStatus(404)}} sebaiknya digunakan.

+ +
+

Catatan: Sebuah respon 410 dapat disimpan di dalam cache secara bawaan.

+
+ +

Status

+ +
410 Gone
+ +

Spesifikasi

+ + + + + + + + + + + + + + +
SpecificationTitle
{{RFC("7231", "410 Gone" , "6.5.9")}}Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
+ +

Dukungan Peramban

+ +

The information shown below has been pulled from MDN's GitHub (https://github.com/mdn/browser-compat-data).

+ + + +

{{Compat("http.status.410")}}

+ +

Lihat Juga

+ + diff --git a/files/id/web/http/status/500/index.html b/files/id/web/http/status/500/index.html new file mode 100644 index 0000000000..ce5c5157fb --- /dev/null +++ b/files/id/web/http/status/500/index.html @@ -0,0 +1,38 @@ +--- +title: 500 Internal Server Error +slug: Web/HTTP/Status/500 +translation_of: Web/HTTP/Status/500 +--- +
{{HTTPSidebar}}
+ +

HTTP kode respons kesalahan server menunjukkan bahwa server mengalami kondisi tak terduga yang menghalanginya memenuhi permintaan.

+ +

Respons kesalahan ini adalah turunan "mencakup-semua" respons. Seringkali respons server pengelola catatan seperti kode status 500 dengan lebih banyak detail tentang permintaan untuk mencegah kesalahan terjadi lagi di masa mendatang.

+ +

Status

+ +
500 Kesalahan Server dari Dalam
+
+ +

Specifications

+ + + + + + + + + + + + +
SpecificationTitle
{{RFC("7231", "" , "6.6.1")}}Protokol Transfer Hiperteks (HTTP / 1.1): Semantik dan Konten
+ +

Kompatibilias browser

+ + + + + +

{{Compat("http.status.500")}}

diff --git a/files/id/web/http/status/index.html b/files/id/web/http/status/index.html new file mode 100644 index 0000000000..066d40771e --- /dev/null +++ b/files/id/web/http/status/index.html @@ -0,0 +1,141 @@ +--- +title: HTTP response status codes +slug: Web/HTTP/Status +translation_of: Web/HTTP/Status +--- +
{{HTTPSidebar}}
+ +

kode status respon HTTP menunjukkan apakah permintaan HTTP tertentu telah berhasil diselesaikan. Tanggapan dikelompokkan dalam lima kelas: tanggapan informasi, tanggapan yang sukses, pengalihan, kesalahan klien, dan server kesalahan.

+ +

Respon informasi

+ +
+
{{HTTPStatus(100, "100 Continue")}}
+
Tanggapan sementara ini menunjukkan bahwa segala sesuatu sejauh ini adalah OK dan bahwa klien harus melanjutkan dengan permintaan atau mengabaikannya jika sudah selesai.
+
{{HTTPStatus(101, "101 Switching Protocol")}}
+
Kode ini dikirim sebagai tanggapan ke header permintaan {{HTTPHeader ("Upgrade")}} oleh klien, dan menunjukkan protokol yang digunakan oleh server.
+
{{HTTPStatus(102, "102 Processing")}} ({{Glossary("WebDAV")}})
+
Kode ini menunjukkan bahwa server telah menerima dan memproses permintaan, tetapi belum ada respons.
+
+ +

Response Sukses

+ +
+
{{HTTPStatus(200, "200 OK")}}
+
Permintaan telah berhasil . Arti keberhasilan bervariasi tergantung pada metode HTTP :
+ GET: The resource has been fetched and is transmitted in the message body.
+ HEAD: The entity headers are in the message body.
+ POST: The resource describing the result of the action is transmitted in the message body.
+ TRACE: The message body contains the request message as received by the server
+
{{HTTPStatus(201, "201 Created")}}
+
The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request.
+
{{HTTPStatus(202, "202 Accepted")}}
+
The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.
+
{{HTTPStatus(203, "203 Non-Authoritative Information")}}
+
This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response.
+
{{HTTPStatus(204, "204 No Content")}}
+
There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones.
+
{{HTTPStatus(205, "205 Reset Content")}}
+
This response code is sent after accomplishing request to tell user agent reset document view which sent this request.
+
{{HTTPStatus(206, "206 Partial Content")}}
+
This response code is used because of range header sent by the client to separate download into multiple streams.
+
+ +

Redirection messages

+ +
+
{{HTTPStatus(300, "300 Multiple Choice")}}
+
The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses.
+
{{HTTPStatus(301, "301 Moved Permanently")}}
+
This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response.
+
{{HTTPStatus(302, "302 Found")}}
+
This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.
+
{{HTTPStatus(303, "303 See Other")}}
+
Server sent this response to directing client to get requested resource to another URI with an GET request.
+
{{HTTPStatus(304, "304 Not Modified")}}
+
This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response.
+
{{HTTPStatus(305, "305 Use Proxy")}}
+
This means requested response must be accessed by a proxy. This response code is not largely supported because security reasons.
+
{{HTTPStatus(306, "306 unused")}}
+
This response code is no longer used, it is just reserved currently. It was used in a previous version of the HTTP 1.1 specification.
+
{{HTTPStatus(307, "307 Temporary Redirect")}}
+
Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
+
{{HTTPStatus(308, "308 Permanent Redirect")}}
+
This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
+
+ +

Client error responses

+ +
+
{{HTTPStatus(400, "400 Bad Request")}}
+
Respons ini berarti server tidak dapat memahami permintaan karena sintaks yang tidak valid.
+
{{HTTPStatus(401, "401 Unauthorized")}}
+
Authentication is needed to get requested response. This is similar to 403, but in this case, authentication is possible.
+
{{HTTPStatus(402, "402 Payment Required")}}
+
This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently.
+
{{HTTPStatus(403, "403 Forbidden")}}
+
Client does not have access rights to the content so server is rejecting to give proper response.
+
{{HTTPStatus(404, "404 Not Found")}}
+
Server can not find requested resource. This response code probably is most famous one due to its frequency to occur in web.
+
{{HTTPStatus(405, "405 Method Not Allowed")}}
+
The request method is known by the server but has been disabled and cannot be used. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code.
+
{{HTTPStatus(406, "406 Not Acceptable")}}
+
This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent.
+
{{HTTPStatus(407, "407 Proxy Authentication Required")}}
+
This is similar to 401 but authentication is needed to be done by a proxy.
+
{{HTTPStatus(408, "408 Request Timeout")}}
+
This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome or IE9, use HTTP preconnection mechanisms to speed up surfing (see {{ bug(634278) }}, which tracks the future implementation of such a mechanism in Firefox). Also note that some servers merely shut down the connection without sending this message.
+
{{HTTPStatus(409, "409 Conflict")}}
+
This response would be sent when a request conflict with current state of server.
+
{{HTTPStatus(410, "410 Gone")}}
+
This response would be sent when requested content has been deleted from server.
+
{{HTTPStatus(411, "411 Length Required")}}
+
Server rejected the request because the Content-Length header field is not defined and the server requires it.
+
{{HTTPStatus(412, "412 Precondition Failed")}}
+
The client has indicated preconditions in its headers which the server does not meet.
+
{{HTTPStatus(413, "413 Payload Too Large")}}
+
Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field.
+
{{HTTPStatus(414, "414 URI Too Long")}}
+
The URI requested by the client is longer than the server is willing to interpret.
+
{{HTTPStatus(415, "415 Unsupported Media Type")}}
+
The media format of the requested data is not supported by the server, so the server is rejecting the request.
+
{{HTTPStatus(416, "416 Requested Range Not Satisfiable")}}
+
The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data.
+
{{HTTPStatus(417, "417 Expectation Failed")}}
+
This response code means the expectation indicated by the Expect request header field can't be met by the server.
+
{{HTTPStatus(421, "421 Misdirected Request")}}
+
The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
+
{{HTTPStatus(426, "426 Upgrade Required")}}
+
The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server MUST send an Upgrade header field in a 426 response to indicate the required protocol(s) (Section 6.7 of [RFC7230]).
+
{{HTTPStatus(428, "428 Precondition Required")}}
+
The origin server requires the request to be conditional. Intended to prevent "the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.
+
{{HTTPStatus(429, "429 Too Many Requests")}}
+
The user has sent too many requests in a given amount of time ("rate limiting").
+
{{HTTPStatus(431, "431 Request Header Fields Too Large")}}
+
The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.
+
{{HTTPStatus(451, "451 Unavailable For Legal Reasons")}}
+
The user requests an illegal resource, such as a web page censored by a government.
+
+ +

Server error responses

+ +
+
{{HTTPStatus(500, "500 Internal Server Error")}}
+
The server has encountered a situation it doesn't know how to handle.
+
{{HTTPStatus(501, "501 Not Implemented")}}
+
The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.
+
{{HTTPStatus(502, "502 Bad Gateway")}}
+
This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
+
{{HTTPStatus(503, "503 Service Unavailable")}}
+
The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.
+
{{HTTPStatus(504, "504 Gateway Timeout")}}
+
This error response is given when the server is acting as a gateway and cannot get a response in time.
+
{{HTTPStatus(505, "505 HTTP Version Not Supported")}}
+
The HTTP version used in the request is not supported by the server.
+
{{HTTPStatus(506, "506 Variant Also Negotiates")}}
+
The server has an internal configuration error: transparent content negotiation for the request results in a circular reference.
+
{{HTTPStatus(507, "507 Variant Also Negotiates")}}
+
The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
+
{{HTTPStatus(511, "511 Network Authentication Required")}}
+
The 511 status code indicates that the client needs to authenticate to gain network access.
+
diff --git a/files/id/web/index.html b/files/id/web/index.html new file mode 100644 index 0000000000..9d74fa1a90 --- /dev/null +++ b/files/id/web/index.html @@ -0,0 +1,153 @@ +--- +title: Teknologi Web untuk Pengembang +slug: Web +tags: + - Landing + - Web +translation_of: Web +--- + + +

Sifat terbuka World Wide Web memberikan kesempatan luar biasa bagi orang-orang yang ingin membuat situs-situs web atau aplikasi daring. Untuk memanfaatkan kemampuan-kemampuan web, Anda perlu belajar cara menggunakannya. Jelajahi link dibawah ini untuk mempelajari lebih lanjut berbagai teknologi web.

+ +
+
+

Teknologi-teknologi Web

+ +

Dasar-dasar

+ +
+
HTML
+
HyperText Markup Language (HTML) adalah bahasa yang digunakan untuk mendeskripsikan dan menentukan konten dari halaman Web.
+
CSS
+
Cascading Style Sheets (CSS) digunakan untuk menentukan tampilan/gambaran konten Web.
+
HTTP
+
HyperText Transfer Protocol (HTTP) digunakan untuk mengantar HTML dan dokumen hypermedia lainnya pada web.
+
+ +

Scripting

+ +
+
JavaScript
+
JavaScript merupakan bahasa pemrograman yang berjalan di browser Anda. Anda dapat menggunakan untuk menambahkan interaktivitas dan fitur dinamis pada situs web atau aplikasi Anda.
+
Dengan adanya {{glossary("Node.js")}}, Anda juga bisa menjalankan JavaScript pada server.
+
Web APIs
+
Web Aplication Programming Interfaces (Web API) digunakan untuk melaksanakan tugas-tugas beragam, seperti memanipulasi DOM, memainkan audio maupun vidio atau membuat grafis 3D. +
    +
  • Referensi Web API antarmuka semua jenis daftar objek yang Anda dapat gunakan selagi mengembangkan untuk web.
  • +
  • Halaman WebAPI semua daftar komunikasi, akses perangkat keras, dan API lainnya yang dapat Anda gunakan di aplikasi web.
  • +
  • Event reference semua daftar events yang dapat Anda gunakan untuk melacak dan bereaksi pada hal-hal yang menarik yang telah terjadi di halaman web atau aplikasi Anda.
  • +
+
+
Komponen-komponen Web
+
Komponen-komponen web adalah serangkaian teknologi-teknologi berbeda yang memungkinkan Anda untuk membuat elemmen-elemen khusus yang dapat digunakan kembali dengan fungsionalitasnya dienkapsulasi (menjaga elemen didalamnya) jauh dari sisa kode Anda dan menggunakannya di aplikasi web Anda.
+
+ +

Grafis

+ +
+
Canvas
+
Elemen {{HTMLElement("canvas")}} menyediakan API untuk membuat grafik 2D menggunakan JavaScript.
+
SVG
+
Scalable Vector Graphics (SVG) memungkinkan Anda mengunakan berbagai garis, kurva, dan bentuk-bentuk geometris lainnya untuk membuat grafik. Dengan vektor, Anda dapat membuat gambar yang diubah ukurannya tetap jernih pada ukuran apapun.
+
WebGL
+
WebGL merupakan API JavaScript yang memungkinkan Anda menggambar grafis 3D atau 2D HTML elemen {{HTMLElement("canvas")}}. Teknologi ini memungkinan Anda melihat OpenGL ES standar di konten Web.
+
+ +

Audio, vidio, dan multimedia

+ +
+
Teknologi-teknologi media Web
+
Sebuah daftar media API terhubung dengan link-link ke dokumentasi yang Anda perlukan masing-masing.
+
Media capture and streams API
+
Referensi untuk API yang memungkinkan untuk streaming, merekam, dan memanipulasi di dua media secara lokal dan seluruh jaringan. Ini termasuk menggunakan kamera lokal dan mikrofon untuk merekam vidio, audio, dan gambar.
+
Menggunakan audio dan vidio HTML
+
Menggabungkan vidio dan/atau audio di sebuah halaman web dan mengendalikan tayangannya.
+
WebRTC
+
RTC di WebRTC singkatan untuk Real-Time Communications, teknologi yang memungkinkan streaming audio/vidio dan berbagi data antara peramban (teman sebaya) klien.
+
+ +

Lainnya

+ +
+
MathML
+
Mathematical Markup Language (MathML) memungkinkan Anda menampilkan persamaan dan sintaks.
+
XSLT
+
Extensible Stylesheet Language Transformations (XSLT) memungkinan Anda mengubah dokumen XML menjadi HTML yang lebih dapat dibaca manusia.
+
EXSLT
+
Fungsi tambahan yang memungkinkan penambahan fitur ke XSLT.
+
XPath
+
XPath memungkinan Anda memilih node DOM di dokumen menggunakan sintaks kuat daripada penyedianya saat ini oleh CSS selectors.
+
+
+ +
+

Ruang Belajar

+ +
+
Belajar Pengembangan Web
+
Kumpulan artikel ini menyediakan pemula dengan segala yang mereka butuhkan untuk memulai coding situs web sederhana.
+
Pemroses aplikasi web
+
Pemroses aplikasi web menggunakan modern API bersama dengan strategi peningkatan pemrosesan tradisi untuk membuat aplikasi web berbagai perangkat. Aplikasi ini bekerja dimana saja dan menyediakan beberapa fitur yang memberikan keuntungan pengalaman sesama pengguna sebagai aplikasi asli. Kumupulan set dokumen ini dan panduannya memberikan semua yang kalian perlukan untuk mengetahui tentang PAW.
+
+ +

Topik-topik lainnya

+ +
+
Aksesbilitas
+
Situs-situs web aksessibel memungkinkan sebanyak-banyaknya orang dapat menggubakan web, termasuk keterbatasan visual, pendengaran, atau kemampuan lainnya. Kumpulan artikel ini menyediakan informasi mengenai pengembangan web aksessibel.
+
Kinerja Web
+
Kinerja Web merupakan seni untuk memastika aplikasi web dimuat cepat dan responsif untuk interaksi pengguna, gak peduli bandwith pengguna, ukuran layar, jaringan, atau kemampuan perangkat.
+
Keamanan
+
Jangan biarkan situs web atau aplikasi Anda kebocoran data ke penjahat. Gunakan kumpulan artikel ini untuk memastikan proyek Anda aman.
+
WebAssembly
+
WebAssembly adalah jenis kode baru yang dapat dijalankan di peramban web — ini merupakan seperti bahasa assembly low-level dengan format compact binary yang berjalan dengan mendekati kinerja asli dan menyediakan bahasa seperti C/C++ dan Rust dengan target kompasi jadi dapat dijalankan di web.
+
+
+
+ +

Lihat Semua...

diff --git a/files/id/web/javascript/a_re-introduction_to_javascript/index.html b/files/id/web/javascript/a_re-introduction_to_javascript/index.html new file mode 100644 index 0000000000..5b7ef3b14e --- /dev/null +++ b/files/id/web/javascript/a_re-introduction_to_javascript/index.html @@ -0,0 +1,862 @@ +--- +title: Sebuah pengenalan ulang pada bahasa JavaScript (tutorial JS) +slug: Web/JavaScript/A_re-introduction_to_JavaScript +translation_of: Web/JavaScript/A_re-introduction_to_JavaScript +--- +
{{jsSidebar}}
+ +

Pengantar

+ +

Mengapa melakukan pengenalan ulang? Karena bahasa {{Glossary("JavaScript")}} terkenal dengan cap buruk sebagai bahasa pemprograman yang paling sering membuat kesalahpahaman di dunia. Sering kali JavaScript diejek sebagai sebuah mainan (layaknya mobil-mobilan) karena terlihat sederhana, tetapi dibalik kesederhanaannya tersebut, terdapat beberapa fitur yang sangat andal. Saat ini JavaScript digunakan oleh aplikasi-aplikasi terkenal dalam jumlah yang luar biasa banyaknya, memiliki pengetahuan yang mendalam tentang teknologi ini adalah salah satu skill penting bagi para pengembang web atau mobile.

+ +

Ada baiknya kita memulai pengenalan ini dengan mengetahui sekilas gambaran sejarah dari bahasa pemograman ini. JavaScript dibuat pada tahun 1995 oleh Brendan Eich ketika dia menjadi seorang insinyur perangkat lunak di Netscape. JavaScript dirilis bersamaan dengan Netscape 2 di permulaan tahun 1996. Awalnya JavaScript dinamakan LiveScript, tetapi diganti menjadi JavaScript karena  memanfaatkan ketenaran bahasa pemograman Java dari Sun Microsystem, walaupun keduanya memiliki sedikit sekali kesamaan. Hal inilah yang menjadi sumber kebingungan sejak saat itu.

+ +

Beberapa bulan kemudian, Microsoft merilis JScript yang tertanam di dalam Internet Explore 3. Sebagian besar JScript kompatible dan mirip dengan JavaScript. Beberapa bulan setelahnya Netscape mengajukan JavaScript ke  Ecma International, Organisasi Eropa yang melakukan standarisasi sistem informasi dan komunikasi, yang kemudian menghasilkan edisi pertama dari standar {{Glossary("ECMAScript")}} pada tahun itu. Standar ini memperoleh pembaharuan yang signifikan pada ECMAScript edisi ke-3 pada tahun 1999, dan sejak saat itu standar tersebut tidak terlalu banyak mengalami perubahan. Edisi ke-4 ECMAScript diabaikan dengan alasan perbedaan pandangan terhadap kompleksitas bahasa. Beberapa bagian dari edisi ECMAScript ke-4  membentuk dasar ECMAScript edisi ke-5, yang dipublikasi pada tahun 2009 and edisi ECMAScript ke-6 dirilis pada bulan Juni tahun 2015.

+ +
+

Karena lebih familiar, mulai dari sini kita akan mengacu ECMAScript sebagai "JavaScript".

+
+ +

Tidak seperti kebanyakan bahasa pemograman, JavaScript tidak mempunyai konsep input atau output (I/O). Didesain untuk dapat dieksekusi sebagai bahasa scripting pada lingkungan pengguna dan mekanisme komunikasi dengan dunia luar diserahkan kepada lingkungan pengguna. Browser adalah lingkungan pengguna yang sangat umum, tetapi Interpreter JavaScript dapat juga ditemukan ditempat lain, termasuk Adobe Acrobat, Adobe Photshop, SVG images, Yahoo Widget engine, lingkungan server seperti Node.js, database NoSQL  seperti Apache CouchDB, komputer tertanam, lingkungan desktop seperti GNOME (salah satu antarmuka yang paling terkenal pada sustem operasi GNU/Linux), dan masih banyak lagi yang lainnya.
+  

+ +

Ikhtisar

+ +

JavaScript adalah bahasa pemograman dinamis berorientasi objek dengan types dan operator, objek bawaan standar (objek literal),  dan methods. Syntax JavaScript dipengaruhi oleh bahasa Java dan C - sangat banyak struktur dalam bahasa tersebut yang digunakan dalam JavaScript. Perbedaan yang paling mendasar adalah JavaScript tidak mempunyai kelas, melainkan fungsionalitas kelas yang dicapai dengan obyek prototipe (Lebih lanjut tentang ES6 {{jsxref("Classes")}}). Perbedaan utama lainnya adalah fungsi sebagai objek, yaitu fungsi mempunyai kapasitas untuk menahan kode yang dapat dieksekusi dan dilewatkan seperti objek yang lain.

+ +

Mari mulai dengan melihat blok pembangun dari bahasa pemograman: types (tipe-tipe data). Program pada JavaScript memanipulasi nilai dan nilai tersebut termasuk ke dalam sebuah tipe. Beberapa tipe dalam JavaScript adalah:
+  

+ + + +

...ooo, ada lagi {{jsxref("undefined")}} and {{jsxref("null")}} keduanya mempunyai karakteristik yang sedikit ganjil, {{jsxref("Array")}} merupakan objek spesial, {{jsxref("Date")}} dan {{jsxref("RegExp")}} merupakan objek yang dapat digunakan langsung dan untuk lebih tepatnya, fungsi termasuk dalam objek spesial. Jadi, diagramnya kira-kira seperti ini:

+ + + +

Ada beberapa tipe {{jsxref("Error")}} bawaan juga, akan lebih memudahkan jika kita mempelajari terlebih dahulu diagram pertama, bagaimanapun juga kita akan membahas tipe - tipe yang telah dituliskan diatas.

+ +

Numbers

+ +

Menurut spesifikasi, tipe nomer pada JavaScript menggunakan "format IEEE 754 64-bit double-presisi". Hal ini menyebabkan beberapa konsekuensi, diantaranya tidak adanya tipe integer pada JavaScript. Jadi programmer harus agak teliti dengan operasi aritmatika jika sebelumnya berangkat dari C atau Java.
+
+ Perlu juga memperhatikan kasus seperti berikut:

+ +
0.1 + 0.2 == 0.30000000000000004
+
+ +

Dalam praktiknya, nilai integer diperlakukan sebagai int 32-bit, dan beberapa implementasi bahkan menyimpannya demikian (dalam int 32-bit) kecuali diinstruksikan agar nilai tersebut valid sebagai tipe Number namun tidak dalam integer 32-bit. Hal ini mungkin saja penting untuk operasi yang mementingkan ukuran bit.

+ +

Standar operasi aritmatika tersedia, seperti penjumlahan, pengurangan, modulus, dan lain-lain. Ada juga Object bawaan yang kami lupa menyebutkannya di awal disebut {{jsxref("Math")}} yang menyediakan fungsi matematika dan konstan:

+ +
Math.sin(3.5);
+var circumference = Math.PI * (r + r);
+
+ +

Anda dapat mengonversi sebuah string ke integer dengan menggunakan fungsi bawaan  {{jsxref("Global_objeks/parseInt", "parseInt()")}}. Basis konversi dapat ditambahkan sebagai argumen kedua (tidak wajib), namun sebaiknya ditambahkan:

+ +
parseInt("123", 10); // 123
+parseInt("010", 10); // 10
+
+ +

Pada peramban kuno, string yang diawali dengan "0" diasumsikan sebagai octal (radix 8), namun hal ini tidak lagi menjadi masalah sejak 2013 dan seterusnya. Kecuali Anda sudah yakin mengenai format string-nya, Anda akan mendapatkan hasil mengejutkan pada peramban kuno tersebut:

+ +
parseInt("010");  //  8
+parseInt("0x10"); // 16
+
+ +

Di sini, kita melihat fungsi {{jsxref("Global_objeks/parseInt", "parseInt()")}} memperlakukan string pertama sebagai oktal karena diawali dengan "0", dan string kedua sebagai hexadecimal karena diawali dengan "0x". Notasi heksadesimal masih ada; hanya oktal yang telah dihapus.

+ +

If you want to convert a binary number to an integer, just change the base:

+ +
parseInt("11", 2); // 3
+
+ +

Similarly, you can parse floating point numbers using the built-in {{jsxref("Global_objeks/parseFloat", "parseFloat()")}} function. Unlike its {{jsxref("Global_objeks/parseInt", "parseInt()")}} cousin, parseFloat() always uses base 10.

+ +

You can also use the unary + operator to convert values to numbers:

+ +
+ "42";   // 42
++ "010";  // 10
++ "0x10"; // 16
+
+ +

A special value called {{jsxref("NaN")}} (short for "Not a Number") is returned if the string is non-numeric:

+ +
parseInt("hello", 10); // NaN
+
+ +

NaN is toxic: if you provide it as an input to any mathematical operation the result will also be NaN:

+ +
NaN + 5; // NaN
+
+ +

You can test for NaN using the built-in {{jsxref("Global_objeks/isNaN", "isNaN()")}} function:

+ +
isNaN(NaN); // true
+
+ +

JavaScript also has the special values {{jsxref("Infinity")}} and -Infinity:

+ +
 1 / 0; //  Infinity
+-1 / 0; // -Infinity
+
+ +

You can test for Infinity, -Infinity and NaN values using the built-in {{jsxref("Global_objeks/isFinite", "isFinite()")}} function:

+ +
isFinite(1/0); // false
+isFinite(-Infinity); // false
+isFinite(NaN); // false
+
+ +
The {{jsxref("Global_objeks/parseInt", "parseInt()")}} and {{jsxref("Global_objeks/parseFloat", "parseFloat()")}} functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. However the "+" operator simply converts the string to NaN if there is an invalid character contained within it. Just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better.
+ +

Strings

+ +

Strings in JavaScript are sequences of Unicode characters. This should be welcome news to anyone who has had to deal with internationalization. More accurately, they are sequences of UTF-16 code units; each code unit is represented by a 16-bit number. Each Unicode character is represented by either 1 or 2 code units.

+ +

If you want to represent a single character, you just use a string consisting of that single character.

+ +

To find the length of a string (in code units), access its length property:

+ +
"hello".length; // 5
+
+ +

There's our first brush with JavaScript objeks! Did we mention that you can use strings like {{jsxref("objek", "objeks", "", 1)}} too? They have {{jsxref("String", "methods", "#Methods", 1)}} as well that allow you to manipulate the string and access information about the string:

+ +
"hello".charAt(0); // "h"
+"hello, world".replace("hello", "goodbye"); // "goodbye, world"
+"hello".toUpperCase(); // "HELLO"
+
+ +

Other types

+ +

JavaScript distinguishes between {{jsxref("null")}}, which is a value that indicates a deliberate non-value (and is only accessible through the null keyword), and {{jsxref("undefined")}}, which is a value of type undefined that indicates an uninitialized value — that is, a value hasn't even been assigned yet. We'll talk about variables later, but in JavaScript it is possible to declare a variable without assigning a value to it. If you do this, the variable's type is undefined. undefined is actually a constant.

+ +

JavaScript has a boolean type, with possible values true and false (both of which are keywords.) Any value can be converted to a boolean according to the following rules:

+ +
    +
  1. false, 0, empty strings (""), NaN, null, and undefined all become false.
  2. +
  3. All other values become true.
  4. +
+ +

You can perform this conversion explicitly using the Boolean() function:

+ +
Boolean("");  // false
+Boolean(234); // true
+
+ +

However, this is rarely necessary, as JavaScript will silently perform this conversion when it expects a boolean, such as in an if statement (see below.) For this reason, we sometimes speak simply of "true values" and "false values," meaning values that become true and false, respectively, when converted to booleans. Alternatively, such values can be called "truthy" and "falsy", respectively.

+ +

Boolean operations such as && (logical and), || (logical or), and ! (logical not) are supported; see below.

+ +

Variables

+ +

New variables in JavaScript are declared using the var keyword:

+ +
var a;
+var name = "simon";
+
+ +

If you declare a variable without assigning any value to it, its type is undefined.

+ +

An important difference between JavaScript and other languages like Java is that in JavaScript, blocks do not have scope; only functions have scope. So if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function. However, starting with ECMAScript Edition 6, let and const declarations allow you to create block-scoped variables.

+ +

Operators

+ +

JavaScript's numeric operators are +, -, *, / and % — which is the remainder operator (which is not the same as modulo.) Values are assigned using =, and there are also compound assignment statements such as += and -=. These extend out to x = x operator y.

+ +
x += 5
+x = x + 5
+
+ +

You can use ++ and -- to increment and decrement respectively. These can be used as prefix or postfix operators.

+ +

The + operator also does string concatenation:

+ +
"hello" + " world"; // "hello world"
+
+ +

If you add a string to a number (or other value) everything is converted in to a string first. This might catch you up:

+ +
"3" + 4 + 5;  // "345"
+ 3 + 4 + "5"; // "75"
+
+ +

Adding an empty string to something is a useful way of converting it to a string itself.

+ +

Comparisons in JavaScript can be made using <, >, <= and >=. These work for both strings and numbers. Equality is a little less straightforward. The double-equals operator performs type coercion if you give it different types, with sometimes interesting results:

+ +
123 == "123"; // true
+1 == true; // true
+
+ +

To avoid type coercion and make sure your comparisons are always accurate, you should always use the triple-equals operator:

+ +
123 === "123"; // false
+1 === true;    // false
+
+ +

There are also != and !== operators.

+ +

JavaScript also has bitwise operations. If you want to use them, they're there.

+ +

Control structures

+ +

JavaScript has a similar set of control structures to other languages in the C family. Conditional statements are supported by if and else; you can chain them together if you like:

+ +
var name = "kittens";
+if (name == "puppies") {
+  name += "!";
+} else if (name == "kittens") {
+  name += "!!";
+} else {
+  name = "!" + name;
+}
+name == "kittens!!"
+
+ +

JavaScript has while loops and do-while loops. The first is good for basic looping; the second for loops where you wish to ensure that the body of the loop is executed at least once:

+ +
while (true) {
+  // an infinite loop!
+}
+
+var input;
+do {
+  input = get_input();
+} while (inputIsNotValid(input))
+
+ +

JavaScript's for loop is the same as that in C and Java: it lets you provide the control information for your loop on a single line.

+ +
for (var i = 0; i < 5; i++) {
+  // Will execute 5 times
+}
+
+ +

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objeks before accessing their attributes:

+ +
var name = o && o.getName();
+
+ +

Or for setting default values:

+ +
var name = otherName || "default";
+
+ +

JavaScript has a ternary operator for conditional expressions:

+ +
var allowed = (age > 18) ? "yes" : "no";
+
+ +

The switch statement can be used for multiple branches based on a number or string:

+ +
switch(action) {
+  case 'draw':
+    drawIt();
+    break;
+  case 'eat':
+    eatIt();
+    break;
+  default:
+    doNothing();
+}
+
+ +

If you don't add a break statement, execution will "fall through" to the next level. This is very rarely what you want — in fact it's worth specifically labeling deliberate fallthrough with a comment if you really meant it to aid debugging:

+ +
switch(a) {
+  case 1: // fallthrough
+  case 2:
+    eatIt();
+    break;
+  default:
+    doNothing();
+}
+
+ +

The default clause is optional. You can have expressions in both the switch part and the cases if you like; comparisons take place between the two using the === operator:

+ +
switch(1 + 3) {
+  case 2 + 2:
+    yay();
+    break;
+  default:
+    neverhappens();
+}
+
+ +

objeks

+ +

JavaScript objeks can be thought of as simple collections of name-value pairs. As such, they are similar to:

+ + + +

The fact that this data structure is so widely used is a testament to its versatility. Since everything (bar core types) in JavaScript is an objek, any JavaScript program naturally involves a great deal of hash table lookups. It's a good thing they're so fast!

+ +

The "name" part is a JavaScript string, while the value can be any JavaScript value — including more objeks. This allows you to build data structures of arbitrary complexity.

+ +

There are two basic ways to create an empty objek:

+ +
var obj = new objek();
+
+ +

And:

+ +
var obj = {};
+
+ +

These are semantically equivalent; the second is called objek literal syntax, and is more convenient. This syntax is also the core of JSON format and should be preferred at all times.

+ +

objek literal syntax can be used to initialize an objek in its entirety:

+ +
var obj = {
+  name: "Carrot",
+  "for": "Max",
+  details: {
+    color: "orange",
+    size: 12
+  }
+}
+
+ +

Attribute access can be chained together:

+ +
obj.details.color; // orange
+obj["details"]["size"]; // 12
+
+ +

The following example creates an objek prototype, Person, and instance of that prototype, You.

+ +
function Person(name, age) {
+  this.name = name;
+  this.age = age;
+}
+
+// Define an objek
+var You = new Person("You", 24);
+// We are creating a new person named "You"
+// (that was the first parameter, and the age..)
+
+ +

Once created, an objek's properties can again be accessed in one of two ways:

+ +
obj.name = "Simon";
+var name = obj.name;
+
+ +

And...

+ +
obj["name"] = "Simon";
+var name = obj["name"];
+
+ +

These are also semantically equivalent. The second method has the advantage that the name of the property is provided as a string, which means it can be calculated at run-time. However, using this method prevents some JavaScript engine and minifier optimizations being applied. It can also be used to set and get properties with names that are reserved words:

+ +
obj.for = "Simon"; // Syntax error, because 'for' is a reserved word
+obj["for"] = "Simon"; // works fine
+
+ +
+

Starting in ECMAScript 5, reserved words may be used as objek property names "in the buff". This means that they don't need to be "clothed" in quotes when defining objek literals. See the ES5 Spec.

+
+ +

For more on objeks and prototypes see: objek.prototype.

+ +

Arrays

+ +

Arrays in JavaScript are actually a special type of objek. They work very much like regular objeks (numerical properties can naturally be accessed only using [] syntax) but they have one magic property called 'length'. This is always one more than the highest index in the array.

+ +

One way of creating arrays is as follows:

+ +
var a = new Array();
+a[0] = "dog";
+a[1] = "cat";
+a[2] = "hen";
+a.length; // 3
+
+ +

A more convenient notation is to use an array literal:

+ +
var a = ["dog", "cat", "hen"];
+a.length; // 3
+
+ +

Note that array.length isn't necessarily the number of items in the array. Consider the following:

+ +
var a = ["dog", "cat", "hen"];
+a[100] = "fox";
+a.length; // 101
+
+ +

Remember — the length of the array is one more than the highest index.

+ +

If you query a non-existent array index, you'll get a value of undefined returned:

+ +
typeof a[90]; // undefined
+
+ +

If you take the above into account, you can iterate over an array using the following:

+ +
for (var i = 0; i < a.length; i++) {
+  // Do something with a[i]
+}
+
+ +

You can iterate over an array using a for...in loop. Note that if someone added new properties to Array.prototype, they will also be iterated over by this loop.  Therefore this method is "not" recommended.

+ +

Another way of iterating over an array that was added with ECMAScript 5 is forEach():

+ +
["dog", "cat", "hen"].forEach(function(currentValue, index, array) {
+  // Do something with currentValue or array[index]
+});
+
+ +

If you want to append an item to an array simply do it like this:

+ +
a.push(item);
+ +

Arrays come with a number of methods. See also the full documentation for array methods.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Method nameDescription
a.toString()Returns a string with the toString() of each element separated by commas.
a.toLocaleString()Returns a string with the toLocaleString() of each element separated by commas.
a.concat(item1[, item2[, ...[, itemN]]])Returns a new array with the items added on to it.
a.join(sep)Converts the array to a string — with values delimited by the sep param
a.pop()Removes and returns the last item.
a.push(item1, ..., itemN)Adds one or more items to the end.
a.reverse()Reverses the array.
a.shift()Removes and returns the first item.
a.slice(start[, end])Returns a sub-array.
a.sort([cmpfn])Takes an optional comparison function.
a.splice(start, delcount[, item1[, ...[, itemN]]])Lets you modify an array by deleting a section and replacing it with more items.
a.unshift(item1[, item2[, ...[, itemN]]])Prepends items to the start of the array.
+ +

Functions

+ +

Along with objeks, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler:

+ +
function add(x, y) {
+  var total = x + y;
+  return total;
+}
+
+ +

This demonstrates a basic function. A JavaScript function can take 0 or more named parameters. The function body can contain as many statements as you like, and can declare its own variables which are local to that function. The return statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns undefined.

+ +

The named parameters turn out to be more like guidelines than anything else. You can call a function without passing the parameters it expects, in which case they will be set to undefined.

+ +
add(); // NaN
+// You can't perform addition on undefined
+
+ +

You can also pass in more arguments than the function is expecting:

+ +
add(2, 3, 4); // 5
+// added the first two; 4 was ignored
+
+ +

That may seem a little silly, but functions have access to an additional variable inside their body called arguments, which is an array-like objek holding all of the values passed to the function. Let's re-write the add function to take as many values as we want:

+ +
function add() {
+  var sum = 0;
+  for (var i = 0, j = arguments.length; i < j; i++) {
+    sum += arguments[i];
+  }
+  return sum;
+}
+
+add(2, 3, 4, 5); // 14
+
+ +

That's really not any more useful than writing 2 + 3 + 4 + 5 though. Let's create an averaging function:

+ +
function avg() {
+  var sum = 0;
+  for (var i = 0, j = arguments.length; i < j; i++) {
+    sum += arguments[i];
+  }
+  return sum / arguments.length;
+}
+
+avg(2, 3, 4, 5); // 3.5
+
+ +

This is pretty useful, but introduces a new problem. The avg() function takes a comma separated list of arguments — but what if you want to find the average of an array? You could just rewrite the function as follows:

+ +
function avgArray(arr) {
+  var sum = 0;
+  for (var i = 0, j = arr.length; i < j; i++) {
+    sum += arr[i];
+  }
+  return sum / arr.length;
+}
+
+avgArray([2, 3, 4, 5]); // 3.5
+
+ +

But it would be nice to be able to reuse the function that we've already created. Luckily, JavaScript lets you call a function and call it with an arbitrary array of arguments, using the {{jsxref("Function.apply", "apply()")}} method of any function objek.

+ +
avg.apply(null, [2, 3, 4, 5]); // 3.5
+
+ +

The second argument to apply() is the array to use as arguments; the first will be discussed later on. This emphasizes the fact that functions are objeks too.

+ +

JavaScript lets you create anonymous functions.

+ +
var avg = function() {
+  var sum = 0;
+  for (var i = 0, j = arguments.length; i < j; i++) {
+    sum += arguments[i];
+  }
+  return sum / arguments.length;
+};
+
+ +

This is semantically equivalent to the function avg() form. It's extremely powerful, as it lets you put a full function definition anywhere that you would normally put an expression. This enables all sorts of clever tricks. Here's a way of "hiding" some local variables — like block scope in C:

+ +
var a = 1;
+var b = 2;
+
+(function() {
+  var b = 3;
+  a += b;
+})();
+
+a; // 4
+b; // 2
+
+ +

JavaScript allows you to call functions recursively. This is particularly useful for dealing with tree structures, such as those found in the browser DOM.

+ +
function countChars(elm) {
+  if (elm.nodeType == 3) { // TEXT_NODE
+    return elm.nodeValue.length;
+  }
+  var count = 0;
+  for (var i = 0, child; child = elm.childNodes[i]; i++) {
+    count += countChars(child);
+  }
+  return count;
+}
+
+ +

This highlights a potential problem with anonymous functions: how do you call them recursively if they don't have a name? JavaScript lets you name function expressions for this. You can use named IIFEs (Immediately Invoked Function Expressions) as shown below:

+ +
var charsInBody = (function counter(elm) {
+  if (elm.nodeType == 3) { // TEXT_NODE
+    return elm.nodeValue.length;
+  }
+  var count = 0;
+  for (var i = 0, child; child = elm.childNodes[i]; i++) {
+    count += counter(child);
+  }
+  return count;
+})(document.body);
+
+ +

The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the engine and results in more readable code. The name also shows up in the debugger and some stack traces, which can save you time when debugging.

+ +

Note that JavaScript functions are themselves objeks — like everything else in JavaScript — and you can add or change properties on them just like we've seen earlier in the objeks section.

+ +

Custom objeks

+ +
For a more detailed discussion of objek-oriented programming in JavaScript, see Introduction to objek Oriented JavaScript.
+ +

In classic objek Oriented Programming, objeks are collections of data and methods that operate on that data. JavaScript is a prototype-based language that contains no class statement, as you'd find in C++ or Java (this is sometimes confusing for programmers accustomed to languages with a class statement.) Instead, JavaScript uses functions as classes. Let's consider a person objek with first and last name fields. There are two ways in which the name might be displayed: as "first last" or as "last, first". Using the functions and objeks that we've discussed previously, we could display the data like this:

+ +
function makePerson(first, last) {
+  return {
+    first: first,
+    last: last
+  };
+}
+function personFullName(person) {
+  return person.first + ' ' + person.last;
+}
+function personFullNameReversed(person) {
+  return person.last + ', ' + person.first;
+}
+
+s = makePerson("Simon", "Willison");
+personFullName(s); // "Simon Willison"
+personFullNameReversed(s); // "Willison, Simon"
+
+ +

This works, but it's pretty ugly. You end up with dozens of functions in your global namespace. What we really need is a way to attach a function to an objek. Since functions are objeks, this is easy:

+ +
function makePerson(first, last) {
+  return {
+    first: first,
+    last: last,
+    fullName: function() {
+      return this.first + ' ' + this.last;
+    },
+    fullNameReversed: function() {
+      return this.last + ', ' + this.first;
+    }
+  };
+}
+
+s = makePerson("Simon", "Willison")
+s.fullName(); // "Simon Willison"
+s.fullNameReversed(); // "Willison, Simon"
+
+ +

There's something here we haven't seen before: the this keyword. Used inside a function, this refers to the current objek. What that actually means is specified by the way in which you called that function. If you called it using dot notation or bracket notation on an objek, that objek becomes this. If dot notation wasn't used for the call, this refers to the global objek.

+ +

Note that this is a frequent cause of mistakes. For example:

+ +
s = makePerson("Simon", "Willison");
+var fullName = s.fullName;
+fullName(); // undefined undefined
+
+ +

When we call fullName() alone, without using s.fullName(), this is bound to the global objek. Since there are no global variables called first or last we get undefined for each one.

+ +

We can take advantage of the this keyword to improve our makePerson function:

+ +
function Person(first, last) {
+  this.first = first;
+  this.last = last;
+  this.fullName = function() {
+    return this.first + ' ' + this.last;
+  };
+  this.fullNameReversed = function() {
+    return this.last + ', ' + this.first;
+  };
+}
+var s = new Person("Simon", "Willison");
+
+ +

We have introduced another keyword: new. new is strongly related to this. It creates a brand new empty objek, and then calls the function specified, with this set to that new objek. Notice though that the function specified with this does not return a value but merely modifies the this objek. It's new that returns the this objek to the calling site. Functions that are designed to be called by new are called constructor functions. Common practice is to capitalize these functions as a reminder to call them with new.

+ +

The improved function still has the same pitfall with calling fullName() alone.

+ +

Our person objeks are getting better, but there are still some ugly edges to them. Every time we create a person objek we are creating two brand new function objeks within it — wouldn't it be better if this code was shared?

+ +
function personFullName() {
+  return this.first + ' ' + this.last;
+}
+function personFullNameReversed() {
+  return this.last + ', ' + this.first;
+}
+function Person(first, last) {
+  this.first = first;
+  this.last = last;
+  this.fullName = personFullName;
+  this.fullNameReversed = personFullNameReversed;
+}
+
+ +

That's better: we are creating the method functions only once, and assigning references to them inside the constructor. Can we do any better than that? The answer is yes:

+ +
function Person(first, last) {
+  this.first = first;
+  this.last = last;
+}
+Person.prototype.fullName = function() {
+  return this.first + ' ' + this.last;
+};
+Person.prototype.fullNameReversed = function() {
+  return this.last + ', ' + this.first;
+};
+
+ +

Person.prototype is an objek shared by all instances of Person. It forms part of a lookup chain (that has a special name, "prototype chain"): any time you attempt to access a property of Person that isn't set, JavaScript will check Person.prototype to see if that property exists there instead. As a result, anything assigned to Person.prototype becomes available to all instances of that constructor via the this objek.

+ +

This is an incredibly powerful tool. JavaScript lets you modify something's prototype at any time in your program, which means you can add extra methods to existing objeks at runtime:

+ +
s = new Person("Simon", "Willison");
+s.firstNameCaps(); // TypeError on line 1: s.firstNameCaps is not a function
+
+Person.prototype.firstNameCaps = function firstNameCaps() {
+  return this.first.toUpperCase()
+};
+s.firstNameCaps(); // "SIMON"
+
+ +

Interestingly, you can also add things to the prototype of built-in JavaScript objeks. Let's add a method to String that returns that string in reverse:

+ +
var s = "Simon";
+s.reversed(); // TypeError on line 1: s.reversed is not a function
+
+String.prototype.reversed = function reversed() {
+  var r = "";
+  for (var i = this.length - 1; i >= 0; i--) {
+    r += this[i];
+  }
+  return r;
+};
+
+s.reversed(); // nomiS
+
+ +

Our new method even works on string literals!

+ +
"This can now be reversed".reversed(); // desrever eb won nac sihT
+
+ +

As mentioned before, the prototype forms part of a chain. The root of that chain is objek.prototype, whose methods include toString() — it is this method that is called when you try to represent an objek as a string. This is useful for debugging our Person objeks:

+ +
var s = new Person("Simon", "Willison");
+s; // [objek objek]
+
+Person.prototype.toString = function() {
+  return '<Person: ' + this.fullName() + '>';
+}
+
+s.toString(); // "<Person: Simon Willison>"
+
+ +

Remember how avg.apply() had a null first argument? We can revisit that now. The first argument to apply() is the objek that should be treated as 'this'. For example, here's a trivial implementation of new:

+ +
function trivialNew(constructor, ...args) {
+  var o = {}; // Create an objek
+  constructor.apply(o, args);
+  return o;
+}
+
+ +

This isn't an exact replica of new as it doesn't set up the prototype chain (it would be difficult to illustrate). This is not something you use very often, but it's useful to know about. In this snippet, ...args (including the ellipsis) is called the "rest arguments" — as the name implies, this contains the rest of the arguments.

+ +

Calling

+ +
var bill = trivialNew(Person, "William", "Orange");
+ +

is therefore almost equivalent to

+ +
var bill = new Person("William", "Orange");
+ +

apply() has a sister function named call, which again lets you set this but takes an expanded argument list as opposed to an array.

+ +
function lastNameCaps() {
+  return this.last.toUpperCase();
+}
+var s = new Person("Simon", "Willison");
+lastNameCaps.call(s);
+// Is the same as:
+s.lastNameCaps = lastNameCaps;
+s.lastNameCaps();
+
+ +

Inner functions

+ +

JavaScript function declarations are allowed inside other functions. We've seen this once before, with an earlier makePerson() function. An important detail of nested functions in JavaScript is that they can access variables in their parent function's scope:

+ +
function betterExampleNeeded() {
+  var a = 1;
+  function oneMoreThanA() {
+    return a + 1;
+  }
+  return oneMoreThanA();
+}
+
+ +

This provides a great deal of utility in writing more maintainable code. If a function relies on one or two other functions that are not useful to any other part of your code, you can nest those utility functions inside the function that will be called from elsewhere. This keeps the number of functions that are in the global scope down, which is always a good thing.

+ +

This is also a great counter to the lure of global variables. When writing complex code it is often tempting to use global variables to share values between multiple functions — which leads to code that is hard to maintain. Nested functions can share variables in their parent, so you can use that mechanism to couple functions together when it makes sense without polluting your global namespace — "local globals" if you like. This technique should be used with caution, but it's a useful ability to have.

+ +

Closures

+ +

This leads us to one of the most powerful abstractions that JavaScript has to offer — but also the most potentially confusing. What does this do?

+ +
function makeAdder(a) {
+  return function(b) {
+    return a + b;
+  };
+}
+var x = makeAdder(5);
+var y = makeAdder(20);
+x(6); // ?
+y(7); // ?
+
+ +

The name of the makeAdder() function should give it away: it creates a new 'adder' functions, which when called with one argument adds it to the argument that they were created with.

+ +

What's happening here is pretty much the same as was happening with the inner functions earlier on: a function defined inside another function has access to the outer function's variables. The only difference here is that the outer function has returned, and hence common sense would seem to dictate that its local variables no longer exist. But they do still exist — otherwise the adder functions would be unable to work. What's more, there are two different "copies" of makeAdder()'s local variables — one in which a is 5 and one in which a is 20. So the result of those function calls is as follows:

+ +
x(6); // returns 11
+y(7); // returns 27
+
+ +

Here's what's actually happening. Whenever JavaScript executes a function, a 'scope' objek is created to hold the local variables created within that function. It is initialized with any variables passed in as function parameters. This is similar to the global objek that all global variables and functions live in, but with a couple of important differences: firstly, a brand new scope objek is created every time a function starts executing, and secondly, unlike the global objek (which is accessible as this and in browsers as window) these scope objeks cannot be directly accessed from your JavaScript code. There is no mechanism for iterating over the properties of the current scope objek, for example.

+ +

So when makeAdder() is called, a scope objek is created with one property: a, which is the argument passed to the makeAdder() function. makeAdder() then returns a newly created function. Normally JavaScript's garbage collector would clean up the scope objek created for makeAdder() at this point, but the returned function maintains a reference back to that scope objek. As a result, the scope objek will not be garbage collected until there are no more references to the function objek that makeAdder() returned.

+ +

Scope objeks form a chain called the scope chain, similar to the prototype chain used by JavaScript's objek system.

+ +

A closure is the combination of a function and the scope objek in which it was created. Closures let you save state — as such, they can often be used in place of objeks. You can find several excellent introductions to closures.

diff --git a/files/id/web/javascript/data_structures/index.html b/files/id/web/javascript/data_structures/index.html new file mode 100644 index 0000000000..3521bbc640 --- /dev/null +++ b/files/id/web/javascript/data_structures/index.html @@ -0,0 +1,267 @@ +--- +title: JavaScript data types and data structures +slug: Web/JavaScript/Data_structures +tags: + - JavaScript + - Tipe +translation_of: Web/JavaScript/Data_structures +--- +

   {{jsSidebar("More")}}

+ +

Semua bahasa pemrograman memiliki struktur data bawaan, namun hal tersebut sering dijumpai berbeda antara satu bahasa dengan bahasa lainya. Artikel ini mencoba untuk membuat daftar struktur data bawaan yang tersedia di JavaScript dan sifat-sifat apa saja yang dimiliki. Struktur data bawaan dapat digunakan untuk membangun struktur data lainnya. Bila memungkinkan, perbandingan dengan bahasa lainya akan diambil.

+ +

Dynamic typing

+ +

JavaScript adalah salah satu bahasa pemrograman yang tidak mengutamakan tipe data. Tidak perlu mendeklarasikan jenis data dari suatu variabel setiap saat. Tipe data akan dideklarasikan secara otomatis diawal program dijalankan. Dengan kata lain memungkinkan untuk menggunakan nama peubah yang sama dengan jenis data yang berbeda:

+ +
var foo = 42;    // foo saat ini adalah angka
+foo     = 'bar'; // foo saat ini adalah string
+foo     = true;  // foo saat ini adalah boolean
+
+ +

Tipe Data

+ +

Standar ECMAScript terakhir menjelaskan tujuh tipe data:

+ + + +

Nilai Primitif

+ +

Semua tipe kecuali objek menentukan nilai tetap (nilai, yang tidak dapat diubah). Misalnya dan tidak seperti C, Strings tidak dapat diubah. Di JavaScript, string termasuk sebagai nilai primitif.

+ +

Undefined

+ +

Variabel yang nilainya tidak ditetapkan (tidak diisi) memiliki nilai undefined. Lihat {{jsxref("undefined")}} dan {{Glossary("Undefined")}} untuk lebih lanjut.

+ +

Null

+ +

Null hanya memiliki sebuah nilai dan terdiri nilai itu sendiri: null. Lihat {{jsxref("null")}} dan {{Glossary("Null")}} untuk lebih lanjut.

+ +

Boolean

+ +

Merepresentasikan entitas logika dan hanya memiliki dua nilai atau kemungkinan, yaitu: true dan false.

+ +

Number

+ +

Berdasarkan standar ECMAScript, dikatakan bahwa hanya ada satu tipe nomor, yaitu double-precision 64-bit binary format IEEE 754 value (nomor diantara -(253 -1) dan (253 -1) ). Tidak ada penomoran bilangan bulat yang spesifik. Sebagai tambahan untuk menampilkan bilangan floating-point (bilangan pecahan float), tipe nomor memiliki tiga simbol, yaitu: +Infinity, -Infinity, dan NaN (Not-a-Number)

+ +

Untuk memeriksa nomor paling besar atau paling kecil diantara +/-Infinity diatas, dapat menggunakan konstanta {{jsxref("Number.MAX_VALUE")}} atau {{jsxref("Number.MIN_VALUE")}}. Semenjak standar ECMAScript 2015, untuk memeriksa nilai double-precision floating-point dapat menggunakan {{jsxref("Number.isSafeInteger()")}} yang setara dengan {{jsxref("Number.MAX_SAFE_INTEGER")}} dan {{jsxref("Number.MIN_SAFE_INTEGER")}}. Lebih dari batas tersebut, bilangan bulat di JavaScript tidak aman dan akan digantikan dengan perkiraan double-precision floating-point.

+ +

Angka 0 merupakan bilangan bulat integer yang memiliki dua representasi, yaitu +0 dan -0 dan pada kenyataannya tidak berpengaruh dalam perhitungan karena jika keduanya dibandingkan akan bernilai benar: +0 === -0 //-->(true) dan akan diberitahu jika pembagi merupakan nol:

+ +
> 42 / +0
+Infinity
+> 42 / -0
+-Infinity
+
+ +

Meskipun angka sering hanya mewakili nilainya, JavaScript menyediakan beberapa operator biner (bitwise) yang dapat digunakan untuk bit masking, yaitu mewakili beberapa nilai Boolean dalam sebuah nomor. Namun, ini biasanya dianggap sebagai praktik yang buruk, karena JavaScript menawarkan cara lain untuk mewakili satu set Boolean (seperti array Boolean atau objek dengan nilai Boolean yang ditetapkan untuk properti bernama). Bit masking juga cenderung membuat kode lebih sulit dibaca, dipahami, dan dirawat. Mungkin diperlukan untuk digunakan di lingkungan yang sangat terbatas, seperti saat mencoba mengatasi kompresi atau dalam kasus ekstrim ketika setiap bit di atas jumlah jaringan. Teknik ini hanya harus dipertimbangkan ketika tidak ada cara terakhir yang dapat diambil untuk mengoptimalkan ukuran.

+ +

String

+ +

Tipe {{jsxref("Global_Objects/String", "String")}} digunakan untuk menampilkan data tulisan (teks). Terdiri dari beberapa bagian karakter yang dibentuk dari bilangan 16-bit unsigned integer. Setiap karakter pada String menempati posisi pada String. Karakter pertama pada string berindeks 0, kemudian 1, lalu 2, ..., hingga karakter terakhir dari String. Panjang String merupakan jumlah karakter pembentuknya.

+ +

Berbeda dengan bahasa pemrogramman C, JavaScript string tidak dapat diubah. Dengan kata lain sekali String dibuat, maka tidak mungkin untuk mengubahnya. Namun memungkinkan untuk membuat String baru berdasarkan operasi string sebelumnya. Contoh:

+ + + +

Hati-hati pada "stringly-typing" kode!

+ +

String dapat digunakan untuk menampilkan data kompleks (rumit). Keuntungan untuk jangka pendek:

+ + + +

Dengan adanya konversi, string dapat menampung semua tipe data, dan hentu bukan hal yang baik. Sebagai contoh, dengan separator (pemisah), string dapat meniru list (pada JavaScript disebut sebagai array). Sayangnya saat pemisah digunakan di salahsatu bagian "list" maka strukturnya akan rusak. Escape character menjadi salahsatu cara untuk menangani hal tersebut. Hal tersebut membutuhkan konversi mahal dan hanya menambah beban pemeliharaan.

+ +

Gunakan string untuk data teks. Parse string dan gunakan abstraksi yang tepat jika untuk menampilkan data yang rumit.

+ +

Symbol

+ +

Baru diperkenalkan sejak JavaScript ECMAScript 2015. Simbol memiliki ciri khas (unik) dan nilai primitif tetap (immutable) serta dapat digunakan sebagai kunci dari properti sebuah Objek. Pada beberapa bahasa pemrogramman, Simbol disebut sebagai atom. Untuk lebih jelasnya, lihat pustaka {{Glossary("Symbol")}} dan pembungkus {{jsxref("Symbol")}} objek di JavaScript.

+ +

Objek

+ +

Pada ilmu komputer, objek adalah nilai pada memori yang dimungkinkan dialamatkan oleh {{Glossary("Identifier", "identifier")}}.

+ +

Properties

+ +

Pada JavaScript, objek dapat digambarkan sebagai kumpulan properti. Dengan adanya sintaks objek literal, set properti dibatasi; kemudian properti dapat ditambahkan atau dihapus. Nilai dari properti dapat berupa "nilai" atau tipe data lain, termasuk objek itu sendiri, yang memungkinkan untuk membangun struktur data yang rumit. Properti diidentifikasi menggunakan nilai kunci. Kunci dapat berupa String ataupun Simbol.

+ +

Terdapat dua tipe objek properti yang memiliki attribut: data property dan accessor property.

+ +

Data Property

+ +

mengkaitkan kunci dengan nilai dan memiliki beberapa atribut:

+ +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributTipeKeteranganNilai bawaan
[[Value]]Semua jenis JavaScriptNilai yang diterima dengan mengambil akses properti.undefined
[[Writable]]BooleanJika false, maka propeti [[Value]] tidak dapat diubah.false
[[Enumerable]]BooleanJika true, properti dapat terbaca saat for...in loops. Lihat juga Enumerability and ownership of propertiesfalse
[[Configurable]]BooleanJika false, properti tidak dapat dihapus, tidak dapat diubah menjadi aksesor propeti, juga atribut selain [[Value]] dan [[Writable]] tidak dapat diubah.false
+ +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Atribut usang (as of ECMAScript 3, renamed in ECMAScript 5)
AtributTipeKeterangan
Read-onlyBooleanDiubah di ES5 menjadi atribut [[Writable]].
DontEnumBooleanDiubah di ES5 menjadi atribut [[Enumerable]].
DontDeleteBooleanDiubah di ES5 menjadi atribut [[Configurable]].
+ +

 

+ +
+

Note: Biasanya atribut digunakan oleh JavaScript engine, sehingga tidak dapat diakses secara langsung (lihat Object.defineProperty()). Itulah mengapa atribut ditulis dengan kurung siku ganda.

+
+ +

 

+ +

"Normal" objects, and functions

+ +

A JavaScript object is a mapping between keys and values. Keys are strings (or {{jsxref("Symbol")}}s) and values can be anything. This makes objects a natural fit for hashmaps.

+ +

Functions are regular objects with the additional capability of being callable.

+ +

Dates

+ +

When representing dates, the best choice is to use the built-in Date utility in JavaScript.

+ +

Indexed collections: Arrays and typed Arrays

+ +

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push(adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.

+ +

Typed Arrays are new to JavaScript with ECMAScript 2015 and present an array-like view of an underlying binary data buffer. The following table helps you to find the equivalent C data types:

+ +

{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects", "", 0, 3)}}

+ +

Keyed collections: Maps, Sets, WeakMaps, WeakSets

+ +

These data structures take object references as keys and are introduced in ECMAScript Edition 6. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

+ +

One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of "less than" for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.

+ +

Usually, to bind data to a DOM node, one could set properties directly on the object or use data-* attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.

+ +

Structured data: JSONBagian

+ +

JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See {{Glossary("JSON")}} and {{jsxref("JSON")}} for more details.

+ +

More objects in the standard libraryBagian

+ +

JavaScript has a standard library of built-in objects. Please have a look at the referenceto find out about more objects.

+ +

Determining types using the typeofoperator

+ +

The typeof operator can help you to find the type of your variable. Please read the reference page for more details and edge cases.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-8', 'Types')}}{{Spec2('ES5.1')}} 
{{SpecName('ES2015', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ESDraft')}} 
+ +

See also

+ + + +

 

+ +

 

diff --git a/files/id/web/javascript/index.html b/files/id/web/javascript/index.html new file mode 100644 index 0000000000..bfc6233ce4 --- /dev/null +++ b/files/id/web/javascript/index.html @@ -0,0 +1,116 @@ +--- +title: JavaScript +slug: Web/JavaScript +tags: + - JavaScript + - belajar +translation_of: Web/JavaScript +--- +
{{JsSidebar}}
+ +

JavaScript (JS) sangat ringan, terinterpretasi, bahasa pemrogramman dengan first-class functions. Umum dikenal sebagai bahasa scripting untuk halaman web, Banyak lingkungan non-browser juga menggunakan javascript, seperti node.js dan Apache CouchDB. JS merupakan prototype-based, multi-paradigm, bahasa scripting dinamis, medukung object-oriented, diperlukan, dan declarative (mis. functional programming) styles. Baca lebih lanjut about JavaScript.

+ +

Bagian situs ini didedikasikan untuk bahasa javascript dan bukan bagian yang spesifik dengan halaman web atau lingkungan host lain. Untuk informasi tentang {{Glossary("API","APIs")}} yang spesifik untuk halaman web, Lihat Web APIs dan DOM.

+ +

Standar untuk JavaScript adalah ECMAScript. Seperti pada 2012, semua modern browsers mendukung ECMAScript 5.1. Browser lama mendukung setidaknya  ECMAScript 3. Juni 17, 2015, ECMA International mempublikasikan versi major keenam dari ECMAScript, yang secara ofisial disebut ECMAScript 2015, dan umumnya dikaitkan sebagai ECMAScript 6 atau ES6. Sejak ketika standar ECMAScript pada siklus rilis tahunan. Dokumentasi ini mengacu pada draft versi terbaru, saat ini ECMAScript 2018.

+ +

Jangan keliru antara JavaScript dengan Bahasa pemrograman java. Keduanya "Java" dan "JavaScript" adalah merek dagang dan merek ini terdaftar oleh Oracle di U.S. dan negara lainnya. Namun, kedua bahasa pemrograman tersebut memiliki sintaks, struktur, dan penggunaan yang berbeda.

+ +
+
+

Tutorial

+ +

Belajar cara menulis program di javascript dengan paduan dan tutorial.

+ +

Untuk Pemula

+ +

Pergilah ke topik Area Pembelajaran JavaScript kami jika Anda ingin belajar JavaScript dan belum memiliki pengalaman dari pemrograman JavaScript. Tersedia modul lengkap sebagai berikut:

+ +

Langkah pertama JavaScript
+      Jawaban beberapa pertanyaan mendasar seperti "apa itu JavaScript?", "Seperti apa tampilannya?", Dan "apa yang bisa dilakukan?", Bersama mendiskusikan fitur utama JavaScript seperti variabel, string, angka dan array.

+ +

Bangunan Blok JavaScript
+     Lanjutan jangkauan dari fitur dasar kunci JavaScript, arahkan perhatian pada jenis blok kode yang biasa ditemukan seperti statement kondisional, loop, fungsi, dan events.

+ +

Perkenalan Objek JavaScript
+      Sifat JavaScript yang berorientasi objek penting untuk dipahami jika Anda ingin melangkah lebih jauh dengan pengetahuan Anda tentang bahasanya dan menulis kode yang lebih efisien, oleh karena itu kami menyediakan modul ini untuk membantu Anda.

+ +

Pengantar

+ +
+
Paduan JavaScript
+
Jika anda baru mengenal javascript, paduan ini akan menuntun anda belajar.
+
Ikhtisar Teknologi JavaScript
+
Pengantar javascript pada lingkungan web browser.
+
Pengantar JavaScript Berbasis Objek
+
Pengantar pada konsep dari bahasa berorientasi object di JavaScript.
+
+ +

Menengah

+ +
+
Mengenal kembali JavaScript
+
Gambaran bagi mereka yang berfikir mengetahui tentang JavaScript.
+
+ +
+
Struktur data JavaScript
+
Gambaran struktur data yang tersedia di JavaScript.
+
Perbandingan kesetaraan dan kesamaan
+
JavaScript  menyediakan tiga operasi perbandingan yang berbeda: perbandingan stric ===, perbandingan loggar menggunakan ==, dan method {{jsxref("Global_Objects/Object/is", "Object.is()")}}.
+
+ +

Lanjut

+ +
+
Pewarisan dan rantai purwarupa
+
Menjelaskan tentang kesalah-pahaman dan meremehkan yang terjadi pada  pewarisan berbasis purwarupa.
+
Mode Strict
+
Mode strict mendefinisikan bahwa anda tidak dapat menggunakan variabel sebelum menginisialisasinya. Ini bentuk batasan dari varian ECMAScript 5, berguna untuk performa yang lebih cepat dan debuging yang lebih mudah.
+
JavaScript typed arrays
+
JavaScript typed arrays menyediakan mekanisme untuk mengakses data binari mentah(raw).
+
Pengelolaan Memory
+
Siklus memori dan garbage collection di JavaScript.
+
Model konkurensi dan Event Loop
+
JavaScript memiliki model konkurensi berbasis pada "event loop".
+
+
+ +
+

Referensi

+ +

Jelajahi dokumentasi Referensi javaScript.

+ +
+
Standard objects
+
Mencari tahu tentang standarbuilt-in objects {{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}},{{jsxref("RegExp")}} , {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}} , {{jsxref("WeakSet")}}, dan lainnya.
+
Ekspresi dan operator
+
Belajar tentang cara kerja operator {{jsxref("Operators/instanceof", "instanceof")}},  {{jsxref("Operators/typeof", "typeof")}}, {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}},  operator precedence, dan banyak lagi.
+
Statemen dan pendeklarasian
+
Belajar cara menggunakan {{jsxref("Statements/do...while", "do-while")}}, {{jsxref("Statements/for...in", "for-in")}}, {{jsxref("Statements/for...of", "for-of")}}, {{jsxref("Statements/try...catch", "try-catch")}}, {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/var", "var")}}, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/if...else", "if-else")}}, {{jsxref("Statements/switch", "switch")}}, dan statement Javascript lain dan juga kerja keywords.
+
 Fungsi
+
Belajar bagaimana menggunakan fugsi untuk digunakan di aplikasi anda.
+
+ +

Alat & sumber

+ +

Alat yang dapat membantu anda menulis dan mendebug kode JavaScript.

+ +
+
Firefox Developer Tools
+
Scratchpad, Web Console, JavaScript Profiler, Debugger, dan lainnya.
+
Firebug
+
Edit, debug, dan melihat CSS, HTML, juga JavaScript langsung di setiap halaman web.
+
JavaScript Shells
+
JavaScript shell memungkinkan anda untuk mencoba kode snippet JavaScript.
+
TogetherJS
+
Mempermudah kolaborasi.
+
Stack Overflow
+
Bertanya di Stack Overflow dengan tag "JavaScript".
+
Versi JavaScript dan catatan release
+
Jelajahi sejarah fitur JavaScript dan status implementasi.
+
JSFiddle
+
Edit JavaScript, CSS, HTML dan lihat secara langsung. Gunakan sumber dari luar dan berkolaborasi dengan tim anda secara online.
+
+
+
diff --git a/files/id/web/javascript/inheritance_dan_prototype_chain/index.html b/files/id/web/javascript/inheritance_dan_prototype_chain/index.html new file mode 100644 index 0000000000..49a0100ed8 --- /dev/null +++ b/files/id/web/javascript/inheritance_dan_prototype_chain/index.html @@ -0,0 +1,304 @@ +--- +title: Inheritance dan prototype chain +slug: Web/JavaScript/Inheritance_dan_prototype_chain +translation_of: Web/JavaScript/Inheritance_and_the_prototype_chain +--- +
{{jsSidebar("Advanced")}}
+ +

JavaScript sedikit membingungkan bagi pengembang yang berpengalaman di pemrograman berbasis class (seperti java dan C++), sebagai bahasa dinamis dan tidak mendukung implementasi class lihat( keyword class dikenalkan pada ES2015, namun terkesan berlebihan, JavaScript merupakan bahasa berbasis prototype).

+ +

Ketika menggunakan inheritance, JavaScript hanya memiliki satu construct: objek. Setiap objek memiliki sebuah private property ( berkenaan tentang [[Prototype]] ) yang memegang jalinan ke objek lain yang memanggil prototype tersebut. Prototype objek tersebut memiliki prototype sendiri, dan seterusnya hingga objek mencapai prototipe null. Dengan definisi, null tidak lagi memiliki prototype, dan berperan sebagai hubungan terakhir dari prototype chain.

+ +

Hampir seluruh objek pada JavaScript merupakan instance dari {{jsxref("Object")}} dimana berada di atas prototype chain.

+ +

Meskipun hal ini sering dianggap sebagai salah satu kelemahan JavaScript, model Inheritance prototype sebenarnya lebih hebat daripada model klasiknya. Hal ini, misalnya, cukup sepele untuk membangun model klasik di atas model prototipal.

+ +

Inheritance dengan prototype chain

+ +

Meng-Inheriting properti

+ +

JavaScript objects are dynamic "bags" of properties (referred to as own properties). JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.

+ +
+

Following the ECMAScript standard, the notation someObject.[[Prototype]] is used to designate the prototype of someObject. Since ECMAScript 2015, the [[Prototype]] is accessed using the accessors {{jsxref("Object.getPrototypeOf()")}} and {{jsxref("Object.setPrototypeOf()")}}. This is equivalent to the JavaScript property __proto__ which is non-standard but de-facto implemented by many browsers.

+ +

It should not be confused with the func.prototype property of functions, which instead specifies the [[Prototype]] to be assigned to all instances of objects created by the given function when used as a constructor. The Object.prototype property represents the {{jsxref("Object")}} prototype object.

+
+ +

Here is what happens when trying to access a property:

+ +
// Let's assume we have object o, with its own properties a and b:
+// {a: 1, b: 2}
+// o.[[Prototype]] has properties b and c:
+// {b: 3, c: 4}
+// Finally, o.[[Prototype]].[[Prototype]] is null.
+// This is the end of the prototype chain, as null,
+// by definition, has no [[Prototype]].
+// Thus, the full prototype chain looks like:
+// {a: 1, b: 2} ---> {b: 3, c: 4} ---> null
+
+console.log(o.a); // 1
+// Is there an 'a' own property on o? Yes, and its value is 1.
+
+console.log(o.b); // 2
+// Is there a 'b' own property on o? Yes, and its value is 2.
+// The prototype also has a 'b' property, but it's not visited.
+// This is called "property shadowing."
+
+console.log(o.c); // 4
+// Is there a 'c' own property on o? No, check its prototype.
+// Is there a 'c' own property on o.[[Prototype]]? Yes, its value is 4.
+
+console.log(o.d); // undefined
+// Is there a 'd' own property on o? No, check its prototype.
+// Is there a 'd' own property on o.[[Prototype]]? No, check its prototype.
+// o.[[Prototype]].[[Prototype]] is null, stop searching,
+// no property found, return undefined.
+
+ +

Setting a property to an object creates an own property. The only exception to the getting and setting behavior rules is when there is an inherited property with a getter or a setter.

+ +

Inheriting "methods"

+ +

JavaScript does not have "methods" in the form that class-based languages define them. In JavaScript, any function can be added to an object in the form of a property. An inherited function acts just as any other property, including property shadowing as shown above (in this case, a form of method overriding).

+ +

When an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property.

+ +
var o = {
+  a: 2,
+  m: function() {
+    return this.a + 1;
+  }
+};
+
+console.log(o.m()); // 3
+// When calling o.m in this case, 'this' refers to o
+
+var p = Object.create(o);
+// p is an object that inherits from o
+
+p.a = 4; // creates an own property 'a' on p
+console.log(p.m()); // 5
+// when p.m is called, 'this' refers to p.
+// So when p inherits the function m of o,
+// 'this.a' means p.a, the own property 'a' of p
+
+ +

Different ways to create objects and the resulting prototype chain

+ +

Objects created with syntax constructs

+ +
var o = {a: 1};
+
+// The newly created object o has Object.prototype as its [[Prototype]]
+// o has no own property named 'hasOwnProperty'
+// hasOwnProperty is an own property of Object.prototype.
+// So o inherits hasOwnProperty from Object.prototype
+// Object.prototype has null as its prototype.
+// o ---> Object.prototype ---> null
+
+var b = ['yo', 'whadup', '?'];
+
+// Arrays inherit from Array.prototype
+// (which has methods indexOf, forEach, etc.)
+// The prototype chain looks like:
+// b ---> Array.prototype ---> Object.prototype ---> null
+
+function f() {
+  return 2;
+}
+
+// Functions inherit from Function.prototype
+// (which has methods call, bind, etc.)
+// f ---> Function.prototype ---> Object.prototype ---> null
+
+ +

With a constructor

+ +

A "constructor" in JavaScript is "just" a function that happens to be called with the new operator.

+ +
function Graph() {
+  this.vertices = [];
+  this.edges = [];
+}
+
+Graph.prototype = {
+  addVertex: function(v) {
+    this.vertices.push(v);
+  }
+};
+
+var g = new Graph();
+// g is an object with own properties 'vertices' and 'edges'.
+// g.[[Prototype]] is the value of Graph.prototype when new Graph() is executed.
+
+ +

With Object.create

+ +

ECMAScript 5 introduced a new method: {{jsxref("Object.create()")}}. Calling this method creates a new object. The prototype of this object is the first argument of the function:

+ +
var a = {a: 1};
+// a ---> Object.prototype ---> null
+
+var b = Object.create(a);
+// b ---> a ---> Object.prototype ---> null
+console.log(b.a); // 1 (inherited)
+
+var c = Object.create(b);
+// c ---> b ---> a ---> Object.prototype ---> null
+
+var d = Object.create(null);
+// d ---> null
+console.log(d.hasOwnProperty);
+// undefined, because d doesn't inherit from Object.prototype
+
+ +
+

With the class keyword

+ +

ECMAScript 2015 introduced a new set of keywords implementing classes. Although these constructs look like those familiar to developers of class-based languages, they are not the same. JavaScript remains prototype-based. The new keywords include {{jsxref("Statements/class", "class")}}, {{jsxref("Classes/constructor", "constructor")}}, {{jsxref("Classes/static", "static")}}, {{jsxref("Classes/extends", "extends")}}, and {{jsxref("Operators/super", "super")}}.

+ +
'use strict';
+
+class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+
+class Square extends Polygon {
+  constructor(sideLength) {
+    super(sideLength, sideLength);
+  }
+  get area() {
+    return this.height * this.width;
+  }
+  set sideLength(newLength) {
+    this.height = newLength;
+    this.width = newLength;
+  }
+}
+
+var square = new Square(2);
+
+ +

Performance

+ +

The lookup time for properties that are high up on the prototype chain can have a negative impact on performance, and this may be significant in code where performance is critical. Additionally, trying to access nonexistent properties will always traverse the full prototype chain.

+ +

Also, when iterating over the properties of an object, every enumerable property that is on the prototype chain will be enumerated.To check whether an object has a property defined on itself and not somewhere on its prototype chain, it is necessary to use the hasOwnProperty method which all objects inherit from Object.prototype. To give you a concrete example, let's take the above graph example code to illustrate it:

+ +
console.log(g.hasOwnProperty('vertices'));
+// true
+
+console.log(g.hasOwnProperty('nope'));
+// false
+
+console.log(g.hasOwnProperty('addVertex'));
+// false
+
+console.log(g.__proto__.hasOwnProperty('addVertex'));
+// true
+
+ +

hasOwnProperty is the only thing in JavaScript which deals with properties and does not traverse the prototype chain.

+ +

Note: It is not enough to check whether a property is undefined. The property might very well exist, but its value just happens to be set to undefined.

+
+ +

Bad practice: Extension of native prototypes

+ +

One mis-feature that is often used is to extend Object.prototype or one of the other built-in prototypes.

+ +

This technique is called monkey patching and breaks encapsulation. While used by popular frameworks such as Prototype.js, there is still no good reason for cluttering built-in types with additional non-standard functionality.

+ +

The only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines, like Array.forEach.

+ +

Example

+ +

B shall inherit from A:

+ +
function A(a) {
+  this.varA = a;
+}
+
+// What is the purpose of including varA in the prototype when A.prototype.varA will always be shadowed by
+// this.varA, given the definition of function A above?
+A.prototype = {
+  varA: null,  // Shouldn't we strike varA from the prototype as doing nothing?
+      // perhaps intended as an optimization to allocate space in hidden classes?
+      // https://developers.google.com/speed/articles/optimizing-javascript#Initializing-instance-variables
+      // would be valid if varA wasn't being initialized uniquely for each instance
+  doSomething: function() {
+    // ...
+  }
+};
+
+function B(a, b) {
+  A.call(this, a);
+  this.varB = b;
+}
+B.prototype = Object.create(A.prototype, {
+  varB: {
+    value: null,
+    enumerable: true,
+    configurable: true,
+    writable: true
+  },
+  doSomething: {
+    value: function() { // override
+      A.prototype.doSomething.apply(this, arguments); // call super
+      // ...
+    },
+    enumerable: true,
+    configurable: true,
+    writable: true
+  }
+});
+B.prototype.constructor = B;
+
+var b = new B();
+b.doSomething();
+
+ +

The important parts are:

+ + + +

prototype and Object.getPrototypeOf

+ +

JavaScript is a bit confusing for developers coming from Java or C++, as it's all dynamic, all runtime, and it has no classes at all. It's all just instances (objects). Even the "classes" we simulate are just a function object.

+ +

You probably already noticed that our function A has a special property called prototype. This special property works with the JavaScript new operator. The reference to the prototype object is copied to the internal [[Prototype]] property of the new instance. For example, when you do var a1 = new A(), JavaScript (after creating the object in memory and before running function A() with this defined to it) sets a1.[[Prototype]] = A.prototype. When you then access properties of the instance, JavaScript first checks whether they exist on that object directly, and if not, it looks in [[Prototype]]. This means that all the stuff you define in prototype is effectively shared by all instances, and you can even later change parts of prototype and have the changes appear in all existing instances, if you wanted to.

+ +

If, in the example above, you do var a1 = new A(); var a2 = new A(); then a1.doSomething would actually refer to Object.getPrototypeOf(a1).doSomething, which is the same as the A.prototype.doSomething you defined, i.e. Object.getPrototypeOf(a1).doSomething == Object.getPrototypeOf(a2).doSomething == A.prototype.doSomething.

+ +

In short, prototype is for types, while Object.getPrototypeOf() is the same for instances.

+ +

[[Prototype]] is looked at recursively, i.e. a1.doSomething, Object.getPrototypeOf(a1).doSomething, Object.getPrototypeOf(Object.getPrototypeOf(a1)).doSomething etc., until it's found or Object.getPrototypeOf returns null.

+ +

So, when you call

+ +
var o = new Foo();
+ +

JavaScript actually just does

+ +
var o = new Object();
+o.[[Prototype]] = Foo.prototype;
+Foo.call(o);
+ +

(or something like that) and when you later do

+ +
o.someProp;
+ +

it checks whether o has a property someProp. If not, it checks Object.getPrototypeOf(o).someProp, and if that doesn't exist it checks Object.getPrototypeOf(Object.getPrototypeOf(o)).someProp, and so on.

+ +
+

In conclusion

+ +

It is essential to understand the prototypal inheritance model before writing complex code that makes use of it. Also, be aware of the length of the prototype chains in your code and break them up if necessary to avoid possible performance problems. Further, the native prototypes should never be extended unless it is for the sake of compatibility with newer JavaScript features.

+
diff --git a/files/id/web/javascript/language_resources/index.html b/files/id/web/javascript/language_resources/index.html new file mode 100644 index 0000000000..bda5fe1f42 --- /dev/null +++ b/files/id/web/javascript/language_resources/index.html @@ -0,0 +1,136 @@ +--- +title: JavaScript language resources +slug: Web/JavaScript/Language_Resources +tags: + - Advanced + - JavaScript +translation_of: Web/JavaScript/Language_Resources +--- +
{{JsSidebar}}
+ +

ECMAScript merupakan bahasa scripting yang membentuk basis dari  JavaScript. ECMAScript di standarisasi oleh organisasi standard ECMA International pada Spesifikasi ECMA-262 dan ECMA-402. Berikut ECMAScript standard yang telah disetujui atau masih dalam pengerjaan:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NamaLinkTanggal rilisDeskripsi
Edisi saat ini
ECMA-262 2017 (ES 8)Working draft, repository2017ECMAScript 2017 (8th Edition), currently work in progress.
ECMA-402 4.0Working draft, repository2017ECMAScript Internationalization API 4.0, currently work in progress.
Obsolete/historical editions
ECMA-262 (ES 1)PDFJune 1997the original ECMAScript standard.
ECMA-262 (ES 2)PDFAugust 1998the second revision of the ECMAScript standard; also ISO standard 16262.
ECMA-262 (ES 3)PDFDecember 1999the third revision of the ECMAScript standard; corresponds to JavaScript 1.5.
+ See also the errata
ECMA-262 (ES 5)PDFDecember 2009ECMAScript 5
+ See also the ES5 errata and ECMAScript 5 support in Mozilla
ECMA-357PDFJune 2004ECMAScript for XML (E4X).
+ See also the E4X errata.
ECMA-357 Edition 2PDFDecember 2005ECMAScript for XML (E4X).
ECMA-262 (ES 5.1)PDF, HTMLJune 2011This version is fully aligned with 3rd edition of the international standard ISO/IEC 16262:2011.
+ It includes ES5 errata fixes, no new features.
ECMA-402 1.0PDF, HTMLDecember 2012ECMAScript Internationalization API 1.0.
ECMA-262 2015 (ES 6)PDF, HTMLJune 2015ECMAScript 2015 (6th Edition).
ECMA-402 2.0PDFJune 2015ECMAScript Internationalization API 2.0.
ECMA-262 2016 (ES 7)HTMLJune 2016ECMAScript 2016 (7th Edition). Now feature frozen. To be ratified later this year (June).
ECMA-402 3.0HTMLJune 2016ECMAScript Internationalization API 3.0. To be ratified later this year (June).
+ +

Lihat entri Wikipedia ECMAScript untuk info lebih lanjut tentang sejarah ECMAScript.

+ +

Anda dapat berpartisipasi atau mengikuti pekerjaan di revisi berikutnya dari spasifikasi bahasa ECMAScript, nama kode "Harmony", dan Spesifikasi ECMAScript Internationalization API melalui public wiki dan es-discuss mailing list tercantum dari ecmascript.org.

+ +

Implementasi

+ + + +

Lihat juga

+ + diff --git a/files/id/web/javascript/memory_management/index.html b/files/id/web/javascript/memory_management/index.html new file mode 100644 index 0000000000..90242f72da --- /dev/null +++ b/files/id/web/javascript/memory_management/index.html @@ -0,0 +1,187 @@ +--- +title: Memory Management +slug: Web/JavaScript/Memory_Management +translation_of: Web/JavaScript/Memory_Management +--- +
{{JsSidebar("Advanced")}}
+ +

Introduction

+ +

Bahasa-bahasa Level Bawah, seperti C, memiliki manajemen memory level rendah yang primitiv seperti malloc() dan  free(). Pada bagian lain, nilai Javascript dialokasikan ketika sesuatu (objek, string,dll.) dibuat dan secara otomatis dibebaskan ketika tidak digunakan lagi. Proses terakhir disebut garbage collection. "Secara Otomatis" ini adalah sumber kekeliruan dan memberikan kesan developer Javascript (dan Bahasa tingkat tinggi lainnya) bahwa mereka bisa memilih untuk tidak mempedulikan tentang manajemen memory, maka itu adalah suatu kesalahan

+ +

Low-level languages, like C, have low-level memory management primitives like malloc() and free(). On the other hand, JavaScript values are allocated when things (objects, strings, etc.) are created and "automatically" freed when they are not used anymore. The latter process is called garbage collection. This "automatically" is a source of confusion and gives JavaScript (and high-level languages) developers the impression they can decide not to care about memory management. This is a mistake.

+ +

Siklus hidup sebuah memori

+ +

Tanpa memperhatikan bahasa pemograman, siklus hidup memori pada akhirnya selalu sama :

+ +
    +
  1. Mengalokasi memori yang kamu gunakan.
  2. +
  3. Menggunakan alokasi memori untuk (baca, tulis).
  4. +
  5. Membebaskan alokasi memori saat tidak digunakan lagi.
  6. +
+ +

Bagian pertama dan kedua bersifat ekplisit untuk semua bahasa. Sedangkan untuk bagian terakhir adalah eksplisit untuk bahasa tingkat rendah, tetapi hampir semua bahasa tingkat atas seperti JavaScript juga bersifat implisit.

+ +

Allocation in JavaScript

+ +

Value initialization

+ +

In order not to bother the programmer with allocations, JavaScript does it alongside with declaring values.

+ +
var n = 123; // allocates memory for a number
+var s = "azerty"; // allocates memory for a string
+
+var o = {
+  a: 1,
+  b: null
+}; // allocates memory for an object and contained values
+
+// (like object) allocates memory for the array and
+// contained values
+var a = [1, null, "abra"];
+
+function f(a){
+  return a + 2;
+} // allocates a function (which is a callable object)
+
+// function expressions also allocate an object
+someElement.addEventListener('click', function(){
+  someElement.style.backgroundColor = 'blue';
+}, false);
+
+ +

Allocation via function calls

+ +

Some function calls result in object allocation.

+ +
var d = new Date(); // allocates a Date object
+
+var e = document.createElement('div'); // allocates a DOM element
+ +

Some methods allocate new values or objects:

+ +
var s = "azerty";
+var s2 = s.substr(0, 3); // s2 is a new string
+// Since strings are immutable value,
+// JavaScript may decide to not allocate memory,
+// but just store the [0, 3] range.
+
+var a = ["ouais ouais", "nan nan"];
+var a2 = ["generation", "nan nan"];
+var a3 = a.concat(a2);
+// new array with 4 elements being
+// the concatenation of a and a2 elements
+
+ +

Using values

+ +

Using value basically means reading and writing in allocated memory. This can be done by reading or writing the value of a variable or an object property or even passing an argument to a function.

+ +

Release when the memory is not needed anymore

+ +

Most of memory management issues come at this phase. The hardest task here is to find when "the allocated memory is not needed any longer". It often requires for the developer to determine where in the program such piece of memory is not needed anymore and free it.

+ +

High-level languages embed a piece of software called "garbage collector" whose job is to track memory allocation and use in order to find when a piece of allocated memory is not needed any longer in which case, it will automatically free it. This process is an approximation since the general problem of knowing whether some piece of memory is needed is undecidable (can't be solved by an algorithm).

+ +

Garbage collection

+ +

As stated above the general problem of automatically finding whether some memory "is not needed anymore" is undecidable. As a consequence, garbage collections implement a restriction of a solution to the general problem. This section will explain the necessary notions to understand the main garbage collection algorithms and their limitations.

+ +

References

+ +

The main notion garbage collection algorithms rely on is the notion of reference. Within the context of memory management, an object is said to reference another object if the former has an access to the latter (either implicitly or explicitly). For instance, a JavaScript object has a reference to its prototype (implicit reference) and to its properties values (explicit reference).

+ +

In this context, the notion of "object" is extended to something broader than regular JavaScript objects and also contains function scopes (or the global lexical scope).

+ +

Reference-counting garbage collection

+ +

This is the most naive garbage collection algorithm. This algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it". An object is considered garbage collectable if there is zero reference pointing at this object.

+ +

Example

+ +
var o = {
+  a: {
+    b:2
+  }
+};
+// 2 objects are created. One is referenced by the other as one of its properties.
+// The other is referenced by virtue of being assigned to the 'o' variable.
+// Obviously, none can be garbage-collected
+
+
+var o2 = o; // the 'o2' variable is the second thing that
+            // has a reference to the object
+o = 1;      // now, the object that was originally in 'o' has a unique reference
+            // embodied by the 'o2' variable
+
+var oa = o2.a; // reference to 'a' property of the object.
+               // This object has now 2 references: one as a property,
+               // the other as the 'oa' variable
+
+o2 = "yo"; // The object that was originally in 'o' has now zero
+           // references to it. It can be garbage-collected.
+           // However what was its 'a' property is still referenced by
+           // the 'oa' variable, so it cannot be freed
+
+oa = null; // what was the 'a' property of the object originally in o
+           // has zero references to it. It can be garbage collected.
+
+ +

Limitation: cycles

+ +

There is a limitation when it comes to cycles. In the following example two objects are created and reference one another – thus creating a cycle. They will not get out of the function scope after the function call, so they are effectively useless and could be freed. However, the reference-counting algorithm considers that since each of both object is referenced at least once and none can be garbage-collected.

+ +
function f(){
+  var o = {};
+  var o2 = {};
+  o.a = o2; // o references o2
+  o2.a = o; // o2 references o
+
+  return "azerty";
+}
+
+f();
+
+ +

Real-life example

+ +

Internet Explorer 6 and 7 are known to have reference-counting garbage collectors for DOM objects. Cycles are a common mistake that can generate memory leaks:

+ +
var div;
+window.onload = function(){
+  div = document.getElementById("myDivElement");
+  div.circularReference = div;
+  div.lotsOfData = new Array(10000).join("*");
+};
+
+ +

In the above example, the DOM element "myDivElement" has a circular reference to itself in the "circularReference" property. If the property is not explicitly removed or nulled, a reference-counting garbage collector will always have at least one reference intact and will keep the DOM element in memory even if it was removed from the DOM tree. If the DOM element holds lots of data (illustrated in the above example with the "lotsOfData" property), the memory consumed by this data will never be released.

+ +

Mark-and-sweep algorithm

+ +

This algorithm reduces the definition of "an object is not needed anymore" to "an object is unreachable".

+ +

This algorithm assumes the knowledge of a set of objects called roots (In JavaScript, the root is the global object). Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

+ +

This algorithm is better than the previous one since "an object has zero reference" leads to this object being unreachable. The opposite is not true as we have seen with cycles.

+ +

As of 2012, all modern browsers ship a mark-and-sweep garbage-collector. All improvements made in the field of JavaScript garbage collection (generational/incremental/concurrent/parallel garbage collection) over the last few years are implementation improvements of this algorithm, but not improvements over the garbage collection algorithm itself nor its reduction of the definition of when "an object is not needed anymore".

+ +

Cycles are not a problem anymore

+ +

In the first above example, after the function call returns, the 2 objects are not referenced anymore by something reachable from the global object. Consequently, they will be found unreachable by the garbage collector.

+ +

The same thing goes with the second example. Once the div and its handler are made unreachable from the roots, they can both be garbage-collected despite referencing each other.

+ +

Limitation: objects need to be made explicitly unreachable

+ +

Although this is marked as a limitation, it is one that is rarely reached in practice which is why no one usually cares that much about garbage collection.

+ +

See also

+ + diff --git a/files/id/web/javascript/new_in_javascript/index.html b/files/id/web/javascript/new_in_javascript/index.html new file mode 100644 index 0000000000..79ee10c2b3 --- /dev/null +++ b/files/id/web/javascript/new_in_javascript/index.html @@ -0,0 +1,74 @@ +--- +title: New in JavaScript +slug: Web/JavaScript/New_in_JavaScript +tags: + - ECMAScript + - JavaScript + - NeedsTranslation + - TopicStub + - Versions +translation_of: Archive/Web/JavaScript/New_in_JavaScript +--- +
{{jsSidebar("New_in_JS")}}
+ +

This chapter contains information about JavaScript's version history and implementation status for Mozilla/SpiderMonkey-based JavaScript applications, such as Firefox.

+ +

ECMAScript versions

+ +
+
Language resources
+
Learn more about the ECMAScript standards on which the JavaScript language is based on.
+
ECMAScript 5 support
+
Implementation status for the current standard ECMA-262 Edition 5.1 in Mozilla-based engines and products.
+
ECMAScript 2015 support
+
Implementation status for the draft ECMA-262 Edition 6 (ES2015) in Mozilla-based engines and products.
+
ECMAScript Next support
+
Implementation status for upcoming ECMA-262 features as per the yearly (ES2016/ES2017/ES2018/...) release schedule in Mozilla-based engines and products.
+
+ +

JavaScript release notes

+ +
+
Firefox JavaScript changelog
+
See this changelog for JavaScript features implemented in Firefox 5 and later.
+
+ +

JavaScript versions

+ +

Deprecated ({{deprecated_inline}}). The explicit versioning and opt-in of language features was Mozilla-specific and are in process of being removed. Firefox 4 was the last version which referred to a JavaScript version (1.8.5). With new ECMA standards, JavaScript language features are now often mentioned with their initial definition in ECMA-262 Editions such as ECMAScript 2015.

+ +

JavaScript was released as version 1.0 in March 1996 in Netscape Navigator 2.0 and Internet Explorer 2.0.

+ +
+
JavaScript 1.1
+
Version shipped in Netscape Navigator 3.0. Released on August 19, 1996.
+
JavaScript 1.2
+
Version shipped in Netscape Navigator 4.0-4.05. Released on June 11, 1997.
+
JavaScript 1.3
+
Version shipped in Netscape Navigator 4.06-4.7x. Released on October 19, 1998.
+ Standardization work to be compliant with ECMA-262 1st and 2nd Edition.
+
JavaScript 1.4
+
Version shipped with Netscape's server-side JavaScript. Released in 1999.
+
JavaScript 1.5
+
Version shipped in Netscape Navigator 6.0 and Firefox 1.0. Release on November 14, 2000.
+ Standardization work to be compliant with ECMA-262 3rd Edition.
+
JavaScript 1.6
+
Version shipped in Firefox 1.5. Released in November 2005.
+ Includes ECMAScript for XML (E4X), new Array methods plus String and Array generics.
+
JavaScript 1.7
+
Version shipped in Firefox 2. Released in October 2006.
+ Includes generators, iterators, array comprehensions, let expressions, and destructuring assignment.
+
JavaScript 1.8
+
Version shipped in Firefox 3. Released in June 2008.
+ Includes expression closures, generator expressions and Array.reduce()
+
JavaScript 1.8.1
+
Version shipped in Firefox 3.5. Released on June 30, 2009.
+ Includes the TraceMonkey JIT and supports native JSON.
+
JavaScript 1.8.2
+
Version shipped in Firefox 3.6. Released June 22, 2009.
+ Includes only minor changes.
+
JavaScript 1.8.5
+
Version shipped in Firefox 4. Released July 27, 2010.
+ Includes many new features for ECMA-262 Edition 5 compliance.
+ This is the last JavaScript version.
+
diff --git a/files/id/web/javascript/panduan/closures/index.html b/files/id/web/javascript/panduan/closures/index.html new file mode 100644 index 0000000000..73cdbb7e15 --- /dev/null +++ b/files/id/web/javascript/panduan/closures/index.html @@ -0,0 +1,345 @@ +--- +title: Closures +slug: Web/JavaScript/Panduan/Closures +translation_of: Web/JavaScript/Closures +--- +

Closure adalah fungsi yang merujuk kepada variabel yang mandiri (bebas). 

+ +

Dengan kata lain, fungsi yang di definisikan di dalam closure 'mengingat' lingkungan dimana closure ini didefinisikan. 

+ +

Lihat contoh berikut:

+ +
+
function init() {
+    var name = "Mozilla"; // name adalah sebuah lokal variabel yang dibuat oleh init
+    function displayName() { // displayName() adalah fungsi internal, sebuah closure
+        alert (name); // displayName() menggunakan variabel yang dideklarasikan pada fungsi induknya
+    }
+    displayName();
+}
+init();
+
+
+ +

init() membuat sebuah lokal variabel name dan kemudian memanggil fungsi displayName(). displayName() adalah fungsi internal yang didefinisikan didalam init() dan hanya dapat diakses di dalam fungsi tersebut. displayName() tidak memiliki lokal variabelnya sendiri, namun fungsi ini memiliki akses ke variabel diluar fungsinya dan dapat menggunakan variabel name tersebut yang telah di deklarasikan di fungsi induknya.

+ +

Jalankan kode dan perhatikan bahwa alert() dapat menampilkan isi dari variabel name, dimana variabel tersebut dideklarasikan pada fungsi induknya. Ini adalah sebuah contoh dari ruang lingkup leksikal (lexical scoping), yang menunjukan bagaimana cara javascript mencari variabel. Di Javascript lokasi dimana variabel tersebut dideklarasikan di dalam source code menentukan dimana variabel itu dapat diakses. Nested functions memiliki akses pada variabel yang dideklarasikan pada ruang lingkup induknya.

+ +

Lihat contoh berikut:

+ +
function makeFunc() {
+  var name = "Mozilla";
+  function displayName() {
+    alert(name);
+  }
+  return displayName;
+}
+
+var myFunc = makeFunc();
+myFunc();
+
+ +

Jika kamu menjalankan kode ini, kode ini akan memiliki efek yang sama seperti contoh sebelumnya init(): teks "Mozilla" akan muncul di JavaScript alert box. Yang membedakan dan menarik adalah fungsi internal displayName() di kembalikan terlebih dahulu ke fungsi di luar sebelum di eksekusi.

+ +

Jika dilihat ini agak aneh karena normalnya pada bahasa pemrograman lain, variabel lokal di dalam sebuah fungsi hanya ada saat fungsi tersebut dieksekusi. Sehingga saat makeFunc() selesai dieksekusi, sewajarnya variabel name ini tidak dapat diakses lagi. Namun, karena kode ini masih berjalan normal, ini adalah hal yang berbeda di Javascript.

+ +

Alasannya adalah fungsi tersebut telah menjadi closure di javascript. Closure adalah kombinasi dari fungsi dan lingkungan leksikal dimana fungsi itu di deklarasikan. Lingkungan ini terdiri dari lokal variabel yang berada di ruang lingkup yang sama saat closure dibuat. Pada kasus ini, myFunc bereferensi kepada fungsi displayName yang telah dibuat ketika makeFunc dijalankan. Fungsi displayName akan tepat menjaga akses ke lingkungan leksikalnya, dimana variabel name ini aktif. Untuk alasan inilah, ketika myFunc di panggil, variabel name tetap dapat digunakan dan "Mozilla" dikirim ke alert box.

+ +

Berikut adalah contoh menarik yang lainnya — fungsi makeAdder :

+ +
function makeAdder(x) {
+  return function(y) {
+    return x + y;
+  };
+}
+
+var add5 = makeAdder(5);
+var add10 = makeAdder(10);
+
+console.log(add5(2));  // 7
+console.log(add10(2)); // 12
+
+ +

Di contoh ini, kita telah mendefinisikan fungsi makeAdder(x) dengan satu argument x dan mengembalikan sebuah fungsi baru. Fungsi yang dikembalikan membutuhkan satu argumen y, dan mengembalikan jumlah x dan y.

+ +

Esensinya, makeAdder adalah fungsi untuk membuat fungsi (function factory) — fungsi ini akan membuat fungsi yang akan menambahkan angka melalui argumen. Pada contoh diatas kita membuat dua fungsi baru — yang satu menambahkan 5 melalui argumentnya dan satu menambahkan 10.

+ +

add5 dan add10 keduanya adalah closure. Fungsi ini menggunakan definisi fungsi yang sama, namun menggunakan memori yang berbeda. Di add5 variabel x memiliki nilai 5. sedangkan di add10 variabel x memiliki nilai 10.

+ +

Penggunaan Closure

+ +

Setelah membaca teorinya muncul pertanyaan —  Apakah closure berguna? Mari kita lihat implikasi dari penggunaan closure. Closure membantu kita mengakses data (pada lingkungannya) dengan fungsi yang mengoperasikan data tersebut. Ini berhubungan dengan object oriented programming, dimana objek obj0ek tersebut membantu kita dalam menghubukan beberapa data (properti objek) dengan satu atau lebih method.

+ +

Karena itu, kamu dapat menggunakan closure dimanapun kamu dapat menggunakan objek dengan satu method.

+ +

Situasi ini banyak ditemui umumnya pada pengembangan web. Banyak kode yang kita tulis di Javascript berdasarkan event — kita definisikan terlebih dahulu sifat dari event ini, kemudian menempelkannya pada event yang di panggil oleh user (seperti klik atau penekanan tombol). Kode kita secara garis umum adalah sebuah callback: sebuah fungsi yang dijalankan untuk merespon sebuah event.

+ +

Berikut adalah contoh: kita ingin menambahkan beberapa tombol di sebuah halaman yang akan merubah ukuran teks. Cara untuk melakukannya adalah dengan menentukan ukuran huruf dari elemen body dalam satuan unit pixel, kemudian menentukan ukuran elemen lain di halaman (seperti header) menggunakan satuan unit em:

+ +
body {
+  font-family: Helvetica, Arial, sans-serif;
+  font-size: 12px;
+}
+
+h1 {
+  font-size: 1.5em;
+}
+
+h2 {
+  font-size: 1.2em;
+}
+
+ +

Tombol interaktif kita dapat merubah ukuran huruf dari elemen body dan elemen yang lainnya akan menyesuaikan.

+ +

Berikut kode Javascript:

+ +
function makeSizer(size) {
+  return function() {
+    document.body.style.fontSize = size + 'px';
+  };
+}
+
+var size12 = makeSizer(12);
+var size14 = makeSizer(14);
+var size16 = makeSizer(16);
+
+ +

size12, size14, dan size16 adalah fungsi yang akan merubah ukuran teks body ke 12, 14, dan 16 pixel, secara berurutan. Kemudian kita tempelkan fungsi ini ke tombol (pada kasus ini adalah link) sebagai berikut:

+ +
document.getElementById('size-12').onclick = size12;
+document.getElementById('size-14').onclick = size14;
+document.getElementById('size-16').onclick = size16;
+
+ +
<a href="#" id="size-12">12</a>
+<a href="#" id="size-14">14</a>
+<a href="#" id="size-16">16</a>
+
+ +

Lihat pada JSFiddle

+ +

Emulating private methods with closures

+ +

Languages such as Java provide the ability to declare methods private, meaning that they can only be called by other methods in the same class.

+ +

JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures. Private methods aren't just useful for restricting access to code: they also provide a powerful way of managing your global namespace, keeping non-essential methods from cluttering up the public interface to your code.

+ +

Here's how to define some public functions that can access private functions and variables, using closures which is also known as the module pattern:

+ +
var counter = (function() {
+  var privateCounter = 0;
+  function changeBy(val) {
+    privateCounter += val;
+  }
+  return {
+    increment: function() {
+      changeBy(1);
+    },
+    decrement: function() {
+      changeBy(-1);
+    },
+    value: function() {
+      return privateCounter;
+    }
+  };
+})();
+
+alert(counter.value()); /* Alerts 0 */
+counter.increment();
+counter.increment();
+alert(counter.value()); /* Alerts 2 */
+counter.decrement();
+alert(counter.value()); /* Alerts 1 */
+
+ +

There's a lot going on here. In previous examples each closure has had its own environment; here we create a single environment which is shared by three functions: counter.increment, counter.decrement, and counter.value.

+ +

The shared environment is created in the body of an anonymous function, which is executed as soon as it has been defined. The environment contains two private items: a variable called privateCounter and a function called changeBy. Neither of these private items can be accessed directly from outside the anonymous function. Instead, they must be accessed by the three public functions that are returned from the anonymous wrapper.

+ +

Those three public functions are closures that share the same environment. Thanks to JavaScript's lexical scoping, they each have access to the privateCounter variable and changeBy function.

+ +

You'll notice we're defining an anonymous function that creates a counter, and then we call it immediately and assign the result to the counter variable. We could store this function in a separate variable makeCounter and use it to create several counters.

+ +
var makeCounter = function() {
+  var privateCounter = 0;
+  function changeBy(val) {
+    privateCounter += val;
+  }
+  return {
+    increment: function() {
+      changeBy(1);
+    },
+    decrement: function() {
+      changeBy(-1);
+    },
+    value: function() {
+      return privateCounter;
+    }
+  }
+};
+
+var counter1 = makeCounter();
+var counter2 = makeCounter();
+alert(counter1.value()); /* Alerts 0 */
+counter1.increment();
+counter1.increment();
+alert(counter1.value()); /* Alerts 2 */
+counter1.decrement();
+alert(counter1.value()); /* Alerts 1 */
+alert(counter2.value()); /* Alerts 0 */
+
+ +

Notice how each of the two counters maintains its independence from the other. Its environment during the call of the makeCounter() function is different each time. The closure variable privateCounter contains a different instance each time.

+ +

Using closures in this way provides a number of benefits that are normally associated with object oriented programming, in particular data hiding and encapsulation.

+ +

Creating closures in loops: A common mistake

+ +

Prior to the introduction of the let keyword in JavaScript 1.7, a common problem with closures occurred when they were created inside a loop. Consider the following example:

+ +
<p id="help">Helpful notes will appear here</p>
+<p>E-mail: <input type="text" id="email" name="email"></p>
+<p>Name: <input type="text" id="name" name="name"></p>
+<p>Age: <input type="text" id="age" name="age"></p>
+
+ +
function showHelp(help) {
+  document.getElementById('help').innerHTML = help;
+}
+
+function setupHelp() {
+  var helpText = [
+      {'id': 'email', 'help': 'Your e-mail address'},
+      {'id': 'name', 'help': 'Your full name'},
+      {'id': 'age', 'help': 'Your age (you must be over 16)'}
+    ];
+
+  for (var i = 0; i < helpText.length; i++) {
+    var item = helpText[i];
+    document.getElementById(item.id).onfocus = function() {
+      showHelp(item.help);
+    }
+  }
+}
+
+setupHelp();
+
+ +

Lihat pada JSFiddle

+ +

The helpText array defines three helpful hints, each associated with the ID of an input field in the document. The loop cycles through these definitions, hooking up an onfocus event to each one that shows the associated help method.

+ +

If you try this code out, you'll see that it doesn't work as expected. No matter what field you focus on, the message about your age will be displayed.

+ +

The reason for this is that the functions assigned to onfocus are closures; they consist of the function definition and the captured environment from the setupHelp function's scope. Three closures have been created, but each one shares the same single environment. By the time the onfocus callbacks are executed, the loop has run its course and the item variable (shared by all three closures) has been left pointing to the last entry in the helpText list.

+ +

One solution in this case is to use more closures: in particular, to use a function factory as described earlier on:

+ +
function showHelp(help) {
+  document.getElementById('help').innerHTML = help;
+}
+
+function makeHelpCallback(help) {
+  return function() {
+    showHelp(help);
+  };
+}
+
+function setupHelp() {
+  var helpText = [
+      {'id': 'email', 'help': 'Your e-mail address'},
+      {'id': 'name', 'help': 'Your full name'},
+      {'id': 'age', 'help': 'Your age (you must be over 16)'}
+    ];
+
+  for (var i = 0; i < helpText.length; i++) {
+    var item = helpText[i];
+    document.getElementById(item.id).onfocus = makeHelpCallback(item.help);
+  }
+}
+
+setupHelp();
+
+ +

Lihat pada JSFiddle

+ +

This works as expected. Rather than the callbacks all sharing a single environment, the makeHelpCallback function creates a new environment for each one in which help refers to the corresponding string from the helpText array.

+ +

Performance considerations

+ +

It is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption.

+ +

For instance, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. The reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation).

+ +

Consider the following impractical but demonstrative case:

+ +
function MyObject(name, message) {
+  this.name = name.toString();
+  this.message = message.toString();
+  this.getName = function() {
+    return this.name;
+  };
+
+  this.getMessage = function() {
+    return this.message;
+  };
+}
+
+ +

The previous code does not take advantage of the benefits of closures and thus could instead be formulated:

+ +
function MyObject(name, message) {
+  this.name = name.toString();
+  this.message = message.toString();
+}
+MyObject.prototype = {
+  getName: function() {
+    return this.name;
+  },
+  getMessage: function() {
+    return this.message;
+  }
+};
+
+ +

However, redefining the prototype is not recommended, so the following example is even better because it appends to the existing prototype:

+ +
function MyObject(name, message) {
+  this.name = name.toString();
+  this.message = message.toString();
+}
+MyObject.prototype.getName = function() {
+  return this.name;
+};
+MyObject.prototype.getMessage = function() {
+  return this.message;
+};
+
+ +

In the two previous examples, the inherited prototype can be shared by all objects and the method definitions need not occur at every object creation. See Details of the Object Model for more details.

+ +

Expression closures

+ +

This addition is nothing more than a shorthand for writing simple functions, giving the language something similar to a typical Lambda notation.

+ +

JavaScript 1.7 and older:

+ +
function(x) { return x * x; }
+ +

JavaScript 1.8:

+ +
function(x) x * x
+ +

This syntax allows you to leave off the braces and 'return' statement - making them implicit. There is no added benefit to writing code in this manner, other than having it be syntactically shorter.

+ +

Examples:

+ +

A shorthand for binding event listeners:

+ +
 document.addEventListener("click", function() false, true);
+
+ +

Using this notation with some of the array functions from JavaScript 1.6:

+ +
elems.some(function(elem) elem.type == "text");
diff --git a/files/id/web/javascript/panduan/index.html b/files/id/web/javascript/panduan/index.html new file mode 100644 index 0000000000..491d4a4a84 --- /dev/null +++ b/files/id/web/javascript/panduan/index.html @@ -0,0 +1,119 @@ +--- +title: Panduan JavaScript +slug: Web/JavaScript/Panduan +translation_of: Web/JavaScript/Guide +--- +
{{jsSidebar("JavaScript Guide")}}
+ +

Pedoman javasript memberi tahu bagaimana menggunakan JavaScript dan memberikan penjelasan tentang bahasa javascript. Jika anda ingin memulai javascript atau programming secara umum, konsultasikan artikel di Area pembelajaran. Jika anda membutuhkan informasi lengkap tentang fitur silakan lihat  Referensi javaScript.

+ +

Bagian

+ +

Pedoman ini dibagi menjadi beberapa bagian:

+ + + + + + + + + +

{{Next("Web/JavaScript/Guide/Introduction")}}

diff --git a/files/id/web/javascript/panduan/loops_and_iteration/index.html b/files/id/web/javascript/panduan/loops_and_iteration/index.html new file mode 100644 index 0000000000..7fbb416c43 --- /dev/null +++ b/files/id/web/javascript/panduan/loops_and_iteration/index.html @@ -0,0 +1,330 @@ +--- +title: Loops and iteration +slug: Web/JavaScript/Panduan/Loops_and_iteration +translation_of: Web/JavaScript/Guide/Loops_and_iteration +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}
+ +

Loop menawarkan cara cepat dan mudah untuk melakukan sesuatu secara berulang-ulang. Bab tentang Panduan JavaScript ini memperkenalkan berbagai pernyataan iterasi berbeda yang tersedia untuk JavaScript.

+ +

Anda dapat menganggap loop sebagai versi permainan terkomputerisasi di mana Anda menyuruh seseorang untuk mengambil langkah X menuju satu arah lalu langkah Y ke arah yang lain; Sebagai contoh, gagasan "Pergilah lima langkah ke timur" dapat di ekspresikan dengan cara berikut sebagai sebuah loop (pengulangan):

+ +
var langkah;
+for (langkah= 0; langkah< 5; langkah++) {
+  // berlari 5 kali, dengan nilai langkah 0 sampai 4.
+  console.log('Berjalan ke timur satu langkah');
+}
+
+ +

Ada beberapa jenis loop yang berbeda, namun pada dasarnya semuanya melakukan hal yang sama, mereka mengulangi sebuah aksi beberapa kali (dan sebenarnya memungkinkan bahwa dapat saja menjadi nol). Berbagai mekanisme loop menawarkan berbagai cara untuk menentukan titik awal dan akhir perulangan. Ada berbagai situasi yang lebih mudah dikerjakan oleh sebuah tipe loop dibandingkan tipe (loop) yang lain.

+ +

Pernyataan untuk loop yang disediakan dalam JavaScript adalah:

+ + + +

for statement

+ +

Sebuah {{jsxref("statements/for","for loop")}} mengulang hingga kondisi yang ditentukan evaluasinya menjadi salah/false.  for loop pada Javascript serupa dengan  for loop pada Java dan C. Sebuah statement (pernyataan) for   terlihat sebagai berikut:

+ +
for ([initialExpression]; [condition];
+[incrementExpression]) statement
+
+ +

Ketika sebuah for loop dieksekusi, Berikut ini akan terjadi:

+ +
    +
  1. Ekspresi yang menginisialisasi yaitu initialExpression, Jika ada, maka akan di eksekusi. Ekspresi ini biasanya menginisialisasi satu atau lebih penghitung loop, tetapi sintaksnya memperbolehkan ekspresi dengan tingkat kerumitan apapun. Ekspresi ini juga bisa mendeklarasikan variabel.
  2. +
  3. Ekpresi condition di evaluasi. JIka value dari kondisi adalah true (benar), maka statement loop akan dieksekusi. Jika value dari condition false (salah), for loop akan dihentikan.  Jika ekspresi condition dihilangkan sama sekali, kondisinya diasumsikan benar.
  4. +
  5. Mengeksekusi Statement . Untuk mengeksekusi berbagai pernyataan, gunakanlah sebuah blok pernyataan ({ ... }untuk mengelompokkan pernyataan-pernyataan tersebut.
  6. +
  7. Jika ada, ekspresi baru incrementExpression di eksekusi.
  8. +
  9. Kontrol kembali ke langkah ke-2.
  10. +
+ +

Contoh

+ +

function (fungsi) berikut memuat sebuah statement for yang menghitung angka dari opsi yang terpilih dalam sebuah daftar scrolling  (sebuah elemen {{HTMLElement("select")}} yang memperbolehkan berbagai pilihan). Statement for mendeklarasikan variable i dan menginisialisasinya ke nol. Ia memeriksa bahwa i lebih kecil dari nomor dari opsi dalam elemen <select> , menampilkan statement if yang berhasil, dan menaikan i satu setelah masing-masing lolos melewati loop.

+ +
<form name="selectForm">
+  <p>
+    <label for="musicTypes">Choose some music types, then click the button below:</label>
+    <select id="musicTypes" name="musicTypes" multiple="multiple">
+      <option selected="selected">R&B</option>
+      <option>Jazz</option>
+      <option>Blues</option>
+      <option>New Age</option>
+      <option>Classical</option>
+      <option>Opera</option>
+    </select>
+  </p>
+  <p><input id="btn" type="button" value="How many are selected?" /></p>
+</form>
+
+<script>
+function howMany(selectObject) {
+  var numberSelected = 0;
+  for (var i = 0; i < selectObject.options.length; i++) {
+    if (selectObject.options[i].selected) {
+      numberSelected++;
+    }
+  }
+  return numberSelected;
+}
+
+var btn = document.getElementById('btn');
+btn.addEventListener('click', function() {
+  alert('Number of options selected: ' + howMany(document.selectForm.musicTypes));
+});
+</script>
+
+
+ +

do...while statement

+ +

Pernyataan/statement {{jsxref("statements/do...while", "do...while")}} terus di ulangi sampai evaluasi kondisi bernilai false/salah. Sebuah do...while statement terlihat sebagai berikut:

+ +
do
+  statement
+while (condition);
+
+ +

statement di jalankan lebih dulu sebelum kondisi diperiksa. Untuk menjalankan banyak statements, gunakan statement blok ({ ... }) untuk membuat grup dari statement tersebut. Jika condition bernilai benar, maka statement akan dijalankan kembali. Kondisi diperiksa pada setiap akhir eksekusi. Ketika kondisi bernilai salah, eksekusi berhenti dan kontrol akan melewati pernyataan yang mengikuti do...while.

+ +

Contoh

+ +

Dalam contoh berikut, perulangan do di iterasi sekali dan di iterasi kembali sampai i tidak lagi kurang dari 5. 

+ +
var i = 0;
+do {
+  i += 1;
+  console.log(i);
+} while (i < 5);
+ +

while statement

+ +

Sebuah statement {{jsxref("statements/while","while")}} di eksekusi pernyataan pernyataannya asalkan memenuhi syarat kondisinya yang bernilai true/benar. Sebuah statement  while terlihat sebagai berikut:

+ +
while (condition)
+  statement
+
+ +

Jika kondisi bernilai false/salah, statement dengan perulangan berhenti di eksekusi dan kontrol akan melewati statement yang mengikuti perulangan tersebut.

+ +

Kondisi terjadi sebelum statement dalam perulangan di eksekusi. Jika kondisi bernilai true/benar, statement di eksekusi dan kondisi di uji kembali. Jika kondisi bernilai false/salah, eksekusi akan berhenti dan konrol lewat untuk statement yang mengikuti while.

+ +

Untuk mengeksekusi banyak statement, gunakan blok statement ({ ... }) untuk mengelompokan banyak statement tersebut.

+ +

Contoh 1

+ +

Beikut perulangan while mengiterasi n selama n kurang dari tiga:

+ +
var n = 0;
+var x = 0;
+while (n < 3) {
+  n++;
+  x += n;
+}
+
+ +

Dengan setiap iterasi, perulangan akan menambahkan increments n dan menambahkan nilainya pada  x. Karena itu, x dan n mengambil nilai nilai berikut:

+ + + +

Setelah melewati perulangan yang ketiga , kondisinya n < 3 tidak lagi bernilai true/benar, jadi perulangan di hentikan.

+ +

Contoh 2

+ +

Hindari perulangan tanpa batas. Pastikan kondisi dalam perulangan mendapatkan kondisi yang bernilai false/salah untuk berhenti, jika tidak perulangan tidak akan pernah berhenti. Statements dalam while berikut di eksekusi berulang kali selamanya karena kondisi tidak pernah mendapatkan nilai false/salah:

+ +
while (true) {
+  console.log('Hello, world!');
+}
+ +

labeled statement

+ +

Sebuah {{jsxref("statements/label","label")}} menyediakan sebuah statement dengan pengenal yang memungkinkan Anda merujuknya di tempat lain dalam program Kamu. Untuk contohnya, Kamu dapat menggunakan label untuk mengidentifikasi pengulangan, lalu gunakan statement break atau continue untuk menunjukkan apakah suatu program harus memutuskan loop atau melanjutkan eksekusinya.

+ +

Sintak dari statement berlabel terlihat seperti berikut:

+ +
label :
+   statement
+
+ +

Nilai dai sebuah label dapat berupa identifikasi JavaScript apa pun yang tidak dari kata  kunci yang ada pada javascript. statement
+ yang Kamu identifikasi dengan label tersebut dapat berupa statement apa pun.

+ +

Contoh

+ +

Pada contoh ini, label markLoop mengidentifikasi sebuah perulangan while.

+ +
markLoop:
+while (theMark == true) {
+   doSomething();
+}
+ +

break statement

+ +

Gunakan {{jsxref("statements/break","break")}} statement untuk menghentikan perulangan, switch, atau konjungsi dengan statement yang memakai label.

+ + + +

Sintak dari statement break terlihat seperti ini:

+ +
break [label];
+
+ +

Bentuk pertama sintak mengakhiri perulangan atau switch; Bentuk kedua sintak mengakhiri statement dari spesifik label.

+ +

Contoh 1

+ +

Contoh berikut mengiterasi melewati elemen-elemen dalam array sampai menemukan indeks elemen  yang bernilai dari theValue:

+ +
for (var i = 0; i < a.length; i++) {
+  if (a[i] == theValue) {
+    break;
+  }
+}
+ +

Contoh 2: Breaking pada sebuah label

+ +
var x = 0;
+var z = 0;
+labelCancelLoops: while (true) {
+  console.log('Outer loops: ' + x);
+  x += 1;
+  z = 1;
+  while (true) {
+    console.log('Inner loops: ' + z);
+    z += 1;
+    if (z === 10 && x === 10) {
+      break labelCancelLoops;
+    } else if (z === 10) {
+      break;
+    }
+  }
+}
+
+ +

continue statement

+ +

Statement {{jsxref("statements/continue","continue")}} bisa digunakan untuk memulai lagi statement while, do-while, for, atau label.

+ + + +

Sintak statement continue terlihat sebagai berikut:

+ +
continue [label];
+
+ +

Contoh 1

+ +

Contoh berikut menunjukkan sebuah perulangan while dengan sebuah statement continue yang di eksekusi ketika niai dari i adalah tiga  Jadi, n mengambil nilai satu, tiga, tujuh dan dua belas.

+ +
var i = 0;
+var n = 0;
+while (i < 5) {
+  i++;
+  if (i == 3) {
+    continue;
+  }
+  n += i;
+}
+
+ +

Contoh 2

+ +

Sebuah statement yang berlabel checkiandj berisikan sebuah statement berlabel checkj. Jika ada continue , Programnya akan menghentikan iterasi saat ini dari checkj dan memulai iterasi selanjutnya. Setiap kali continue ditemui, checkj  di iterasi kembali sampai kondisinya bernilai false/salah. Ketika bernilai false/salah, Sisa dari statement checkiandj sudah selesai, dan checkiandj di iterasi kembali sampai kondisi bernilai salah false. Ketika bernilai salah false , program melanjutkan pada statement yang mengikuti checkiandj.

+ +

JIka continue dipunyai label dari checkiandj, program akan terus berlanjut ke bagian atas dari statement checkiandj .

+ +
checkiandj:
+  while (i < 4) {
+    console.log(i);
+    i += 1;
+    checkj:
+      while (j > 4) {
+        console.log(j);
+        j -= 1;
+        if ((j % 2) == 0) {
+          continue checkj;
+        }
+        console.log(j + ' is odd.');
+      }
+      console.log('i = ' + i);
+      console.log('j = ' + j);
+  }
+ +

for...in statement

+ +

Statement {{jsxref("statements/for...in","for...in")}} mengiterasi sebuah variabel spesifik diatas properti enumerable dari sebuah objek. Untuk setiap properti yang berbeda, JavaScript mengeksekusi pernyataan pernyataan yang spesifik. Sebuah statement for...in terlihat sebagai berikut:

+ +
for (variable in object) {
+  statements
+}
+
+ +

Contoh

+ +

Function/fungsi berikut mengambil argumentnya dari sebuah objek dan nama objek. Lalu dia di iterasi diatas semua property objek dan mengembalikan sebuah string yang mendaftarkan nama properti dan nilainya.

+ +
function dump_props(obj, obj_name) {
+  var result = '';
+  for (var i in obj) {
+    result += obj_name + '.' + i + ' = ' + obj[i] + '<br>';
+  }
+  result += '<hr>';
+  return result;
+}
+
+ +

Untuk sebuah objek car dengan property make dan model, result/hasil akan menjadi:

+ +
car.make = Ford
+car.model = Mustang
+
+ +

Arrays

+ +

Meskipun mungkin menggunakan ini sebagai cara untuk melakukan iterasi di atas elemen {{jsxref("Array")}},statement for...in akan mengembalikan nilai nama property yang di tetapkan pengguna dalam penambahan numerik indek. Jadi lebih baik menggunakan tradisional perulangan {{jsxref("statements/for","for")}} dengan sebuah numerik indek ketika mengiterasi diatas array, karena statement  for...in mengiterasi diatas nama properti yang di tetapkan pengguna pada penambahan elemen array, Jika kamu merubah array, seperti menambahkan properti atau metode. 

+ +

for...of statement

+ +

Statement {{jsxref("statements/for...of","for...of")}} membuat sebuah iterasi perulangan diatas iterable objects (termasuk {{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("functions/arguments","arguments")}} object dan seterusnya), menjalankan hubungan iterasi khusus dengan statement yang akan dieksekusi untuk setiap nilai properti yang berbeda.

+ +
for (variable of object) {
+  statement
+}
+ +

Contoh berikut menampilkan perbedaan diantara sebuah perulangan for...of dan sebuah perulangan {{jsxref("statements/for...in","for...in")}}. Ketika for...in mengiterasi diatas nama-nama properti, for...of mengiterasi diatas nilai-nilai properti:

+ +
let arr = [3, 5, 7];
+arr.foo = 'hello';
+
+for (let i in arr) {
+   console.log(i); // logs "0", "1", "2", "foo"
+}
+
+for (let i of arr) {
+   console.log(i); // logs 3, 5, 7
+}
+
+ +

{{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}

diff --git a/files/id/web/javascript/panduan/numbers_and_dates/index.html b/files/id/web/javascript/panduan/numbers_and_dates/index.html new file mode 100644 index 0000000000..e9681b2adf --- /dev/null +++ b/files/id/web/javascript/panduan/numbers_and_dates/index.html @@ -0,0 +1,376 @@ +--- +title: Numbers and dates +slug: Web/JavaScript/Panduan/Numbers_and_dates +translation_of: Web/JavaScript/Guide/Numbers_and_dates +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}
+ +

Pada Bab ini memperkenalkan cara menggunakan angka dan tanggal pada JavaScript.

+ +

Angka

+ +

Pada JavaScript, semua angka diimplementasikan kedalam double-precision 64-bit binary format IEEE 754 (mis. angka antara -(253 -1) dan 253 -1). Tidak ada jenis spesifik untuk integer. Selain bisa mewakili angka float, tipe data angka memiliki 3 nilai secara simbolik: +{{jsxref("Infinity")}}, -{{jsxref("Infinity")}}, dan {{jsxref("NaN")}} (bukan sebuah angka). Lihat juga JavaScript tipe data dan struktur untuk konteks dengan tipe data primitif JavaScript yang lain.

+ +

Anda dapat menggunakan empat tipe angka literal: desimal, biner, oktal, dan heksadesimal.

+ +

Angka Desimal

+ +
1234567890
+42
+
+// Perhatikan ketika menggunakan angka berawalan nol:
+
+0888 // 888 diubah menjadi desimal
+0777 // diubah menjadi oktal pada non-strict mode (511 in decimal)
+
+ +

Perhatikan bahwa desimal literal dapat dimulai dari nol(0) diikuti angka desimal yang lain, namun jika setiap angka setelah 0 lebih kecil dari 8, angkanya diubah menjadi oktal.

+ +

Angka Biner

+ +

Sintaks angka biner menggunakan angka nol diikuti dengan huruf kecil atau dengan huruf besar, huruf Latin "B" (0b atau 0B). Jika digit setelah 0b atau bukan 0 atau 1, menurut SyntaxError yang dilemparkan: "Missing binary digits after 0b".

+ +
var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
+var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
+var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
+ +

Angka oktal

+ +

Angka oktal menggunakan awalan angka nol. Jika digit setelah 0 berada diluar jangkauan 0 hinga 7, angka akan diintrepretasikan sebagai angka desimal.

+ +
var n = 0755; // 493
+var m = 0644; // 420
+
+ +

Mode ketat pada ECMAScript 5 melarang sintaks oktal. Oktal sintaks bukan bagian dari ECMAScript 5, namun didukung oleh semua peramban dengan cara awalan nomor oktal dengan angka nol: 0644 === 420 dan "\045" === "%". Pada ECMAScript 2015, angka oktal didukung jika diawali dengan 0o, e.g.: 

+ +
var a = 0o10; // ES2015: 8
+
+ +

Angka Heksadesimal

+ +

Sintaks heksadesimal menggunakan awalan nol diikuti dengan huruf kecil atau huruf kapital Latin "X" (0x atau 0X). Jika digit setelah 0x berada diluar jangkauan (0123456789ABCDEF),  menurut SyntaxError yang dilemparkan: "Identifier starts immediately after numeric literal".

+ +
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
+0x123456789ABCDEF   // 81985529216486900
+0XA                 // 10
+
+ +

Eksponensial

+ +
1E3   // 1000
+2e6   // 2000000
+0.1e2 // 10
+ +

Angka object

+ +

The built-in {{jsxref("Number")}} objek memiliki properti untuk numerik konstanta, seperti nilai maksimal, bukan-sebuah-angka, dan tak terhingga. Anda tidak dapat mengganti nilai dari properti tersebut dan anda dapat menggunakannya sebagai berikut:

+ +
var biggestNum = Number.MAX_VALUE;
+var smallestNum = Number.MIN_VALUE;
+var infiniteNum = Number.POSITIVE_INFINITY;
+var negInfiniteNum = Number.NEGATIVE_INFINITY;
+var notANum = Number.NaN;
+
+ +

Anda selalu mengacu pada properti dari objek angka yang telah ditentukan seperti yang ditunjukkan diatas, dan bukan sebagai properti objek angka yang anda tentukan.

+ +

Tabel berikut meringkas sifat-sifat nomor object.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Properties of Number
PropertiDeskripsi
{{jsxref("Number.MAX_VALUE")}}Merepresantikan angka maksimal / terbesar
{{jsxref("Number.MIN_VALUE")}}Merepresantikan angka minimal / terkecil
{{jsxref("Number.NaN")}}Nilai spesial "bukan sebuah angka"
{{jsxref("Number.NEGATIVE_INFINITY")}}Nilai spesial negatif tak terhingga; dikembalikan pada overflow
{{jsxref("Number.POSITIVE_INFINITY")}}Nilai spesial positif tak terhingga; dikembalikan pada overflow
{{jsxref("Number.EPSILON")}}Perbedaan antara satu dan nilai terkecil lebih besar dari satu yang dapat direpresentasikan sebagai {{jsxref("Number")}}.
{{jsxref("Number.MIN_SAFE_INTEGER")}}Bilangan bulat aman minimum dalam JavaScript.
{{jsxref("Number.MAX_SAFE_INTEGER")}}Bilangan bulat aman maksimum dalam JavaScript.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Methods of Number
MethodDescription
{{jsxref("Number.parseFloat()")}}Parses a string argument and returns a floating point number.
+ Same as the global {{jsxref("parseFloat", "parseFloat()")}} function.
{{jsxref("Number.parseInt()")}}Parses a string argument and returns an integer of the specified radix or base.
+ Same as the global {{jsxref("parseInt", "parseInt()")}} function.
{{jsxref("Number.isFinite()")}}Determines whether the passed value is a finite number.
{{jsxref("Number.isInteger()")}}Determines whether the passed value is an integer.
{{jsxref("Number.isNaN()")}}Determines whether the passed value is {{jsxref("Global_Objects/NaN", "NaN")}}. More robust version of the original global {{jsxref("Global_Objects/isNaN", "isNaN()")}}.
{{jsxref("Number.isSafeInteger()")}}Determines whether the provided value is a number that is a safe integer.
+ +

Prototipe Angka menyediakan metode-metode untuk menampilkan informasi dari objek angka dalam format bervariasi. Tabel berikut meringkas metode-metode prototipe angka.

+ + + + + + + + + + + + + + + + + + + + + + + +
Methods of Number.prototype
MethodDescription
{{jsxref("Number.toExponential", "toExponential()")}}Mengembalikan string yang merepresentasikan nomor dalam notasi eksponensial.
{{jsxref("Number.toFixed", "toFixed()")}}Mengembalikan string yang merepresentasikan nomor dalam notasi fixed-point.
{{jsxref("Number.toPrecision", "toPrecision()")}}Mengembalikan string yang merepresentasikan nomor dalam notasi fixed-point yang lebih spesifik.
+ +

Math object

+ +

The built-in {{jsxref("Math")}} objek memiliki properti dan metode-metode untuk konstanta matematika dan fungsi-fungsi. Sebagai contoh, objek matematik PI properti memiliki nilai (3.141...), yang akan anda gunakan dalam aplikasi sebagai

+ +
Math.PI
+
+ +

Demikian pula, fungsi standard matematika merupakan metode-metode Math. termasuk trigonometri, logaritma, eksponensial, dan fungsi lainnya. Sebagai contoh, jika anda ingin menggunakan fungsi trigonometri sin, anda akan menulis

+ +
Math.sin(1.56)
+
+ +

Perhatikan bahwa semua metode trigonometri matematika menggunakan argumen dalam radian.

+ +

Tabel berikut meringkas metode-metode objek matematik.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Methods of Math
MethodDescription
{{jsxref("Math.abs", "abs()")}}Nilai absolut
{{jsxref("Math.sin", "sin()")}}, {{jsxref("Math.cos", "cos()")}}, {{jsxref("Math.tan", "tan()")}}Fungsi trigonometri standar; dengan argumen dalam radian.
{{jsxref("Math.asin", "asin()")}}, {{jsxref("Math.acos", "acos()")}}, {{jsxref("Math.atan", "atan()")}}, {{jsxref("Math.atan2", "atan2()")}}Fungsi trigonometri terbalik; mengembalikan nilai dalam radian.
{{jsxref("Math.sinh", "sinh()")}}, {{jsxref("Math.cosh", "cosh()")}}, {{jsxref("Math.tanh", "tanh()")}}Fungsi hiperbolik. argumen dalam sudut hiperbolik.
{{jsxref("Math.asinh", "asinh()")}}, {{jsxref("Math.acosh", "acosh()")}}, {{jsxref("Math.atanh", "atanh()")}}Fungsi hiperbolik terbalik. mengembalikan nilai dalam sudut hiperbolik.
+

{{jsxref("Math.pow", "pow()")}}, {{jsxref("Math.exp", "exp()")}}, {{jsxref("Math.expm1", "expm1()")}}, {{jsxref("Math.log10", "log10()")}}, {{jsxref("Math.log1p", "log1p()")}}, {{jsxref("Math.log2", "log2()")}}

+
Fungsi eksponen dan logaritma.
{{jsxref("Math.floor", "floor()")}}, {{jsxref("Math.ceil", "ceil()")}}Mengembalikan angka bulat terkecil/terbesar kurang/lebih dari atau sama dengan pada sebuah argumen.
{{jsxref("Math.min", "min()")}}, {{jsxref("Math.max", "max()")}}Mengembalikan nilai minimum/maksimum sebuah koma terpisah dari angka sebagai argumen.
{{jsxref("Math.random", "random()")}}Megembalikan angka acak antara 0 dan 1.
{{jsxref("Math.round", "round()")}}, {{jsxref("Math.fround", "fround()")}}, {{jsxref("Math.trunc", "trunc()")}},Fungsi pembulatan dan pemotongan.
{{jsxref("Math.sqrt", "sqrt()")}}, {{jsxref("Math.cbrt", "cbrt()")}}, {{jsxref("Math.hypot", "hypot()")}}Akar kuadrat, akar pangkat tiga, akar kuadrat dari jumlah argumen persegi.
{{jsxref("Math.sign", "sign()")}}tanda sebuah angka, mengindikasikan angka apapun merupakan angka positif, negatif, atau nol.
{{jsxref("Math.clz32", "clz32()")}},
+ {{jsxref("Math.imul", "imul()")}}
Angka yang dimulai dari nol bit dalam 32-bit.
+ Hasil dari C-like 32-bit perkalian dari dua argumen.
+ +

Tidak seperti beberapa objek lainnya, anda tidak perlu membuat objek matematika sendiri. anda selalu menggunakan built-in Math object.

+ +

Date object

+ +

JavaScript does not have a date data type. However, you can use the {{jsxref("Date")}} object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.

+ +

JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00, with a Unix Timestamp being the number of seconds since January 1, 1970, 00:00:00.

+ +

The Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.

+ +

To create a Date object:

+ +
var dateObjectName = new Date([parameters]);
+
+ +

where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object.

+ +

Calling Date without the new keyword returns a string representing the current date and time.

+ +

The parameters in the preceding syntax can be any of the following:

+ + + +

Methods of the Date object

+ +

The Date object methods for handling dates and times fall into these broad categories:

+ + + +

With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a getDay method that returns the day of the week, but no corresponding setDay method, because the day of the week is set automatically. These methods use integers to represent these values as follows:

+ + + +

For example, suppose you define the following date:

+ +
var Xmas95 = new Date('December 25, 1995');
+
+ +

Then Xmas95.getMonth() returns 11, and Xmas95.getFullYear() returns 1995.

+ +

The getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since January 1, 1970, 00:00:00 for a Date object.

+ +

For example, the following code displays the number of days left in the current year:

+ +
var today = new Date();
+var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month
+endYear.setFullYear(today.getFullYear()); // Set year to this year
+var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
+var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
+var daysLeft = Math.round(daysLeft); //returns days left in the year
+
+ +

This example creates a Date object named today that contains today's date. It then creates a Date object named endYear and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today and endYear, using getTime and rounding to a whole number of days.

+ +

The parse method is useful for assigning values from date strings to existing Date objects. For example, the following code uses parse and setTime to assign a date value to the IPOdate object:

+ +
var IPOdate = new Date();
+IPOdate.setTime(Date.parse('Aug 9, 1995'));
+
+ +

Example

+ +

In the following example, the function JSClock() returns the time in the format of a digital clock.

+ +
function JSClock() {
+  var time = new Date();
+  var hour = time.getHours();
+  var minute = time.getMinutes();
+  var second = time.getSeconds();
+  var temp = '' + ((hour > 12) ? hour - 12 : hour);
+  if (hour == 0)
+    temp = '12';
+  temp += ((minute < 10) ? ':0' : ':') + minute;
+  temp += ((second < 10) ? ':0' : ':') + second;
+  temp += (hour >= 12) ? ' P.M.' : ' A.M.';
+  return temp;
+}
+
+ +

The JSClock function first creates a new Date object called time; since no arguments are given, time is created with the current date and time. Then calls to the getHours, getMinutes, and getSeconds methods assign the value of the current hour, minute, and second to hour, minute, and second.

+ +

The next four statements build a string value based on the time. The first statement creates a variable temp, assigning it a value using a conditional expression; if hour is greater than 12, (hour - 12), otherwise simply hour, unless hour is 0, in which case it becomes 12.

+ +

The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way.

+ +

Finally, a conditional expression appends "P.M." to temp if hour is 12 or greater; otherwise, it appends "A.M." to temp.

+ +

{{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}

diff --git a/files/id/web/javascript/panduan/pengenalan/index.html b/files/id/web/javascript/panduan/pengenalan/index.html new file mode 100644 index 0000000000..19523a0821 --- /dev/null +++ b/files/id/web/javascript/panduan/pengenalan/index.html @@ -0,0 +1,156 @@ +--- +title: Perkenalan +slug: Web/JavaScript/Panduan/pengenalan +tags: + - 'I10n:priority' + - JavaScript + - Pedoman + - Pemula + - Perkenalan +translation_of: Web/JavaScript/Guide/Introduction +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
+ +

Bab ini mengenalkan dan membahas konsep yang mendasar di javascript.

+ +

Apa yang perlu anda ketahui

+ +

Pada pedoman ini kami anggap Anda memiliki pengetahuan dasar dari:

+ + + +

Tempat untuk mencari informasi JavaScript 

+ +

Dokumentasi JavaScript di MDN menyediakan materi sebagai berikut:

+ + + +

Jika Anda baru mengenal JavaScript, mulailah dari area belajar dan Paduan JavaScript. Ketika Anda sudah mendapatkan pemahaman dasarnya, Anda bisa menggunakan Referensi JavaScript untuk melihat lebih detil objek dan statement.

+ +

Apa itu JavaScript?

+ +

JavaScript adalah bahasa scripting cross-platform yang berorientasi objek yang digunakan untuk membuat bagian interaktif dari halaman-halaman web (misal: animasi kompleks, tombol yang dapat di-klik, menu pop-up, dll). Terdapat juga versi server-side yang lebih lanjut dari JavaScript seperti Node.Js yang mana dapat memberikan Anda fungsionalitas lebih pada sebuah website (seperti kolaborasi realtime di antara beberapa komputer). Di dalam host environment (contoh, sebuah web browser), JavaScript dapat dihubungkan ke objek-objek dari environment tersebut untuk menyediakan kendali programmatis terhadapnya. 

+ +

JavaScript memuat satu library standar yang memuat objek-objek, seperti Array, Date, dan Math, juga set inti dari elemen-elemen bahasa ini seperti operator, struktur kontrol, dan statement. Inti dari JavaScript dapat dikembangkan untuk kegunaan yang beragam dengan cara menambahkan  objek-objek tambahan; sebagai contoh:

+ + + +

JavaScript dan Java

+ +

JavaScript dan Java memang memiliki kemiripan pada beberapa hal, namun pada dasarnya saling berbeda. JavaScript menyerupai Java namum tidak memiliki static typing dan strong type checking. JavaScript mengikuti sebagian besar expresi syntax Java, konvensi penamaan serta konstruksi control-flow dasar, yang mana menjadi alasan untuk mengganti namanya dari LiveScript ke JavaScript.

+ +

Berbeda dengan sistem compile-time class Java yang dibangun melalui deklarasi, Javascript mendukung sistem runtime yang berbasis pada sebagian kecil tipe data yang mewakili nilai numerik, Boolean, dan string. Javascript memiliki model objek berbasis prototipe ketimbang model objek berbasis kelas yang lebih umum. Model berbasis prototipe menyediakan inheritance dinamis; yaitu, apa yang diturunkan/diwariskan dapat berbeda pada setiap objek. Javascript juga mendukung fungsi tanpa persyaratan deklaratif khusus. Fungsi bisa berupa properti objek, yang dijalankan sebagai tipe metode yang longgar.

+ +

JavaScript merupakan bahasa dengan bentuk yang sangat bebas dibandingkan dengan Java. Anda tidak perlu mendeklarasikan semua variabel, kelas, dan metode. Anda tidak perlu khawatir apakah metode itu public, private, atau protected, dan Anda juga tidak perlu mengimplementasikan interface. Variabel, parameter, dan tipe kembalian fungsi juga tidak ditulis secara eksplisit.

+ +

Java merupakan bahasa berbasis kelas yang didesain untuk eksekusi yang cepat dan penulisan yang aman. Penulisan yang aman, misalnya, Anda tidak bisa mengubah integer Java menjadi referensi objek atau mengakses private memori dengan membobol bytecode. Model berbasis kelas Java bermaksud bahwa program secara eksklusif terdiri atas sejumlah kelas beserta metode-metodenya. Pewarisan kelas dan penulisan ketat milik Java umumnya membutuhkan hirarki objek yang juga sangat kekat. Syarat-syarat tersebut menjadikan pemrograman Java lebih kompleks ketimbang pemrograman Javascript.

+ +

Sebaliknya, JavaScript mewarisi inti dari baris bahasa yang bertipe dinamis dan lebih sederhana sepeti HyperTalk dan dBASE. Bahasa-bahasa scripting tersebut menawarkan fungsionalitas pemrograman ke pengguna yang lebih luas karena syntax-nya yang lebih mudah, berfokus pada fungsi built-in, dan persyaratan yang minimalis untuk membuat objek.

+ + + + + + + + + + + + + + + + + + + + + + + +
JavaScript dibandingkan Java
JavaScriptJava
Berorientasi objek. Tak ada perbedaan antar tipe objek. Inheritance/ pewarisan melalui mekanisme prototipe, serta properti dan metode bisa ditambahkan kepada objek apapun secara dinamis.Berbasis kelas. Objek dibagi ke dalam kelas dan instansi dengan semua pewarisan melalui hirarki kelas. Kelas dan instansi tidak dapat memiliki properti atau metode yang ditambahkan secara dinamis.
Tipe data variabel tidak dideklarasi (dynamic typing, loosely typed).Tipe data variabel harus dideklarasi (static-typing, strongly typed).
Tidak bisa menulis ke hard disk secara otomatis.Bisa menulis ke hard disk secara otomatis.
+ +

Untuk informasi lebih lanjut perbedaan antara JavaScript dan Java, lihat bagian Detil dari model objek.

+ +

JavaScript dan spesifikasi ECMAScript

+ +

Javascript distandarisasi melalui Ecma International — asosiasi Eropa yang men-standarisasi sistem informasi dan komunikasi  (ECMA merupakan singkatan yang dari European Computer Manufacturers Association) yang mengurusi standarisasi bahasa pemrograman internasional berbasis JavaScript. Versi standarisasi JavaScript ini, yang disebut sebagai ECMAScript, akan berperilaku sama pada setiap aplikasi yang mengikutinya. Perusahaan-perusahaan dapat menggunakan bahasa standar terbuka untuk mengembangkan implementasi JavaScript mereka. Standar ECMAScript didokumentasikan dalam spesifikasi ECMA-262. Kunjungi Terbaru di JavaScript untuk mempelajari lebih lanjut tentang berbagai versi dari JavaScript dan spesifikasi edisi ECMAScript.

+ +

Standar ECMA-262 juga disetujui oleh ISO (International Organization for Standardization) sebagai ISO-16262. Anda juga dapat menemukan spesifikasinya di website Ecma International. Spesifikasi ECMAScript tidak memaparkan Document Object Model yang distandarisasi oleh World Wide Web Consortium (W3C) bersama WHATWG (Web Hypertext Application Technology Working Group). DOM mendefinisikan cara dimana dokumen objek HTML diekspos ke script Anda. Untuk mendapatkan pemahaman yang lebih baik tentang berbagai teknologi yang digunakan ketika memrogram menggunakan JavaScript, lihat artikel ikhtisar teknologi JavaScript.

+ +

Perbandingan dokumentasi JavaScript dengan spesifikasi ECMAScript

+ +

Spesifikasi ECMAScript adalah seperangkat persyaratan untuk menerapkan ECMAScript; berguna jika Anda ingin menerapkan fitur bahasa yang sesuai standar dalam penerapan atau mesin ECMAScript Anda (seperti SpiderMonkey di Firefox, atau V8 di Chrome).

+ +

Dokumen ECMAScript tidak dimaksudkan untuk membantu script programmer; gunakanlah dokumentasi JavaScript untuk informasi dalam penulisan script.

+ +

Spesifikasi ECMAScript menggunakan terminologi dan syntax yang mungkin asing bagi programmer JavaScript. Meskpun deskripsi dari bahasa tersebut dapat berbeda dengan ECMAScript, bahasanya sendiri tetap sama. JavaScript mendukung semua fungsionalitas yang diuraikan dalam spesifikasi ECMAScript.

+ +

Dokumentasi JavaScript menggambarkan aspek bahasa yang sesuai bagi seorang programmer JavaScript.

+ +

Memulai Javascript

+ +

Memulai JavaScript itu mudah: semua yang dibutuhkan hanyalah Web browser modern untuk menjalankannya. Panduan ini mencakup beberapa fitur JavaScript yang hanya tersedia pada versi terakhir Firefox, sehingga disarankan untuk menggunakan Firefox versi terbaru.

+ +

Terdapat dua alat yang dipasang ke dalam Firefox yang berguna dalam bereksperimen dengan JavaScript: Web Console dan Scratchpad.

+ +

Web Console

+ +

Web Consol / Konsol Web memperlihatkan kepada Anda tentang informasi laman Web yang sedang di-load saat ini, dan juga mencakup commandline / baris perintah yang dapat Anda gunakan untuk mengeksekusi ekspresi JavaScript pada laman saat ini.

+ +

Untuk membuka Konsol Web, tekan (Ctrl + Shift + K) pada Windows dan Linux atau tekan (Cmd + Option + K) pada Mac, pilih "Web Console" dari menu "Developer", yang berada di bawah menu "Tools" di Firefox. Konsol akan muncul di bagian bawah jendela browser. Di bagian bawah konsol tersebut adalah command line yang dapat Anda gunakan untuk memasukkan JavaScript, dan outputnya akan muncul pada panel di atasnya.

+ +

Konsol tersebut bekerja persis seperti eval: expresi terakhir yang dienter akan dikembalikan. Demi kesederhanaan, bisa dibayangkan jika setiap saat sesuatu dimasukkan ke dalam konsol, ia akan selalu dikelilingi oleh console.log sekitar eval seperti ini.

+ +
function greetMe(yourName) {
+  alert('Hello ' + yourName);
+}
+console.log(eval('3 + 5'));
+ +

 

+ +

Scratchpad

+ +

Konsol Web bagus untuk menjalankan satu baris kode JavaScript, meskipun Anda juga dapat menjalankan banyak baris, tetap saja akan terasa kurang nyaman, dan Anda juga tidak bisa menyimpan sampel kode Anda menggunakan Konsol Web. Jadi untuk contoh yang lebih kompleks, Scratchpad adalah solusinya.

+ +

Untuk membuka Scratchpad tekan (Shift + F4), pilih "Scratchpad" dari menu "Developer", yang ada di bawah menu pada Firefox. Selanjutnya akan muncul di window yang terpisah dan merupakan editor yang dapat Anda gunakan untuk menulis dan menjalankan JavaScript di browser. Anda juga dapat menyimpan dan membuka kode dari disk.

+ +

+ +

Hello world

+ +

Untuk mulai menulis JavaScript, buka Scratchpad dan tulislah kode JavaScript "Hello world" pertama Anda:

+ +
(function(){
+  "use strict";
+  /* Start of your code */
+  function greetMe(yourName) {
+    alert('Hello ' + yourName);
+  }
+
+  greetMe('World');
+  /* End of your code */
+})();
+
+ +

Pilih kode diatas dan tekan Ctrl+R untuk melihatnya berjalan di browser Anda! Di laman-laman berikutnya, panduan ini akan memperkenalkan Anda dengan syntax dan fitur-fitur bahasa JavaScript, sehingga Anda dapat menulis aplikasi yang lebih kompleks. Tapi untuk saat ini, ingatlah untuk selalu memasukkan (function(){"use strict"; sebelum kode Anda, dan tambahkan  })(); di akhir kode Anda. Anda akan mempelajari apa artinya itu, tetapi untuk sekarang mereka bisa dianggap melakukan:

+ +
    +
  1. Meningkatkan performa secara masif
  2. +
  3. Mencegah semantik ceroboh dalam JavaScript yang menjatuhkan pemula
  4. +
  5. Mencegah code snippets yang dieksekusi dalam konsol untuk berinteraksi satu sama lain (misalnya sesuatu yang dibuat dalam suatu eksekusi konsol digunakan untuk eksekusi konsol yang lain).
  6. +
+ +

{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}

diff --git a/files/id/web/javascript/panduan/tentang/index.html b/files/id/web/javascript/panduan/tentang/index.html new file mode 100644 index 0000000000..98b5e2c2b0 --- /dev/null +++ b/files/id/web/javascript/panduan/tentang/index.html @@ -0,0 +1,144 @@ +--- +title: Tentang Panduan Ini +slug: Web/JavaScript/Panduan/Tentang +tags: + - JavaScript + - Panduan + - dasar +translation_of: Web/JavaScript/Guide/Introduction +--- +

JavaScript adalah bahasa yang cross-platform yaitu berarti JavaScript dapat dijalankan di banyak platform seperti Linux, Windows, Mac OS, Android, Firefox OS dan lain - lain. Panduan ini akan memberikan segala pengetahuan dasar yang perlu anda ketahui dalam penggunaan JavaScript.

+ +

Fitur baru pada versi JavaScript

+ +

 

+ + + +

 

+ +

Apa yang perlu anda pelajari terlebih dahulu ?

+ +

Sebelum mempelajari panduan ini anda harus mempunyai pengetahuan dasar tentang:

+ + + +

JavaScript versions

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 1 JavaScript and Navigator versions
JavaScript versionNavigator version
JavaScript 1.0Navigator 2.0
JavaScript 1.1Navigator 3.0
JavaScript 1.2Navigator 4.0-4.05
JavaScript 1.3Navigator 4.06-4.7x
JavaScript 1.4 
JavaScript 1.5Navigator 6.0
+ Mozilla (open source browser)
JavaScript 1.6Firefox 1.5, other Mozilla 1.8-based products
JavaScript 1.7Firefox 2, other Mozilla 1.8.1-based products
JavaScript 1.8Firefox 3, other Gecko 1.9-based products
+ +

Dimana saya mendapatkan informasi tentang JavaScript ?

+ +

Dokumentasi JavaScript terdapat pada buku dibawah ini:

+ + + +

Untuk yang baru belajar bacalah JavaScript Guide. Atau anda ingin mendapat pemahaman yang kuat bacalah JavaScript Reference untuk mendapatkan detail dari masing - masing object dan statements.

+ +

Tips untuk belajar JavaScript

+ +

Untuk memulai belajar JavaScript sangatlah mudah, anda hanya butuh web browser versi terbaru seperti Mozilla Firefox. Karena di dalam panduan ini terdapat beberapa fitur JavaScript yang hanya bisa dijalankan pada web browser firefox versi terbaru (dan web browser lain yang didukung Gecko), jadi kami menyarankan anda selalu update Mozilla Firefox terbaru.

+ +

Ada dua tool yang tersedia di dalam Firefox dan sangat berguna untuk berEksperimen dengan JavaScript yaitu Web Console dan Scratchpad.

+ +

Web Console

+ +

Web Console memberikan anda informasi tentang halaman web yang sedang anda buka, dan juga terdapat command line yang membuat anda bisa menjalankan JavaScript expression di web page yang sedang anda buka.

+ +

Untuk menggunakan Web Console, pilih "Web Console" dari menu "Web Developer" yang terdapat di dalam menu "Tools" atau "Peralatan" dalam bahasa indonesia. Web Console akan muncul pada bagian bawah browser dan anda bisa menjalankan Script anda pada Text Input dan hasilnya akan muncul pada box seperti gambar dibawah ini.

+ +

+ +

Scratchpad

+ +

Web Console biasa digunakan untuk single lines Script, ketika anda ingin mencoba Script multiple lines kami sarankan menggunakan Scratchpad, karena selain tidak efective juga Web Console tidak bisa menyimpan perubahan yang anda lakukan pada Script, namun Scratchpad melakukan itu dengan sangat baik.

+ +

Untuk menggunakan Scratchpad, pilih "Scratchpad" pada menu "Web Developer" di dalam menu "Tools" atau "Pengaturan" dalam bahasa indonesia. Anda dapat menyimpan dan menload Script dari dari hardisk ataupun flashdisk.

+ +

Ketika anda mengklik tombol "Inspect" maka script anda akan tereksekusi dan hasilnya akan dikembalikan pada Script dalam bentuk komentar.

+ +

+ +

Document conventions

+ +

Applikasi JavaScript berjalan di banyak Operating System (OS) dan informasi pada panduan ini adalah untuk semua versi OS. File dan lokasi Folder pada Unix dan Windows dipisahkan oleh backslashes (/)

+ +

Panduan ini menggunakan uniform resource locators (URLs) of the following form:

+ +

http://server.domain/path/file.html

+ +

In these URLs, server represents the name of the server on which you run your application, such as research1 or www; domain represents your Internet domain name, such as netscape.com or uiuc.edu; path represents the directory structure on the server; and file.html represents an individual file name. In general, items in italics in URLs are placeholders and items in normal monospace font are literals. If your server has Secure Sockets Layer (SSL) enabled, you would use https instead of http in the URL.

+ +

This guide uses the following font conventions:

+ + + +
 
diff --git a/files/id/web/javascript/panduan/values,_variables,_and_literals/index.html b/files/id/web/javascript/panduan/values,_variables,_and_literals/index.html new file mode 100644 index 0000000000..41900a1603 --- /dev/null +++ b/files/id/web/javascript/panduan/values,_variables,_and_literals/index.html @@ -0,0 +1,648 @@ +--- +title: Tata Bahasa dan Tipe +slug: 'Web/JavaScript/Panduan/Values,_variables,_and_literals' +tags: + - JavaScript + - Panduan +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
+ +

Pada bagian ini membahas tata bahasa dasar Javascript, deklarasi variabel, tipe data dan literal.

+ +

Dasar

+ +

Sebagian besar sintak JavaScript terinspirasi dari Java, namun juga dipengaruhi oleh Awk, Perl dan Python.

+ +

JavaScript bersifat case-sensitive dan menggunakan set karakter Unicode.

+ +

Dalam JavaScript, instruksi disebut {{Glossary ("Statement", "pernyataan")}} dan dipisahkan oleh titik koma (;). Spasi, tab dan karakter baris baru disebut whitespace.Teks sumber skrip JavaScript dipindai dari kiri ke kanan dan diubah menjadi urutan elemen masukan yang merupakan token, karakter kontrol, terminator baris, komentar atau whitespace. ECMAScript juga mendefinisikan kata kunci dan literal tertentu dan memiliki aturan untuk penyisipan titik koma secara otomatis (ASI) untuk mengakhiri pernyataan. Namun, dianjurkan untuk selalu menambahkan titik koma untuk mengakhiri pernyataan anda; Itu akan terhindar dari efek samping. Untuk informasi lebih lanjut, lihat referensi rinci tentang tata bahasa eksikal JavaScript.

+ +


+ Komentar

+ +

Sintak komentar pada JavaScript sama dengan C++ dan dalam banyak bahasa pemrograman lainnya:

+ +
// komentar satu baris
+
+/* Ini lebih panjang
+   komentar beberapa baris
+ */
+
+/* Anda tidak bisa menggunakannya, /* komentar bersarang */ Sintak bermasalah */
+ +

Deklarasi

+ +

Ada tiga macam deklarasi pada JavaScript.

+ +
+
var
+
Mendeklarasikan sebuah variabel, opsional menginisialisasi sebuah nilai.
+
let
+
Mendeklarasikan lingkup-blok, variabel lokal, opsional menginisialisasi sebuah nilai.
+
const
+
Mendeklarasikan sebuah lingkup-blok, baca-saja dinamakan konstanta.
+
+ +

Variabel

+ +

Anda menggunakan variabel sebagai nama simbolik dalam aplikasi Anda.  Nama variabel, disebut {{Glossary("Identifier", "Pengidentifikasi")}}, sesuai dengan peraturan tertentu.

+ +

Pengindetifikasi pada JavaScript harus dimulai dengan huruf, garis bawah (_), atau tanda dolar ($); Karakter selanjutnya bisa berupa digit (0-9). karena JavaScript sensitif huruf (case-sensitive), Huruf termasuk karakter "A" sampai "Z" (huruf besar) dan huruf "a" sampai "z" (huruf kecil) .

+ +

Anda dapat menggunakan sebagian besar huruf ISO 8859-1 atau Unicode seperti å dan ü dalam pengidentifikasi (untuk lebih jelasnya lihat postingan blog ini). Anda juga dapat menggunakan urutan rangkaian pelolosan/escape Unicode sebagai karakter dalam pengidentifikasi.

+ +

Beberapa contoh nama legal adalah Number_hitstemp99, $credit, dan _name.

+ +

Mendeklarasikan variabel

+ +

Anda bisa mendeklarasikan sebuah variabel dalam tiga cara:

+ + + +

Mengevaluasi variabel

+ +

Variabel yang dideklarasikan dengan menggunakan pernyataan  var atau let tanpa penetapan nilai yang ditentukan memiliki nilai undefined.

+ +

Upaya untuk mengakses variabel yang tidak dideklarasikan akan menuju kepada pelemparan eksepsi ReferenceError:

+ +
var a;
+console.log('Nilai dari a adalah ' + a); // Nilai dari a adalah undefined
+
+console.log('Nilai dari b adalah ' + b); // Nilai dari b adalah undefined
+var b;
+
+console.log('Nilai dari c adalah ' + c); // Tidak tertangkap ReferenceError: c tidak di definisikan
+
+let x;
+console.log('Nilai dari x adalah ' + x); // Nilai dari x adalah undefined
+
+console.log('Nilai dari y adalah ' + y); // Tidak tertangkap ReferenceError: y tidak di definisikan
+let y;
+ +

Anda dapat menggunakan undefined untuk menentukan apakah sebuah variabel memiliki nilai. Dalam kode berikut, variabel input tidak diberi nilai, dan pernyataan  if dievaluasi true.

+ +
var input;
+if (input === undefined) {
+  lakukanIni();
+} else {
+  lakukanItu();
+}
+ +

Nilai  undefined berperilaku sebagai false bila digunakan dalam konteks boolean. Misalnya, kode berikut menjalankan fungsi fungsiSaya karena elemen  myArray undefined:

+ +
var myArray = [];
+if (!myArray[0]) fungsiSaya();
+ +

Nilai  undefined mengkonversi ke NaN bila digunakan dalam konteks numerik.

+ +
var a;
+a + 2;  // Dievaluasi ke NaN
+ +

Ketika Anda mengevaluasi sebuah variabel null, nilai null berperilaku seperti 0 dalam konteks numerik dan sebagai false dalam konteks boolean. Sebagai contoh:

+ +
var n = null;
+console.log(n * 32); // Akan log 0 ke konsol
+ +

Lingkup variabel

+ +

Bila Anda mendeklarasikan variabel di luar fungsi apa pun, ini disebut variabel global , karena tersedia pada kode lain dalam dokumen tersebut. Ketika Anda mendeklarasikan sebuah variabel dalam suatu fungsi, itu disebut variabel lokal , karena hanya tersedia di dalam fungsi itu.

+ +

JavaScript sebelum ECMAScript 2015 tidak memiliki lingkup pernyataan blok ; Sebaliknya, variabel yang dinyatakan dalam blok bersifat lokal terhadap fungsi (atau lingkup global) yang berada di blok. Misalnya kode berikut akan log 5, karena ruang lingkupnya adalah fungsi (atau konteks global) yang dideklarasikan, bukan bloknya, yang dalam hal ini adalah sebuah pernyataan if.

+ +
if (true) {
+  var x = 5;
+}
+console.log(x);  // x is 5
+ +

Perilaku ini berubah, saat menggunakan deklarasi let yang diperkenalkan di ECMAScript 2015.

+ +
if (true) {
+  let y = 5;
+}
+console.log(y);  // ReferenceError: y tidak di definisikan
+ +

Hoisting variabel

+ +

Hal lain yang tidak biasa tentang variabel dalam JavaScript adalah Anda bisa merujuk ke variabel yang dideklarasikan nanti, tanpa mendapatkan eksepsi. Konsep ini dikenal sebagai hoistingVariabel dalam JavaScript dalam arti "dikibarkan" atau diangkat ke atas fungsi atau pernyataan. Bagaimanapun, variabel yang dikibarkan akan memberikan nilai undefinedJadi, bahkan jika Anda mendeklarasikan dan menginisialisasi setelah Anda menggunakan atau merujuk ke variabel ini, itu akan tetap memberikan undefined.

+ +
/**
+ * Contoh 1
+ */
+console.log(x === undefined); // true
+var x = 3;
+
+/**
+ * Contoh 2
+ */
+// Akan memberikan nilai undefined
+var myvar = 'my value';
+
+(function() {
+  console.log(myvar); // undefined
+  var myvar = 'local value';
+})();
+ +

Contoh di atas akan dinterprestasikan sama dengan:

+ +
/**
+ * Contoh 1
+ */
+var x;
+console.log(x === undefined); // true
+x = 3;
+
+/**
+ * Example 2
+ */
+var myvar = 'my value';
+
+(function() {
+  var myvar;
+  console.log(myvar); // undefined
+  myvar = 'nilai lokal';
+})();
+ +

Karena hoisting, semua pernyataan var dalam suatu fungsi harus ditempatkan sedekat mungkin ke atas fungsi. Praktik terbaik ini meningkatkan kejelasan kode.

+ +

Dalam ECMAScript 2015, variabel  let (const) tidak akan hoist ke bagian atas blok. Bagaimanapun, referensi variabel di blok sebelum deklarasi variabel menghasilkan sebuah ReferenceErrorVariabel ini berada dalam "zona mati temporal" dari awal blok sampai deklarasi diproses.

+ +
console.log(x); // ReferenceError
+let x = 3;
+ +

Hoisting fungsi

+ +

Untuk fungsi, hanya deklarasi fungsi yang diangkat ke atas dan bukan ekspresi fungsi.

+ +
/* Deklarasi fungsi */
+
+foo(); // "bar"
+
+function foo() {
+  console.log('bar');
+}
+
+
+/* Ekspresi fungsi */
+
+baz(); // TypeError: baz adalah bukan fungsi
+
+var baz = function() {
+  console.log('bar2');
+};
+ +

Variabel global

+ +

Variabel global sebenarnya adalah properti dari objek global . Di halaman web objek global itu window, sehingga Anda bisa mengatur dan mengakses variabel global dengan menggunakan sintaks window.variable

+ +

Akibatnya, Anda dapat mengakses variabel global yang dideklarasikan dalam satu window atau frame dari window atau frame lain dengan menentukan nama window atau frame. Misalnya, jika variabel yang disebut phoneNumber dinyatakan dalam dokumen, Anda dapat merujuk variabel ini dari iframe as parent.phoneNumber.

+ +

Konstanta

+ +

Anda bisa membuat variabel baca-saja, dinamai dengan kata kunci constSintaksis dari pengenal konstanta sama dengan pengenal variabel: ia harus dimulai dengan huruf, garis bawah atau tanda dolar ($) dan dapat berisi karakter abjad, numerik, atau garis bawah.

+ +
const PI = 3.14;
+ +

Konstanta tidak dapat mengubah nilai melalui penugasan atau dinyatakan ulang saat naskah dijalankan. Ini harus diinisialisasi ke sebuah nilai.

+ +

Aturan lingkup untuk konstanta sama dengan variabel lingkup-blok let . Jika kata kunci  const dihilangkan, pengenal dianggap mewakili variabel.

+ +

Anda tidak dapat mendeklarasikan konstanta dengan nama yang sama dengan fungsi atau variabel dalam lingkup yang sama. Sebagai contoh:

+ +
// INI AKAN MENYEBABKAN ERROR
+function f() {};
+const f = 5;
+
+// INI AKAN MENYEBABKAN ERROR JUGA
+function f() {
+  const g = 5;
+  var g;
+
+  //pernyataan
+}
+ +

Namun, properti objek yang ditugaskan pada konstanta tidak terlindungi, jadi pernyataan berikut dijalankan tanpa masalah.

+ +
const MY_OBJECT = {'key': 'value'};
+MY_OBJECT.key = 'otherValue';
+ +

Struktur dan tipe data

+ +

Tipe data

+ +

Standar ECMAScript terbaru mendefinisikan tujuh tipe data:

+ + + +

Meskipun tipe data ini jumlahnya relatif kecil, namun memungkinkan Anda untuk melakukan fungsi-fungsi yang berguna dengan aplikasi Anda.  {{jsxref("Object", "Objects")}} dan {{jsxref("Function", "functions")}} merupakan unsur fundamental lainnya dalam bahasa ini. Anda bisa memikirkan objek sebagai wadah bernama untuk nilai, dan fungsi sebagai prosedur yang dapat dilakukan aplikasi Anda.

+ +

Konversi tipe data

+ +

JavaScript adalah bahasa yang diketik secara dinamis. Itu berarti Anda tidak perlu menentukan tipe data variabel saat Anda menyatakannya, dan tipe data akan dikonversi secara otomatis sesuai kebutuhan selama eksekusi skrip. Jadi, misalnya, Anda bisa mendefinisikan variabel sebagai berikut:

+ +
var jawaban = 42;
+ +

Dan nanti, Anda bisa menetapkan variabel yang sama dengan nilai string, misalnya:

+ +
jawaban = 'Thanks for all the fish...';
+ +

Karena JavaScript diketik secara dinamis, penugasan ini tidak menyebabkan pesan kesalahan.

+ +

Dalam ekspresi yang melibatkan nilai numerik dan string dengan operator +, JavaScript mengubah nilai numerik menjadi string. Misalnya, perhatikan pernyataan berikut:

+ +
x = 'Jawabannya adalah ' + 42 // "Jawabannya adalah 42"
+y = 42 + ' Adalah jawabannya' // "42 Adalah jawabannya"
+ +

Dalam pernyataan yang melibatkan operator lain, JavaScript tidak mengubah nilai numerik menjadi string. Sebagai contoh:

+ +
'37' - 7 // 30
+'37' + 7 // "377"
+ +

Mengubah string menjadi angka

+ +

Dalam kasus yang sebuah nilai mewakili bilangan ada dalam memori sebagai string, ada metode untuk konversi.

+ + + +

parseInt Hanya akan memberikan bilangan bulat, jadi penggunaannya berkurang untuk desimal. Selain itu, praktik terbaik untuk parseInt selalu menyertakan parameter radix. Parameter radix digunakan untuk menentukan sistem numerik yang akan digunakan.

+ +

Metode alternatif untuk mengambil nomor dari string adalah dengan operator +  (unary plus):

+ +
'1.1' + '1.1' = '1.11.1'
+(+'1.1') + (+'1.1') = 2.2
+// Catatan: kurung siku buka tutup ditambahkan untuk kejelasan, tidak diminta.
+ +

Literal

+ +

Anda menggunakan literal untuk mewakili nilai dalam JavaScript. Ini adalah nilai tetap, bukan variabel, yang Anda berikan secara literal dalam skrip Anda. Bagian ini menjelaskan jenis literal berikut:

+ + + +

Literal array

+ +

Sebuah literal array adalah daftar dari nol atau lebih ekspresi,  yang masing-masing mewakili elemen array, dilampirkan dalam tanda kurung siku ([]). Bila Anda membuat array menggunakan literal array, ini diinisialisasi dengan nilai yang ditentukan sebagai elemennya, dan panjangnya diatur ke jumlah argumen yang ditentukan.

+ +

Contoh berikut membuat array coffees dengan tiga elemen dan panjang tiga:

+ +
var coffees = ['French Roast', 'Colombian', 'Kona'];
+ +

Catatan: Sebuah literal array  adalah tipe dari object initializer. Lihat Menggunakan Penginisialisasi Objek.

+ +

Jika sebuah array dibuat menggunakan literal dalam skrip tingkat-atas, JavaScript menginterpretasikan array setiap kali mengevaluasi ekspresi yang berisi literal array. Selain itu, literal yang digunakan dalam suatu fungsi dibuat setiap kali fungsi dipanggil.

+ +

Array literal juga objek ArrayLihat Array dan Koleksi diIndek untuk rincian tentang objek Array.

+ +

Ekstra koma dalam literal array

+ +

Anda tidak perlu menentukan semua elemen dalam literal array. Jika Anda memasukkan dua koma berturut-turut, array dibuat undefined untuk elemen yang tidak ditentukan. Contoh berikut membuat array fish:

+ +
var fish = ['Lion', , 'Angel'];
+ +

Array ini memiliki dua elemen dengan nilai dan satu elemen kosong (fish[0] adalah "Lion", fish[1] adalah undefined, dan fish[2] merupakan "Angel").

+ +

Jika Anda menyertakan koma di akhir daftar elemen, koma diabaikan. Pada contoh berikut, panjang array adalah tiga. Tidak ada myList[3]Semua koma lainnya dalam daftar menunjukkan elemen baru.

+ +

Catatan: Koma diakhir dapat membuat kesalahan pada versi browser lama dan merupakan praktik terbaik untuk menghapusnya.

+ +
var myList = ['home', , 'school', ];
+ +

Dalam contoh berikut, panjang array adalah empat, dan myList[0]dan myList[2] hilang.

+ +
var myList = [ ,'home', , 'school'];
+ +

Dalam contoh berikut, panjang array adalah empat, dan myList[1]dan myList[3] hilang. Hanya koma terakhir yang diabaikan.

+ +
var myList = ['home', , 'school', , ];
+ +

Memahami perilaku ekstra  koma penting untuk memahami JavaScript sebagai bahasa, namun saat menulis kode Anda sendiri: secara eksplisit menyatakan elemen yang hilang sebagai undefined akan meningkatkan kejelasan dan perawatan kode anda.

+ +

Literal boolean

+ +

Tipe Boolean memiliki dua nilai literal: true dan false.

+ +

Jangan membingungkan nilai Boolean primitif true dan false dengan nilai true dan false objek Boolean. Objek Boolean adalah pembungkus di sekitar tipe data Boolean primitif. Lihat {{jsxref("Boolean")}} untuk informasi lebih lanjut.

+ +

Integer

+ +

Integer dapat dinyatakan dalam desimal (basis 10), heksadesimal (basis 16), oktal (basis 8) dan biner (basis 2).

+ + + +

Beberapa contoh literal bilangan bulat adalah:

+ +
0, 117 and -345 (desimal, basis 10)
+015, 0001 and -0o77 (oktal, basis 8)
+0x1123, 0x00111 and -0xF1A7 (heksadesimal, "hex" or basis 16)
+0b11, 0b0011 and -0b11 (biner, basis 2)
+ +

Untuk informasi lebih lanjut, lihat literatur numerik dalam referensi tata bahasa leksikal .

+ +

Literal floating-point

+ +

Sebuah literal  floating-point dapat memiliki bagian berikut:

+ + + +

Bagian eksponennya adalah "e" atau "E" diikuti oleh bilangan bulat, yang dapat ditandatangani (didahului dengan "+" atau "-"). Literal floating-point harus memiliki setidaknya satu digit dan titik desimal atau "e" (atau "E").

+ +

Lebih ringkas lagi, sintaksnya adalah:

+ +
[(+|-)][angka][.angka][(E|e)[(+|-)]angka]
+ +

Sebagai contoh:

+ +
3.1415926
+-.123456789
+-3.1E+12
+.1e-23
+ +

Literal objek

+ +

Literal objek adalah daftar dari nol atau lebih pasangan nama properti dan nilai objek yang terkait, yang dilampirkan dalam kurung kurawal ({}). Anda seharusnya tidak menggunakan literal objek di awal sebuah pernyataan. Ini akan menyebabkan kesalahan atau tidak berperilaku seperti yang Anda harapkan, karena { akan ditafsirkan sebagai awal dari sebuah blok.

+ +

Berikut ini adalah contoh dari literal objek. Elemen pertama dari objek car mendefinisikan sebuah properti myCar, dan menetapkan sebuah string baru, " Saturn";  Elemen kedua, properti getCar,  segera diberi hasil pemanggilan function (carTypes("Honda")); elemen ketiga, properti special menggunakan variabel yang ada ( sales).

+ +
var sales = 'Toyota';
+
+function carTypes(name) {
+  if (name === 'Honda') {
+    return name;
+  } else {
+    return "Maaf, kami tidak menjual " + name + ".";
+  }
+}
+
+var car = { myCar: 'Saturn', getCar: carTypes('Honda'), special: sales };
+
+console.log(car.myCar);   // Saturn
+console.log(car.getCar);  // Honda
+console.log(car.special); // Toyota
+ +

Selain itu, Anda dapat menggunakan literal numerik atau string untuk nama properti atau menyarangkan objek di dalam objek yang lain. Contoh berikut menggunakan opsi ini.

+ +
var car = { manyCars: {a: 'Saab', 'b': 'Jeep'}, 7: 'Mazda' };
+
+console.log(car.manyCars.b); // Jeep
+console.log(car[7]); // Mazda
+ +

Nama properti objek bisa berupa string apapun, termasuk string kosong. Jika nama properti akan menjadi {{Glossary("Identifier","pengidentifikasi")}} JavaScript yang tidak valid atau angka, maka harus dilampirkan dalam tanda petik. Nama properti yang pengidentifikasi tidak valid juga tidak dapat diakses sebagai properti dot (.), namun dapat diakses dan ditetapkan dengan notasi seperti array ("[]").

+ +
var namaPropertiTidakBiasa = {
+  '': 'An empty string',
+  '!': 'Bang!'
+}
+console.log(namaPropertiTidakBiasa.'');   // SyntaxError: Unexpected string
+console.log(namaPropertiTidakBiasa['']);  // An empty string
+console.log(namaPropertiTidakBiasa.!);    // SyntaxError: Unexpected token !
+console.log(namaPropertiTidakBiasa['!']); // Bang!
+ +

Peningkatan Literal Objek

+ +

Di ES2015, literal objek diperluas untuk mendukung pengaturan prototipe pada konstruksi, singkatan untuk  foo: penugasan foo , definisikan metode, pembuatan panggilan super, dan komputasi nama properti dengan ekspresi. Bersamaan dengan itu, ini juga membawa literatur dan deklarasi kelas lebih dekat bersama, dan membiarkan desain berbasis objek mendapatkan keuntungan dari beberapa kemudahan yang sama.

+ +
var obj = {
+    // __proto__
+    __proto__: theProtoObj,
+    // Shorthand for ‘handler: penangan’
+    handler,
+    // Metode
+    toString() {
+     // Pangilan super
+     return 'd ' + super.toString();
+    },
+    // Dikalkulasi (dinamis) nama properti
+    [ 'prop_' + (() => 42)() ]: 42
+};
+ +

Tolong dicatat:

+ +
var foo = {a: 'alpha', 2: 'two'};
+console.log(foo.a);    // alpha
+console.log(foo[2]);   // two
+//console.log(foo.2);  // Error: missing ) after argument list
+//console.log(foo[a]); // Error: a is not defined
+console.log(foo['a']); // alpha
+console.log(foo['2']); // two
+ +

Literal RegExp

+ +

Sebuah literal regex adalah pola yang dilampirkan diantara garis miring. Berikut ini adalah contoh literal regex.

+ +
var re = /ab+c/;
+ +

Literal string

+ +

Literal string adalah nol atau lebih karakter yang dilampirkan dengan tanda kutip ganda (") atau tunggal ('). String harus dibatasi dengan tanda kutip dari jenis yang sama; Yaitu kedua tanda kutip tunggal atau kedua tanda petik ganda. Berikut ini adalah contoh literal string:

+ +
'foo'
+"bar"
+'1234'
+'baris satu \n baris lainnya'
+"Kucing jhon"
+ +

Anda dapat memanggil salah satu metode objek String pada nilai literal string-JavaScript secara otomatis mengubah literal string menjadi objek String sementara, memanggil metode tersebut, lalu membuang objek String sementara. Anda juga bisa menggunakan properti String.length dengan literal string:

+ +
console.log("Kucing jhon".length)
+// Akan mencetak jumlah simbol dalam string termasuk spasi.
+// Dalam hal ini, 11.
+ +

Di ES2015, template literal juga tersedia. Template string memberikan sintaksis gula untuk pembuatan string. Ini mirip dengan fitur interpolasi string di Perl, Python dan lainnya. Secara opsional, tag dapat ditambahkan untuk memungkinkan konstruksi string disesuaikan, menghindari serangan injeksi atau membangun struktur data tingkat tinggi dari konten string.

+ +
// Literal dasar kreasi string
+`Dalam JavaScript '\n' adalah sebuah line-feed.`
+
+// String beberapa baris
+`Dalam template string JavaScript dapat berjalan di
+ beberapa baris, namun string yang dikutip ganda dan tunggal
+ tidak dapat dilakukan.`
+
+// Interpoasi string
+var name = 'Bob', time = 'today';
+`Hello ${name}, how are you ${time}?`
+
+// Membangun prefix permintaan HTTP digunakan untuk menafsirkan penggantian dan konstruksi
+POST`http://foo.org/bar?a=${a}&b=${b}
+     Content-Type: application/json
+     X-Credentials: ${credentials}
+     { "foo": ${foo},
+       "bar": ${bar}}`(myOnReadyStateChangeHandler);
+ +

Anda harus menggunakan literal string kecuali Anda secara khusus perlu menggunakan objek String. Lihat {{jsxref("String")}}  untuk rincian tentang objek String.

+ +

Menggunakan karakter khusus dalam string

+ +

Selain karakter biasa, Anda juga bisa menyertakan karakter khusus dalam string, seperti yang ditunjukkan pada contoh berikut.

+ +
'one line \n another line'
+ +

Tabel berikut mencantumkan karakter khusus yang dapat Anda gunakan dalam string JavaScript.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Tabel: karakter khusus JavaScript
KarakterBerarti
\0Null Byte
\bbackspase
\fform feed
\nBaris baru
\rCariage return
\tTab
\vTab vertikal
\'Apostrof atau kutipan tunggal
\"Kutipan ganda
\\Karakter backslash
\XXXKarakter dengan pengkodean Latin-1 ditentukan oleh hingga tiga digit oktal XXX antara 0 dan 377. Misalnya, \251 adalah urutan oktal untuk simbol hak cipta.
\xXXKarakter dengan pengkodean Latin-1 yang ditentukan oleh dua digit heksadesimal XX antara 00 dan FF. Misalnya, \xA9 adalah urutan heksadesimal untuk simbol hak cipta.
\uXXXXKarakter Unicode ditentukan oleh empat digit heksadesimal XXXX . Misalnya, \u00A9 adalah urutan Unicode untuk simbol hak cipta. Lihat rangkaian pelolosan Unicode.
\u{XXXXX}Kode Unicode lolos. Misalnya, \u {2F804} sama dengan Unicode sederhana yang lolos \uD87E \uDC04.
+ +

Karakter pelolosan

+ +

Untuk karakter yang tidak tercantum dalam tabel, tanda garis miring terbalik sebelumnya diabaikan, namun penggunaan ini tidak berlaku lagi dan harus dihindari.

+ +

Anda dapat memasukkan tanda petik di dalam string sebelum mendahului dengan garis miring terbalik. Ini dikenal sebagai pelolosan dari tanda petik. Sebagai contoh:

+ +
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
+console.log(quote);
+ +

Hasil dari ini adalah:

+ +
He read "The Cremation of Sam McGee" by R.W. Service.
+ +

Untuk menyertakan garis miring terbalik di dalam string, Anda harus melepaskan diri dari karakter garis miring terbalik. Misalnya, untuk menetapkan path file c:\temp ke string, gunakan yang berikut ini:

+ +
var home = 'c:\\temp';
+ +

Anda juga bisa meloloskan dari baris istirahat sebelumnya mendahului mereka dengan garis miring terbalik. Garis miring terbalik dan baris istirahat keduanya terlepas dari nilai string.

+ +
var str = 'this string \
+is broken \
+across multiple \
+lines.'
+console.log(str);   // this string is broken across multiplelines.
+ +

Meskipun JavaScript tidak memiliki sintaks "heredoc", Anda bisa mendekat dengan menambahkan pelolosan baris istirahat dan baris istirahat pada akhir setiap baris:

+ +
var poem =
+'Roses are red,\n\
+Violets are blue.\n\
+Sugar is sweet,\n\
+and so is foo.'
+ +

ECMAScript 2015 memperkenalkan tipe literal baru, yaitu  template literal . Hal ini memungkinkan banyak fitur baru termasuk string beberapa baris!

+ +

 

+ +
var poem =
+`Roses are red,
+Violets are blue.
+Sugar is sweet,
+and so is foo.`
+ +

 

+ +

Informasi lebih lanjut

+ +

Bab ini berfokus pada sintaks dasar untuk deklarasi dan tipe. Untuk mempelajari lebih lanjut tentang konstruksi bahasa JavaScript, lihat juga bab-bab berikut dalam panduan ini:

+ + + +

Pada bab berikutnya, kita akan melihat konstruksi aliran kontrol dan penanganan kesalahan.

diff --git a/files/id/web/javascript/panduan/working_with_objects/index.html b/files/id/web/javascript/panduan/working_with_objects/index.html new file mode 100644 index 0000000000..4449732e61 --- /dev/null +++ b/files/id/web/javascript/panduan/working_with_objects/index.html @@ -0,0 +1,492 @@ +--- +title: Bekerja dengan objek +slug: Web/JavaScript/Panduan/Working_with_Objects +tags: + - 'I10n:priority' + - JavaScript + - Konstruktor + - Membandingkan objek + - Objek + - Panduan + - Pemula + - dokumen +translation_of: Web/JavaScript/Guide/Working_with_Objects +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}
+ +

JavaScript dirancang berdasarkan paradigma berbasis objek sederhana. Objek adalah kumpulan dari properti, dan properti adalah sepasang hubungan antara nama (atau kunci) dan nilai. Nilai properti bisa berupa fungsi, Dalam hal ini properti itu disebut metode. Selain objek yang sudah di tentukan pada peramban, Kamu bisa menentukan objekmu sendiri. Bab ini menjelaskan cara memakai objek, properti, fungsi, dan metode, serta bagaimana cara membuat objekmu sendiri.

+ +

Ikhtisar objek

+ +

Objek di JavaScript sama seperti kebanyakan bahasa pemrograman lainnya, bisa dibandingkan dengan objek dalam kehidupan nyata. Konsep objek dalam JavaScript dapat dipahami dengan kehidupan nyata, objek nyata.

+ +

Di JavaScript, objek adalah entitas yang mandiri dengan properti dan tipe. Bandingkan dengan cangkir, misalnya. Sebuah cangkir adalah objek dengan banyak properti. Cangkir punya warna, desain, berat, materi bahan, dll. Dengan cara sama, objek JavaScript juga punya banyak properti yang menjelaskan karakteristiknya.

+ +

Objek dan properti

+ +

Objek JavaScript punya banyak properti yang terkait dengannya. Properti dari objek dapat didefinisikan sebagai variabel yang dilampirkan pada objek itu. Properti dari objek pada dasarnya sama dengan variabel JavaScript biasa, kecuali lampiran pada objek. Properti objek menentukan karakteristik objek itu. Kamu mengakses properti objek dengan sebuah notasi titik sederhana:

+ +
objectName.propertyName
+
+ +

Seperti semua variabel JavaScript, baik nama objek (bisa jadi variabel normal) maupun nama properti peka terhadap besar huruf. Kamu bisa mendefinisi properti dengan mengassign nilai. Contohnya, ayo buat objek bernama myCar dan dan berikan dia properti bernama make, model, dan year sebagai berikut:

+ +
var myCar = new Object();
+myCar.make = 'Ford';
+myCar.model = 'Mustang';
+myCar.year = 1969;
+
+ +

Nilai properti objek yang tidak diassign adalah {{jsxref("undefined")}} (dan bukan {{jsxref("null")}}).

+ +
myCar.color; // undefined
+ +

Properti dari objek JavaScript juga bisa diakses atau diset menggunakan notasi kurung siku (untuk lebih detil lihat aksesor properti). Terkadang objek disebut associative array, karena tiap properti dikaitkan dengan nilai string yang bisa digunakan untuk mengaksesnya. Jadi, contohnya, kamu bisa mengakses properti dari objek myCar seperti berikut:

+ +
myCar['make'] = 'Ford';
+myCar['model'] = 'Mustang';
+myCar['year'] = 1969;
+
+ +

Nama properti objek bisa berupa string dari JavaScript yang valid, atau apapun yang dapat diubah menjadi string, termasuk string kosong. Namun, nama properti apapun yang tidak valid sebagai identitas di JavaScript (contohnya, nama properti yang memiliki spasi atau tanda hubung, atau yang dimulai dengan angka) hanya bisa diakses menggunakan notasi kurung siku. Notasi ini juga sangat berguna ketika nama properti harus ditentukan secara dinamis (ketika nama properti belum ditentukan hingga runtime). Contohnya sebagai berikut:

+ +
// empat variabel dibuat dan diberi nilai sekali jalan,
+// dipisahkan oleh koma
+var myObj = new Object(),
+    str = 'myString',
+    rand = Math.random(),
+    obj = new Object();
+
+myObj.type              = 'Syntax titik';
+myObj['date created']   = 'String dengan spasi';
+myObj[str]              = 'Nilai string';
+myObj[rand]             = 'Angka Random';
+myObj[obj]              = 'Objek';
+myObj['']               = 'Bahkan string kosong';
+
+console.log(myObj);
+
+ +

Tolong dicatat bahwa semua kunci di dalam notasi kurung siku diubah ke dalam tipe String, karena objek JavaScript hanya bisa punya tipe String sebagai tipe kunci. Contohnya, dalam kode di atas, ketika kunci  obj ditambahkan dalam myObj, JavaScript akan memanggil method obj.toString() , dan menggunakan hasil string ini sebagai kunci baru.

+ +

Kamu juga bisa mengakses properti menggunakan nilai string yang disimpan dalam variabel:

+ +
var propertyName = 'make';
+myCar[propertyName] = 'Ford';
+
+propertyName = 'model';
+myCar[propertyName] = 'Mustang';
+ +

Kamu bisa menggunakan notasi kurung siku dengan for...in untuk mengiterasi ulang semua kumpulan properti yang terdaftar dari sebuah objek. Untuk mengilustrasikan cara kerjanya, fungsi berikut ini menampilkan properti dari objek ketika kamu memasukkan objek dan nama objek sebagai argumen pada fungsi:

+ +
function showProps(obj, objName) {
+  var result = '';
+  for (var i in obj) {
+    // obj.hasOwnProperty() digunakan untuk menyaring properti dari rantai prototipe objek
+    if (obj.hasOwnProperty(i)) {
+      result += objName + '.' + i + ' = ' + obj[i] + '\n';
+    }
+  }
+  return result;
+}
+
+ +

Jadi memanggil fungsi showProps(mobilKu, "mobilKu") akan mengembalikan:

+ +
myCar.make = Ford
+myCar.model = Mustang
+myCar.year = 1969
+ +

Mengenumerasi properti dari objek

+ +

Mulai ECMAScript 5, ada tiga cara asli untuk mendaftarkan/melintasi properti objek:

+ + + +

Sebelum ECMAScript 5, tidak ada cara asli untuk mendaftarkan semua properti-properti dari suatu objek. Namun, ini dapat dicapai dengan fungsi berikut:

+ +
function listAllProperties(o) {
+	var objectToInspect;
+	var result = [];
+
+	for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)) {
+      result = result.concat(Object.getOwnPropertyNames(objectToInspect));
+	}
+
+	return result;
+}
+
+ +

Ini dapat berguna untuk memperlihatkan properti-properti  tersembunyi" (properti-properti dalam rantai prototip yang tidak dapat diakses melalui objek, karena properti lain memiliki nama yang sama di rantai prototip sebelumnya). Mendaftarkan properti-properti yang dapat diakses hanya dapat dilakukan dengan menghapus duplikat di dalam array.

+ +

Membuat objek baru

+ +

JavaScript mempunyai sejumlah objek yang telah ditetapkan. Selain itu, kamu dapat membuat objek sendiri. Kamu bisa membuat sebuah objek menngunakan sebuah object initializer. Sebagai alternatif, kamu bisa membuat sebuah fungsi konstruktor lalu menginstanisasi sebuah pemanggilan objek bersama dengan operator new.

+ +

Menggunakan object initializer

+ +

Selain membuat objek menggunakan fungsi konstruktor, kamu bisa membuat objek memakai object initializer. Kadang pemakaian object initializer disamakan dengan pembuatan objek dengan notasi literal. "Object initializer" sama dengan terminologi dalam C++.

+ +

Syntax untuk objek yang menggunakan object initializer ialah:

+ +
var obj = { property_1:   value_1,   // property_# bisa berupa identifier...
+            2:            value_2,   // atau angka...
+            // ...,
+            'property n': value_n }; // atau string
+
+ +

Di mana obj adalah nama objek baru, setiap property_i adalah identifier (baik nama, angka, atau string literal), dan setiap value_i adalah expresi yang nilainya diassign ke property_i.  obj dan assignment adalah opsional, jika kamu tidak butuh rujukan ke objek ini, kamu tak usah mengassign dia ke variabel. (Ingat bahwa kamu harus membungkus literal objek dalam tanda kurung jika objeknya muncul dalam statement diharapkan, supaya bisa membedakan mana literal dan mana statement blok.)

+ +

Object initializer adalah expresi, dan setiap object initializer mengembalikan objek baru. Objek baru dibuat saat ia muncul dalam statement yang dieksekusi. Object initializer yang identik membuat objek berbeda yang tidak akan sama bila dibandingkan. Objek dibuat seolah-olah ada panggilan new Object(); yaitu, objek yang dibuat dari expresi literal objek adalah instance dari Object.

+ +

Statement berikut membuat objek dan mengassign dia ke variabel x jika dan hanya jika expresi cond benar:

+ +
if (cond) var x = {greeting: 'hi there'};
+
+ +

Contoh berikut membuat myHonda dengan tiga properti. Ingat bahwa properti engine juga adalah objek yang punya properti sendiri.

+ +
var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}};
+
+ +

Kamu juga bisa menggunakan object initializer untuk membuat array. Lihat literal array.

+ +

Menggunakan fungsi konstruktor

+ +

Kamu bisa membuat objek dengan dua langkah alternatif ini:

+ +
    +
  1. Definisikan tipe objek dengan menulis fungsi konstruktor. Ada konvensi dengan alasan bagus untuk menggunakan huruf kapital inisial.
  2. +
  3. Membuat instance objek dengan new.
  4. +
+ +

Untuk mendefinisi tipe objek, buat fungsi untuk tipe objek tersebut yang menspesifikasi nama, properti, dan metodenya. Misalnya, kamu ingin membuat tipe objek untuk mobil. Kamu ingin jenis objek ini disebut Car, dan kamu ingin punya properti pembuat, model, dan tahun. Untuk melakukan ini, kamu akan menulis fungsi berikut:

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+ +

Perhatikan penggunaan this untuk mengassign nilai ke properti objek berdasarkan nilai yang diteruskan kepada fungsi.

+ +

Sekarang kamu bisa membuat objek myCar sebagai berikut:

+ +
var mycar = new Car('Eagle', 'Talon TSi', 1993);
+ +

Statement ini membuat myCar dan mengassign ia nilai spesifik untuk propertinya. Lalu nilai dari myCar.make ialah string "Eagle", myCar.year ialah integer 1993, dan seterusnya.

+ +

Kamu bisa membuat sejumlah objek Car dengan memanggil new. Sebagai contoh.

+ +
var kenscar = new Car('Nissan', '300ZX', 1992);
+var vpgscar = new Car('Mazda', 'Miata', 1990);
+ +

Objek bisa punya properti yang merupakan objek lain. Misalnya, kamu mendefinisi objek person sebagai berikut:

+ +
function Person(name, age, sex) {
+  this.name = name;
+  this.age = age;
+  this.sex = sex;
+}
+ +

dan kemudian menginstantiasi dua objek person baru sebagai berikut:

+ +
var rand = new Person('Rand McKinnon', 33, 'M');
+var ken = new Person('Ken Jones', 39, 'M');
+ +

Kemudian, kamu bisa menulis ulang definisi Car untuk memasukkan properti owner yang mengambil objek person sebagai berikut:

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+}
+ +

Untuk menginstantiasi objek baru, gunakan ini:

+ +
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
+var car2 = new Car('Nissan', '300ZX', 1992, ken);
+ +

Perhatikan bahwa ketimbang meneruskan nilai string atau integer literal ketika membuat objek baru, statement diatas meneruskan objek rand dan ken sebagai argumen untuk pemilik. Lalu jika kamu mau mencari nama pemilik car2, kamu bisa mengakses properti berikut:

+ +
car2.owner.name
+
+ +

Ingat bahwa kamu selalu bisa menambah properti ke objek yang sudah dibuat sebelumnya. Contohnya statement

+ +
car1.color = 'black';
+
+ +

menambah properti color pada car1, dan mengassign nilai "black". Ini tak mempengaruhi objek lain. Untuk menambah properti baru ke semua objek dari tipe yang sama, kamu harus menambah properti pada definisi tipe objek Car.

+ +

Menggunakan metode Object.create

+ +

Objek bisa juga dibuat menggunakan metode {{jsxref("Object.create()")}}. Metode ini bisa sangat berguna, karena ia memungkinkan kamu memilih prototipe objek untuk objek yang mau kamu buat, tanpa harus mendefinisi fungsi konstruktor.

+ +
// Enkapsulasi metode dan properti Animal
+var Animal = {
+  type: 'Invertebrates', // Nilai properti default
+  displayType: function() {  // Method which will display type of Animal
+    console.log(this.type);
+  }
+};
+
+// Create new animal type called animal1 
+var animal1 = Object.create(Animal);
+animal1.displayType(); // Output:Invertebrates
+
+// Create new animal type called Fishes
+var fish = Object.create(Animal);
+fish.type = 'Fishes';
+fish.displayType(); // Output:Fishes
+ +

Warisan

+ +

Semua objek di javascript diwariskan setidaknya dari satu objek lain. Objek yang diwariskan disebut prototipe, dan properti warisan bisa ditemukan dalam objek prototype dari konstruktor. Lihat Rantai warisan dan prototype untuk informasi lebih lanjut.

+ +

Mengindex properti objek

+ +

Kamu dapat merujuk ke properti dari objek menggunakan nama propertinya ataupun index urutannya. Jika kamu awalnya mendefinisi properti memakai namanya, kamu harus selalu merujuknya dengan namanya, dan jika kamu awalnya mendefinisikan properti memakai index, kamu harus selalu merujuknya dengan indexnya.

+ +

Pembatasan ini berlaku ketika kamu membuat objek dan propertinya dengan fungsi konstruktor (seperti yang kita lakukan sebelumnya dengan jenis objek Car) dan ketika kamu mendefinisi properti individual secara explisit (misalnya, myCar.color = "ref"). Jika kamu awalnya mendefinisi properti objek dengan index, seperti myCar[5] = "25 mpg", maka kamu merujuk ke properti tersebut dengan myCar[5].

+ +

Pengecualian dalam aturan ini adalah objek mirip-array pantulan dari HTML, seperti objek mirip-array forms. Kamu selalu dapat merujuk ke objek dalam objek mirip-array ini menggunakan nomor urutan mereka (berdasarkan di mana mereka muncul dalam dokumen) atau nama mereka (jika didefinisi). Misalnya, jika tag <FORM> kedua dalam dokumen punya atribut NAME "myForm", kamu dapat merujuk ke form tersebut sebagai document.forms[1] atau document.forms["myForm"] atau document.forms.myForm.

+ +

Mendefinisi properti untuk tipe objek

+ +

Kamu dapat menambah properti ke tipe objek yang didefinisi sebelumnya menggunakan properti prototype. Ini mendefinisi properti yang dibagikan semua objek dari tipe yang dispesifikasi, bukan cuma satu instance objek. Kode berikut menambahkan sebuah properti color ke semua objek dari tipe objek Car, dan kemudian mengassign nilai ke properti color dari objek car1.

+ +
Car.prototype.color = null;
+car1.color = 'black';
+ +

Lihat properti prototipe dari objek Function dalam referensi JavaScript untuk informasi lebih lanjut.

+ +

Mendefiniskan metode

+ +

Metode ialah fungsi yang terasosiasi dengan objek, atau sederhananya, metode ialah properti dari objek berupa fungsi. Metode didefinisi sebagai cara fungsi nornal didefinisi, kecuali mereka harus diassign sebagai properti objek. Lihat juga definisi metode untuk lebih detil. Contohnya:

+ +
objectName.methodname = functionName;
+
+var myObj = {
+  myMethod: function(params) {
+    // ...do something
+  }
+
+  // OR THIS WORKS TOO
+
+  myOtherMethod(params) {
+    // ...do something else
+  }
+};
+
+ +

Di mana objectName adalah metode yang sudah ada, methodname ialah nama yang kamu assign ke metode, dan functionName adalah nama fungsi.

+ +

Lalu kamu bisa memanggil metode dalam kontex objek sebagai berikut:

+ +
object.methodname(params);
+
+ +

Kamu bisa mendefinisi metode untuk tipe objek dengan memasukkan sebuah definisi metode dalam fungsi konstruktor objek. Kamu bisa mendefinisi fungsi yang akan memformat dan menampilkan properti objek Car sebelumnya; contohnya,

+ +
function displayCar() {
+  var result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
+  pretty_print(result);
+}
+ +

Di mana pretty_print adalah fungsi untuk menampilkan garis horizontal dan string. Perhatikan penggunaan this untuk merujuk ke objek yang punya metode tersebut.

+ +

Kamu bisa menjadikan fungsi ini metode Car dengan menambah statement

+ +
this.displayCar = displayCar;
+ +

ke definisi objek. Jadi definisi penuh dari Car sekarang akan terlihat seperti

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+  this.displayCar = displayCar;
+}
+ +

Maka kamu bisa memanggil metode displayCar untuk masing-masig objek sebagai berikut:

+ +
car1.displayCar();
+car2.displayCar();
+ +

Menggunakan this untuk referensi Objek

+ +

JavaScript punya katakunci spesial this, kamu bisa memakainya dalam metode untuk merujuk ke objek saat ini. Misalnya, kamu punya fungsi yang disebut validate yang memvalidasi properti value, yang diberikan objek dan nilai atas dan bawah:

+ +
function validate(obj, lowval, hival) {
+  if ((obj.value < lowval) || (obj.value > hival)) {
+    alert('Invalid Value!');
+  }
+}
+
+ +

Kemudian kamu bisa panggil validate di penangan event onchange setiap elemen form, gunakan this untuk meneruskan elemen. Seperti contoh berikut:

+ +
<input type="text" name="age" size="3"
+  onChange="validate(this, 18, 99)">
+
+ +

Secara umum, this merujuk ke pemanggilan objek dalam metode.

+ +

Ketika dikombinasikan dengan properti form, this bisa mengacu ke induk objek form saat ini. Dalam contoh berikut, form myForm berisi objek Text dan sebuah tombol. Ketika pengguna mengklik tombol, nilai objek Text diset ke nama form tersebut. Penangan event onclick tombol menggunakan this.form untuk merujuk ke induk form, myForm.

+ +
<form name="myForm">
+<p><label>Form name:<input type="text" name="text1" value="Beluga"></label>
+<p><input name="button1" type="button" value="Show Form Name"
+     onclick="this.form.text1.value = this.form.name">
+</p>
+</form>
+ +

Mendefinisikan getter dan setter

+ +

Getter ialah metode yang mendapat nilai dari properti spesifik. Setter ialah metode yang mengatur nilai properti spesifik. Kamu bisa mendefinisi getter dan setter objek inti apapun yang sudah ditetapkan atau objek yang ditetapkan pengguna yang mendukung penambahan peroperti-properti baru. Syntax untuk mendefinisi getter dan setter menggunakan syntax literal objek.

+ +

Berikut ilustrasi cara getter dan setter bisa bekerja untuk objek o yang sudah didefinisi user.

+ +
var o = {
+  a: 7,
+  get b() {
+    return this.a + 1;
+  },
+  set c(x) {
+    this.a = x / 2;
+  }
+};
+
+console.log(o.a); // 7
+console.log(o.b); // 8
+o.c = 50;
+console.log(o.a); // 25
+
+ +

Properti objek o adalah:

+ + + +

Harap diingat bahwa nama fungsi dari getter dan setter yang didefisini dalam literal objek menggunakan "[gs]et property()" (dibandingkan dengan __define[GS]etter__ ) bukanlah nama getter mereka sendiri, meski syntax [gs]et propertyName(){ } membuatmu berpikir lain. Untuk menamai fungsi dalam getter atau setter menggunakan syntax "[gs]et property()", definiskan fungsi, dengan nama explisit, secara terprogram menggunakan Object.defineProperty (atau pengganti legacy Object.prototype.__defineGetter__).

+ +

Kode berikut mengilustrasikan cara getter dan setter bisa memperluas prototipe {{jsxref("Date")}} untuk menambah properti year ke semua instance dari kelas Date yang sudah didefinisi. Ia menggunakan metode kelas Date yang sudah ada, getFullYear dan setFullYear untuk mendukung properti getter dan setter year.

+ +

Statement ini mendefinisi getter dan setter untuk properti tahun:

+ +
var d = Date.prototype;
+Object.defineProperty(d, 'year', {
+  get: function() { return this.getFullYear(); },
+  set: function(y) { this.setFullYear(y); }
+});
+
+ +

Statement ini menggunakan getter dan setter dalam objek Date:

+ +
var now = new Date();
+console.log(now.year); // 2000
+now.year = 2001; // 987617605170
+console.log(now);
+// Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001
+
+ +

Secara pinsip, getter dan setter bisa

+ + + +

Ketika mendefiniisi getter dan setter menggunakan object initializer yang harus kamu lakukan adalah memprefix metode getter dengan get dan metode setter dengan set. Tentunya, metode getter tidak boleh mengharapkan parameter, lalu metode setter mengharapkan hanya satu parameter (nilai baru untuk diset). Contohnya:

+ +
var o = {
+  a: 7,
+  get b() { return this.a + 1; },
+  set c(x) { this.a = x / 2; }
+};
+
+ +

Getter dan setter juga bisa ditambah ke objek kapanpun setelah membuat objek menggunakan metode Object.defineProperties. Parameter pertama metode ini ialah object tempat kamu mendefinisi getter atau setter. Parameter kedua ialah objek yang nama propertinya berupa nama getter atau setter,dan yang nilai propertinya berupa objek yang mendefinisi fungsi getter atau setter. Berikut adalah contoh mendefinisi getter dan setter yang sama yang digunakan dalam contoh sebelumnya:

+ +
var o = { a: 0 };
+
+Object.defineProperties(o, {
+    'b': { get: function() { return this.a + 1; } },
+    'c': { set: function(x) { this.a = x / 2; } }
+});
+
+o.c = 10; // Menjalankan setter, yang mengassign 10 / 2 (5) ke properti 'a'
+console.log(o.b); // Menjalankan getter, yang menghasilkan a + 1 atau 6
+
+ +

Yang manapun dari dua form ini yang dipilih tergantung dari gaya pemrograman dan tugas di tangan. Jika kamu sudah memilih object initializer ketika mendefinisi prototipe kamu mungkin akan sering memilih form pertama. Form ini lebih compact dan natural. Namun, kalau kamu harus menambah getter dan setter nanti — karena kamu tak menulis prototipenya atau object khusus — maka form kedua menjadi satu-satunya solusi. Form kedua mungkin paling baik mewakiliki sifat dinamis JavaScript — tapi ia bisa membuat kode sulit dibaca dan dipahami.

+ +

Menghapus properti

+ +

Kamu bisa menghapus properti yang bukan warisan menggunakan operator delete. Kode berikut menampilkan cara menghapus properti.

+ +
// Membuat objek baru, myobj, dengan dua properti, a dan b.
+var myobj = new Object;
+myobj.a = 5;
+myobj.b = 12;
+
+// Mengapus properti a, menyisakan myobj hanya dengan properti b.
+delete myobj.a;
+console.log ('a' in myobj); // menghasilkan "false"
+
+ +

Kamu juga bisa memakai delete untuk menghapus variabel global jika katakunci var tidak dipakai untuk mendeklarasi variabel itu:

+ +
g = 17;
+delete g;
+
+ +

Membandingkan objek

+ +

Dalam JavaScript objek ialah tipe referensi. Dua objek berbeda tak akan pernah sama, meski mereka punya properti yang sama. Hanya membandingkan referensi objek yang sama dengannya menghasilkan true.

+ +
// Dua variabel, dua objek berbeda dengan properti yang sama
+var fruit = {name: 'apple'};
+var fruitbear = {name: 'apple'};
+
+fruit == fruitbear; // mengembalikan false
+fruit === fruitbear; // mengembalikan false
+ +
// Dua variabel, objek tunggal
+var fruit = {name: 'apple'};
+var fruitbear = fruit;  // assign referensi objek buah ke fruitbear
+
+// di sini fruit dan fruitbear menunjuk ke objek yang sama
+fruit == fruitbear; // mengembalikan true
+fruit === fruitbear; // mengembalikan true
+
+ +
fruit.name = 'grape';
+console.log(fruitbear);    // menghasilkan { name: "grape" } ketimbang { name: "apple" }
+
+ +

Untuk informasi lebih tentang operator pembandingan, lihat Operator pembandingan.

+ +

Lihat juga

+ + + +

{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}

diff --git a/files/id/web/javascript/reference/about/index.html b/files/id/web/javascript/reference/about/index.html new file mode 100644 index 0000000000..02c6ef967c --- /dev/null +++ b/files/id/web/javascript/reference/about/index.html @@ -0,0 +1,86 @@ +--- +title: Mengenai Pustaka Ini +slug: Web/JavaScript/Reference/About +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/About +--- +

Apa yang perlu diketahui sebelumnya

+ +

Pengalaman menggunakan bahasa pemrograman lainnya dapat menjadi manfaat, meskipun tidak menjadi prasyarat.

+ +

JavaScript ditujukan untuk digunakan pada lingkup yang lebih besar, seperti peramban, script server-side, atau sejenisnya. Secara umum, pustaka ini tergantung pada platform tertentu, dan tidak ditujukan hanya untuk peramban.

+ +

Untuk tujuan demo, pustakan ini menggunakan fungsi, println. Fungsi tersebut bukanlah bagian dari JavaScript. Namun ia dapat dipetakan terhadap implementasi spesifik pada platform tertentu.

+ +

Misal, bila berjalan di peramban, maka fungsi di atas dapat implementasikan sebagai:

+ +
+
function println(string) {
+  window.alert(string);
+}
+
+ +

 

+
+ +

Sejarah JavaScript

+ +

Versi terbaru dari peramban berbasis Mozilla mendukung versi terbaru dari JavaScript. Tabel berikut menampilkan daftar dari versi JavaScript yang didukung oleh versi yang berbeda dari peramban berbasis Mozilla.

+ +

Peramban yang tidak mendukung versi JavaScript setidaknya versi 1.5 adalah hal yang sangat langka untuk saat ini. JavaScript versi 1.5 sudah dipublikasikan sejak tahun 1999. Bila Anda tertarik untuk mempelajari sejarahnya, silahkan mengunjungi referensi yang terdapat di Wikipedia, ECMAScript.

+ +

JavaScript/Browser support history

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
JavaScript (SpiderMonkey) versionMozilla releaseGecko version
JavaScript 1.5Navigator 6.0, Mozilla Application Suite, Firefox 1.0Gecko 0.6x-1.7
JavaScript 1.6Firefox 1.5Gecko 1.8
JavaScript 1.7Firefox 2Gecko 1.8.1
JavaScript 1.8Firefox 3Gecko 1.9
JavaScript 1.8.5Firefox 4Gecko 2.0
JavaScript 1.8.6Firefox 17Gecko 17
+ +

Sumber informasi JavaScript

+ +

Dokumentasi JavaScript dari fitur bahasa inti (murni ECMAScript, untuk sebagian besar) mencakup:

+ + + +

Bila Anda masih baru terhadap JavaScript, mulailah dari pedoman. Bila kemudian Anda sudah merasa memiliki pemahaman yang lebih mendalam, Anda dapat memanfaatkan referensi.

diff --git a/files/id/web/javascript/reference/classes/constructor/index.html b/files/id/web/javascript/reference/classes/constructor/index.html new file mode 100644 index 0000000000..8da1df9428 --- /dev/null +++ b/files/id/web/javascript/reference/classes/constructor/index.html @@ -0,0 +1,162 @@ +--- +title: constructor +slug: Web/JavaScript/Reference/Classes/constructor +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +
{{jsSidebar("Classes")}}
+ +

Metode dengan nama "constructor" adalah metode spesial untuk pembuatan dan penginisialisasian objek yang dibuat dengan kelas.

+ +

sintaks

+ +
constructor([arguments]) { ... }
+ +

Deskripsi

+ +

Hanya boleh ada satu metode spesial dengan nama "constructor" dalam sebuah kelas. {{jsxref("SyntaxError")}}  akan dilemparkan jika suatu kelas memiliki lebih dari satu metode konstruktor.

+ +

Konstruktor dapat menggunakan kata kunci {{jsxref("Operators/super", "super")}} untuk memanggil konstruktor orang-tua.

+ +

Jika metode konstruktor tidak didefinisikan dalam sebuah kelas, maka  kontruktor asali yang akan digunakan.

+ +

Contoh

+ +

Menggunakan metode constructor

+ +

Potongan kode ini diambil dari contoh kelas (demostrasi langsung).

+ +
class Square extends Polygon {
+  constructor(length) {
+    // Di sini, akan memanggil konstruktor orang-tua dengan panjang
+    // diberikan untuk panjang dan tinggi Polygon
+    super(length, length);
+    // Catatan: di kelas turunan, super() harus dipanggil sebelum
+    // bisa menggunakan kata kunci 'this'. Meninggalkan pemanggilan ini di awal
+    // akan menyebabkan kesalahan referensi.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.area = value;
+  }
+}
+ +

Konstruktor asali

+ +

Jika metode konstruktor tidak didefinisikan dalam sebuah kelas, maka kontruktor asali yang akan digunakan. Untuk konstruktor asali untuk kelas dasar adalah:

+ +
constructor() {}
+
+ +

Konstruktor asali untuk kelas turunan adalah:

+ +
constructor(...args) {
+  super(...args);
+}
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES6')}}Definisi awal
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas Peramban

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Default constructors{{CompatUnknown}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
Default constructors{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Lihat Pula

+ + diff --git a/files/id/web/javascript/reference/classes/extends/index.html b/files/id/web/javascript/reference/classes/extends/index.html new file mode 100644 index 0000000000..c6def454fe --- /dev/null +++ b/files/id/web/javascript/reference/classes/extends/index.html @@ -0,0 +1,112 @@ +--- +title: extends +slug: Web/JavaScript/Reference/Classes/extends +tags: + - ECMAScript 2015 + - JavaScript + - Kelas +translation_of: Web/JavaScript/Reference/Classes/extends +--- +
{{jsSidebar("Classes")}}
+ +

Kata kunci extends digunakan pada class declarations atau class expressions untuk membuat sebuah class yang merupakan turunan dari class lain.

+ +
{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}
+ + + +

Sintaks

+ +
class ChildClass extends ParentClass { ... }
+ +

Deskripsi

+ +

Kata kunci extends dapat digunakan untuk subclass custom classes dan built-in objects.

+ +

.prototype dari suatu ekstensi harus berupa sebuah {{jsxref("Object")}} atau {{jsxref("null")}}.

+ +

Contoh

+ +

Menggunakan extends

+ +

Contoh pertama membuat sebuah class bernama Square dari kelas bernama Polygon. Contoh ini diambil dari live demo (source).

+ +
class Square extends Polygon {
+  constructor(length) {
+    // Disini, obyek dari Square memanggil konstruktor dari parent class dengan argumen lengths yang tersedia
+    // untuk width dan height pada Polygon
+    super(length, length);
+    // Catatan: Pada kelas turunan, super() harus dipanggil sebelum Anda
+    // dapat menggunakan 'this'. Pengabaian terhadap hal tersebut akan menyebabkan reference error.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+}
+ +

Menggunakan extends dengan built-in objects

+ +

Contoh berikut mewarisi built-in {{jsxref("Date")}} object. Contoh ini diambil dari live demo (source).

+ +
class myDate extends Date {
+  constructor() {
+    super();
+  }
+
+  getFormattedDate() {
+    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+    return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
+  }
+}
+ +

Extending (Pewarisan) null

+ +

Extending/pewarisan dari {{jsxref("null")}} bekerja layaknya seperti normal class, dengan pengecualian prototype object tidak mewarisi dari {{jsxref("Object.prototype")}}.

+ +
class nullExtends extends null {
+  constructor() {}
+}
+
+Object.getPrototypeOf(nullExtends); // Function.prototype
+Object.getPrototypeOf(nullExtends.prototype) // null
+
+new nullExtends(); //ReferenceError: this is not defined
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('ES2015', '#sec-class-definitions', 'extends')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas peramban

+ + + +

{{Compat("javascript.classes.extends")}}

+ +

Cek juga

+ + diff --git a/files/id/web/javascript/reference/classes/index.html b/files/id/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..3a8a71f562 --- /dev/null +++ b/files/id/web/javascript/reference/classes/index.html @@ -0,0 +1,383 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +tags: + - Classes + - Constructors + - ECMAScript6 + - Inheritance + - Intermediate + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Classes +--- +
{{JsSidebar("Classes")}}
+ +

Kelas di JavaScript diperkenalkan pada ECMAScript 6 seperti pemanis dari prototype-based JavaScript yang sudah ada. Syntax dari kelas tidak menggunakan model object-oriented inheritance yang baru. JavaScript kelas menyediakan syntax yang lebih sederhana dan rapi untuk membuat object-object dan mengatasi / dealing dengan turunan / inheritance.

+ +

Definisi kelas

+ +

Kelas seperti "fungsi istimewa", dan seperti kamu bisa mendeklarasikan ekspresi fungsi (function expressions) dan deklarasi fungsi (function declarations), syntax kelas sendiri mempunyai dua komponen: ekspresi kelas (class expressions) dan deklarasi kelas (class declarations).

+ +

Deklarasi Kelas

+ +

Salah satu cara untuk mendefinisikan kelas adalah dengan menggunakan class declaration / deklarasi kelas. Untuk mendeklarasikan kelas, kamu bisa menggunakan kata kunci class sebagai contoh class "Polygon" di bawah ini.

+ +
class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

Hoisting

+ +

Perbedaan penting antara deklarasi fungsi (function declarations) dan deklarasi kelas (class declarations) adalah deklarasi fungsi  {{Glossary("Hoisting", "hoisted")}} dan  deklarasi class tidak. Pertama-tama kamu harus mendeklarasikan kelas dan mengaksesnya, jika tidak maka kode seperti berikut akan menampilkan {{jsxref("ReferenceError")}}:

+ +
var p = new Polygon(); // ReferenceError
+
+class Polygon {}
+
+ +

Ekspresi Kelas

+ +

Ekspresi kelas (class expression) adalah cara lain untuk mendefinisikan sebuah class. Class expression bisa bernama ataupun tidak. Nama yang diberikan berbentuk lokal berada di body class.

+ +
// unnamed
+var Polygon = class {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+
+// named
+var Polygon = class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+
+ +

Catatan: Ekspresi kelas (Class expressions) juga mempunyai masalah yang sama terkait hoisting seperti pada Deklarasi kelas (Class declarations).

+ +

Tubuh Kelas (class body) and definisi metode

+ +

Tubuh atau body sebuah kelas berada didalam kurung {}. Disitu kamu dapat mendefinisikan isi kelas seperti method atau konstruktor.

+ +

Strict mode

+ +

Body atau bagian badan dari kelas deklarasi dan kelas ekspresi di eksekusi pada strict mode.

+ +

Konstruktor

+ +

konstruktor adalah metode (method) khusus untuk membuat dan inisialisasi sebuah objek yang dibuat dengan  class. Hanya ada satu metode khusus dengan nama "konstruktor" di kelas. Sebuah {{jsxref("SyntaxError")}} akan tampil jika kelas berisi lebih dari satu method constructor.

+ +

Sebuah konstruktor dapat digunakan keyword super untuk memanggil kostruktor dari kelas parent nya.

+ +

Prototipe method

+ +

Lihat juga definisi method

+ +
class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+
+  get area() {
+    return this.calcArea();
+  }
+
+  calcArea() {
+    return this.height * this.width;
+  }
+}
+
+const square = new Polygon(10, 10);
+
+console.log(square.area);
+ +

Metode Statis

+ +

Kata kunci statis mendefinisikan metode statis untuk suatu kelas. Metode statis dipanggil tanpa membuat instance kelasnya dan tidak bisa dipanggil ketika kelas tersebut dipakai. Metode statis sering digunakan untuk membuat fungsi utilitas untuk suatu aplikasi.

+ +
class Point {
+  constructor(x, y) {
+    this.x = x;
+    this.y = y;
+  }
+
+  static distance(a, b) {
+    const dx = a.x - b.x;
+    const dy = a.y - b.y;
+
+    return Math.sqrt(dx*dx + dy*dy);
+  }
+}
+
+const p1 = new Point(5, 5);
+const p2 = new Point(10, 10);
+
+console.log(Point.distance(p1, p2));
+ +

Mem-binding this dengan prototipe dan metode statis

+ +

Ketika metode statis atau prototipe dipanggil tanpa objek yang bernilai "this" (atau "this" sebagai boolean, string, angka, tidak terdefinisi atau null), maka nilai "this" akan ditentukan dalam fungsi yang digunakan. Autoboxing tidak akan berjalan. Hal tersebut juga berlaku ketika kita menulis kode dalam mode non-strict.laku akan sama bahkan jika kita menulis kode dalam mode tidak ketat.

+ +
class Animal {
+  speak() {
+    return this;
+  }
+  static eat() {
+    return this;
+  }
+}
+
+let obj = new Animal();
+let speak = obj.speak;
+speak(); // undefined
+
+let eat = Animal.eat;
+eat(); // undefined
+ +

Jika kita menulis kode diatas menggunakan fungsi tradisional berdasarkan kelas, maka autoboxing akan berjalan sesuai dengan nilai "this" pada fungsi yang dipanggil.

+ +
function Animal() { }
+
+Animal.prototype.speak = function(){
+  return this;
+}
+
+Animal.eat = function() {
+  return this;
+}
+
+let obj = new Animal();
+let speak = obj.speak;
+speak(); // global object
+
+let eat = Animal.eat;
+eat(); // global object
+
+ +

Sub kelas dengan extends

+ +

extends digunakan pada deklarasi kelas atau kelas expresi untuk membuat suatu kelas sebagai turunan dari kelas lain.

+ +
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(this.name + ' makes a noise.');
+  }
+}
+
+class Dog extends Animal {
+  speak() {
+    console.log(this.name + ' barks.');
+  }
+}
+
+var d = new Dog('Mitzie');
+d.speak();
+
+ +

Jika terdapat constructor pada sub kelas saat ini, maka pertama dibutuhkan untuk memanggil super() sebelum menggunakan "this".

+ +
Seseorang juga dapat mengextend "kelas" berbasis fungsi tradisional:
+ +
function Animal (name) {
+  this.name = name;
+}
+
+Animal.prototype.speak = function () {
+  console.log(this.name + ' makes a noise.');
+}
+
+class Dog extends Animal {
+  speak() {
+    console.log(this.name + ' barks.');
+  }
+}
+
+var d = new Dog('Mitzie');
+d.speak();
+
+ +

Perhatikan bahwa kelas tidak dapat di extend pada objek reguler atau biasa (non-constructible) . Jika ingin mewarisi regurel object,  maka dapat menggunakan {{jsxref("Object.setPrototypeOf()")}}:

+ +
var Animal = {
+  speak() {
+    console.log(this.name + ' makes a noise.');
+  }
+};
+
+class Dog {
+  constructor(name) {
+    this.name = name;
+  }
+  speak() {
+    console.log(this.name + ' barks.');
+  }
+}
+
+Object.setPrototypeOf(Dog.prototype, Animal);
+
+var d = new Dog('Mitzie');
+d.speak();
+
+ +

Species

+ +

Kamu dapat mengembalikan objek {{jsxref("Array")}}  di kelas array yang diturunkan MyArray. Pola spesies memungkinkan Kamu overide konstruktor default.

+ +

Contohnya, ketika menggunakan method seperti {{jsxref("Array.map", "map()")}} yang mana mengembalikan konstruktor default, kamu butuh method yang dapat mengembalikan objek parent Array, bukan dari objek MyArray. Simbol {{jsxref("Symbol.species")}} memungkinkan untuk melakukan:

+ +
class MyArray extends Array {
+  // Overwrite species to the parent Array constructor
+  static get [Symbol.species]() { return Array; }
+}
+
+var a = new MyArray(1,2,3);
+var mapped = a.map(x => x * x);
+
+console.log(mapped instanceof MyArray); // false
+console.log(mapped instanceof Array);   // true
+
+ +

Memanggil Kelas Super dengan keyword super

+ +

Keyword super digunakan untuk memanggil fungsi pada objek parent nya.

+ +
class Cat {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(this.name + ' makes a noise.');
+  }
+}
+
+class Lion extends Cat {
+  speak() {
+    super.speak();
+    console.log(this.name + ' roars.');
+  }
+}
+
+ +

Mix-ins

+ +

Subkelas Abstrak or mix-ins adalah template untuk kelas. Kelas berbasis  ECMAScript hanya dapat memiliki satu superclass (Kelas super), jadi inheritence berganda dari kelas tool sebagai contohnya, itu tidak memungkinkan. Fungsionalitas harus disediakan oleh superclass.

+ +

Sebuah fungsi dengan superclass sebagai inputanya dan sukelas as input and a subclass extend superclass sebagai output dapat mengimplemtasikan pada  ECMAScript sebagai berikut:

+ +
var calculatorMixin = Base => class extends Base {
+  calc() { }
+};
+
+var randomizerMixin = Base => class extends Base {
+  randomize() { }
+};
+
+ +

A class that uses these mix-ins can then be written like this:

+ +
class Foo { }
+class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}}
+ +

Kompatibilitas Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}[1]
+ {{CompatChrome(49.0)}}
{{CompatGeckoDesktop(45)}}13{{CompatNo}}{{CompatNo}}{{CompatSafari(9.0)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}9{{CompatChrome(42.0)}}[1]
+ {{CompatChrome(49.0)}}
+
+ +

[1] Requires strict mode. Non-strict mode support is behind the flag "Enable Experimental JavaScript", disabled by default.

+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html b/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html new file mode 100644 index 0000000000..4fab8e8ca2 --- /dev/null +++ b/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html @@ -0,0 +1,69 @@ +--- +title: X.prototype.y called on incompatible type +slug: Web/JavaScript/Reference/Errors/Called_on_incompatible_type +tags: + - Error + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Called_on_incompatible_type +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
TypeError: 'this' is not a Set object (EdgE)
+TypeError: Function.prototype.toString called on incompatible object (Firefox)
+TypeError: Function.prototype.bind called on incompatible target (Firefox)
+TypeError: Method Set.prototype.add called on incompatible receiver undefined (Chrome)
+TypeError: Bind must be called on a function (Chrome)
+
+ +

Tipe error

+ +

{{jsxref("TypeError")}}

+ +

Apa yang salah?

+ +

Ketika error ini dilempar, suatu fungsi (dari objek yang diberikan), dipanggil dengan this tidak berkorespondensi ke tipe yang diharapkan fungsi tersebut.

+ +

Isu ini bisa terbit ketika menggunakan metode {{jsxref("Function.prototype.call()")}} atau {{jsxref("Function.prototype.apply()")}}, dan menyediakan argumen this yang tak punya tipe yang diharapkan.

+ +

Isu ini juga bisa terjadi ketika menyediakan fungsi yang disimpan sebagai properti suatu objek sebagai argumen fungsi lain. Dalam hal ini, objek yang menyimpan fungsi tersebut takkan menjadi target this target dari fungsi itu ketika dipanggil oleh fungsi lain. Untuk mengatasi isu ini, kamu harus menyediakan lambda yang membuat panggilan, ataupun menggunakan fungsi {{jsxref("Function.prototype.bind()")}} untuk memaksa argumen this ke objek yang diharapkan.

+ +

Contoh

+ +

Kasus tak valid

+ +
var mySet = new Set;
+['bar', 'baz'].forEach(mySet.add);
+// mySet.add adalah fungsi, tapi "mySet" tidak dikaptur sebagai this.
+
+var myFun = function () {
+  console.log(this);
+};
+['bar', 'baz'].forEach(myFun.bind);
+// myFun.bind adalah fungsi, tapi "myFun" tidak dikaptur sebagai this.
+
+
+ +

Kasus valid

+ +
var mySet = new Set;
+['bar', 'baz'].forEach(mySet.add.bind(mySet));
+// Ini berjalan karena mengikat "mySet" sebagai this.
+
+var myFun = function () {
+  console.log(this);
+};
+['bar', 'baz'].forEach(x => myFun.bind(x));
+// Ini berjalan menggunakan fungsi "bind". Ia membuat lambda yang meneruskan argumen.
+
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/errors/index.html b/files/id/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..68e7cce3df --- /dev/null +++ b/files/id/web/javascript/reference/errors/index.html @@ -0,0 +1,12 @@ +--- +title: Referensi error JavaScript +slug: Web/JavaScript/Reference/Errors +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Errors +--- +

{{jsSidebar("Errors")}}

+ +

Error, error dimana - mana.

+ +

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

diff --git a/files/id/web/javascript/reference/errors/invalid_array_length/index.html b/files/id/web/javascript/reference/errors/invalid_array_length/index.html new file mode 100644 index 0000000000..3b7fd4e78e --- /dev/null +++ b/files/id/web/javascript/reference/errors/invalid_array_length/index.html @@ -0,0 +1,78 @@ +--- +title: 'RangeError: invalid array length' +slug: Web/JavaScript/Reference/Errors/Invalid_array_length +tags: + - Errors + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
RangeError: Array length must be a finite positive integer (Edge)
+RangeError: invalid array length (Firefox)
+RangeError: Invalid array length (Chrome)
+RangeError: Invalid array buffer length (Chrome)
+
+ +

Tipe error

+ +

{{jsxref("RangeError")}}

+ +

Apa yang salah?

+ +

Panjang array tak valid bisa muncul di situasi berikut:

+ + + +

Kenapa panjang Array dan ArrayBuffer dibatasi? Properti length dari Array atau ArrayBuffer diwakili dengan satu unsigned 32-bit integer, yang hanya menyimpan nilai dalam kisaran dari 0 hingga 232-1.

+ +

Jika kamu membuat satu Array, menggunakan constructor, kamu mungkin mau memakai notasi literal saja, karena argumen pertama diinterpretasi sebagai panjang Array.

+ +

Sebaliknya, kamu mungkin mau mengelam panjangnya sebelum mengeset properti panjangnya, atau memakainya sebagai argumen konstructor.

+ +

Contoh

+ +

Kasus tak valid

+ +
new Array(Math.pow(2, 40))
+new Array(-1)
+new ArrayBuffer(Math.pow(2, 32))
+new ArrayBuffer(-1)
+
+let a = [];
+a.length = a.length - 1;         // set -1 to the length property
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = b.length + 1;         // set 2^32 to the length property
+
+ +

Kasus valid

+ +
[ Math.pow(2, 40) ]                     // [ 1099511627776 ]
+[ -1 ]                                  // [ -1 ]
+new ArrayBuffer(Math.pow(2, 32) - 1)
+new ArrayBuffer(0)
+
+let a = [];
+a.length = Math.max(0, a.length - 1);
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = Math.min(0xffffffff, b.length + 1);
+
+// 0xffffffff is the hexadecimal notation for 2^32 - 1
+// which can also be written as (-1 >>> 0)
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html new file mode 100644 index 0000000000..32be54e5ce --- /dev/null +++ b/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html @@ -0,0 +1,78 @@ +--- +title: 'SyntaxError: missing ; before statement' +slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +--- +
{{jsSidebar("Errors")}}
+ +

Pesan

+ +
SyntaxError: Expected ';' (Edge)
+SyntaxError: missing ; before statement (Firefox)
+
+ +

Tipe error

+ +

{{jsxref("SyntaxError")}}.

+ +

Apa yang Salah?

+ +

Ada titik koma (;) yang hilang di suatu tempat. JavaScript statements harus diakhiri dengan semicolon. Beberapa dari mereka dipengaruhi oleh automatic semicolon insertion (ASI), tetapi dalam hal ini anda perlu memberikan titik koma, sehingga JavaScript dapat mem-parse kode sumber dengan benar.

+ +

Namun, seringkali, kesalahan ini hanya merupakan konsekuensi dari kesalahan lain, seperti tidak menempatkan string dengan benar, atau menggunakan var secara salah. Ada mungkin juga memiliki terlalu banyak tanda kurung di suatu tempat. Hati-hati memeriksa sintaks ketika kesalahan ini dilemparkan.

+ +

Contoh

+ +

Unescaped strings

+ +

Kesalahan ini dapat terjadi dengan mudah ketika tidak melepaskan string dengan benar dan engine JavaScript is expecting the end of your string already. Sebagai contoh:

+ +
var foo = 'Tom's bar';
+// SyntaxError: missing ; before statement
+ +

Anda dapat menggunakan double quotes, atau menggunakan tanda kutip dengan menambahkan backslash

+ +
var foo = "Tom's bar";
+var foo = 'Tom\'s bar';
+
+ +

Declaring properties with var

+ +

Anda tidak dapat mendeklarasikan property dari sebuah objek atau larik(array) dengan deklarasi var.

+ +
var obj = {};
+var obj.foo = 'hi'; // SyntaxError missing ; before statement
+
+var array = [];
+var array[0] = 'there'; // SyntaxError missing ; before statement
+
+ +

Sebagai gantinya, hapus kata kunci var:

+ +
var obj = {};
+obj.foo = 'hi';
+
+var array = [];
+array[0] = 'there';
+
+ +

Kata kunci yang buruk

+ +

Jika ada berasal dari bahasa pemrograman yang lain, itu juga umum untuk menggunakan kata kunci yang tidak berarti sama atau tidak memiliki arti sama sekali di JavaScript:

+ +
def print(info){
+  console.log(info);
+}; // SyntaxError missing ; before statement
+ +

Sebagai gantinya, gunakan function daripada menggunakan kata kunci def:

+ +
function print(info){
+  console.log(info);
+};
+ +

See also

+ + diff --git a/files/id/web/javascript/reference/errors/negative_repetition_count/index.html b/files/id/web/javascript/reference/errors/negative_repetition_count/index.html new file mode 100644 index 0000000000..0ea4bec83a --- /dev/null +++ b/files/id/web/javascript/reference/errors/negative_repetition_count/index.html @@ -0,0 +1,45 @@ +--- +title: 'RangeError: repeat count must be non-negative' +slug: Web/JavaScript/Reference/Errors/Negative_repetition_count +tags: + - Errors + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Negative_repetition_count +--- +
{{jsSidebar("Errors")}}
+ +

Pesan

+ +
RangeError: argument out of range
+RangeError: repeat count must be non-negative (Firefox)
+RangeError: Invalid count value (Chrome)
+
+ +

Tipe error

+ +

{{jsxref("RangeError")}}

+ +

Apa yang salah?

+ +

Metode {{jsxref("String.prototype.repeat()")}} telah digunakan. Ia punya parameter count mengindikasikan jumlah pengulangan string. Ia harus bernilai antara 0 dan kurang dari positif {{jsxref("Infinity")}} dan tidak boleh angka negatif. Kisarannya nilai yang diperbolehkan bisa dijelaskan seperti ini: [0, +∞).

+ +

Contoh

+ +

Kasus tak valid

+ +
'abc'.repeat(-1); // RangeError 
+ +

Kasus valid

+ +
'abc'.repeat(0);    // ''
+'abc'.repeat(1);    // 'abc'
+'abc'.repeat(2);    // 'abcabc'
+'abc'.repeat(3.5);  // 'abcabcabc' (count will be converted to integer)
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/errors/not_a_codepoint/index.html b/files/id/web/javascript/reference/errors/not_a_codepoint/index.html new file mode 100644 index 0000000000..d3d8b2f934 --- /dev/null +++ b/files/id/web/javascript/reference/errors/not_a_codepoint/index.html @@ -0,0 +1,56 @@ +--- +title: 'RangeError: argument is not a valid code point' +slug: Web/JavaScript/Reference/Errors/Not_a_codepoint +tags: + - Errors + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Not_a_codepoint +--- +
{{jsSidebar("Errors")}}
+ +

Pesan

+ +
RangeError: Invalid code point {0} (Edge)
+RangeError: {0} is not a valid code point (Firefox)
+RangeError: Invalid code point {0} (Chrome)
+
+ +

 

+ +

Tipe error

+ +

{{jsxref("RangeError")}}

+ +

Apa yang salah?

+ +

{{jsxref("String.fromCodePoint()")}} throws this error when passed {{jsxref("NaN")}} values, negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF (1114111).

+ +

Satu poin kode ialah satu nilai dalam codespace Unicode; yaitu, kisaran integer dari 0 hingga 0x10FFFF.

+ +

Contoh

+ +

Kasus tak nvalid

+ +
String.fromCodePoint('_');      // RangeError
+String.fromCodePoint(Infinity); // RangeError
+String.fromCodePoint(-1);       // RangeError
+String.fromCodePoint(3.14);     // RangeError
+String.fromCodePoint(3e-2);     // RangeError
+String.fromCodePoint(NaN);      // RangeError
+ +

Kasus valid

+ +
String.fromCodePoint(42);       // "*"
+String.fromCodePoint(65, 90);   // "AZ"
+String.fromCodePoint(0x404);    // "\u0404"
+String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
+String.fromCodePoint(194564);   // "\uD87E\uDC04"
+String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/errors/not_defined/index.html b/files/id/web/javascript/reference/errors/not_defined/index.html new file mode 100644 index 0000000000..d0dc93a0c6 --- /dev/null +++ b/files/id/web/javascript/reference/errors/not_defined/index.html @@ -0,0 +1,66 @@ +--- +title: 'ReferenceError: "x" is not defined' +slug: Web/JavaScript/Reference/Errors/Not_defined +translation_of: Web/JavaScript/Reference/Errors/Not_defined +--- +
{{jsSidebar("Errors")}}
+ +

Pesan

+ +
ReferenceError: "x" is not defined
+
+ +

Type Error

+ +

{{jsxref("ReferenceError")}}.

+ +

Mengapa salah?

+ +

Tidak ditemukannya referensi variabel dimanapun. Variabel ini perlu dideklarasikan, atau anda pastikan lagi bahwa ada di dalam script atau {{Glossary("scope")}} anda.

+ +
+

Note: Ketika memanggil sebuah library (seperti jQuery), pastikan memanggilnya terlebih dahulu tanda "$" sebelum mengakses variabel library. Gunakan tag {{HTMLElement("script")}} untuk memanggil library sebelum menggunakannya pada kode anda.

+
+ +

Contoh

+ +

Variable tidak dideklarasikan

+ +
foo.substring(1); // ReferenceError: foo is not defined
+
+ +

Variabel "foo" tidak ditemukan dimanapun. Variabel tersebut diperlukan oleh beberapa string, agar metode {{jsxref("String.prototype.substring()")}} dapat bekerja.

+ +
var foo = 'bar';
+foo.substring(1); // "ar"
+ +

Ruang lingkup salah

+ +

Sebuah variabel harus tersedia dalam kontek eksekusi saat ini . Variabel yang berada di dalam sebuah fungsi tidak dapat diakses dari luar fungsi, sebab sebuah variabel mepunyai batasan pada cakupan wilayah sebuah fungsi

+ +
function numbers() {
+  var num1 = 2,
+      num2 = 3;
+  return num1 + num2;
+}
+
+console.log(num1); // ReferenceError num1 is not defined.
+ +

Dengan demikian sebuah fungsi dapat mengakses semua variabel dan fungsi lainnya yang didefinisikan di dalam cakupan dimana ia didefinisikan. Dengan kata lain, sebiah fungsi yang didefinisikan di cakupan global dapat mengakses semua variabel yang didefinisian secara global pula.

+ +
var num1 = 2,
+    num2 = 3;
+
+function numbers() {
+  return num1 + num2;
+}
+
+console.log(numbers()); // 5
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/errors/property_access_denied/index.html b/files/id/web/javascript/reference/errors/property_access_denied/index.html new file mode 100644 index 0000000000..6cbece3868 --- /dev/null +++ b/files/id/web/javascript/reference/errors/property_access_denied/index.html @@ -0,0 +1,47 @@ +--- +title: 'Error: Permission denied to access property "x"' +slug: Web/JavaScript/Reference/Errors/Property_access_denied +tags: + - Error + - Errors + - JavaScript + - Keamanan +translation_of: Web/JavaScript/Reference/Errors/Property_access_denied +--- +
{{jsSidebar("Errors")}}
+ +

Pesan

+ +
Error: Permission denied to access property "x"
+
+ +

Tipe error

+ +

{{jsxref("Error")}}.

+ +

Apa kesalahannya?

+ +

Ada usaha pengaksesan objeck yang kamu belum punya ijinnya. Sepertinya elemen {{HTMLElement("iframe")}} diload dari domain berbeda yang kebijakan same-origin policynya kamu langgar.

+ +

Contoh

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe>
+    <script>
+      onload = function() {
+        console.log(frames[0].document);
+        // Error: Permission denied to access property "document"
+      }
+    </script>
+  </head>
+  <body></body>
+</html>
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/errors/too_much_recursion/index.html b/files/id/web/javascript/reference/errors/too_much_recursion/index.html new file mode 100644 index 0000000000..4c35bcfc83 --- /dev/null +++ b/files/id/web/javascript/reference/errors/too_much_recursion/index.html @@ -0,0 +1,70 @@ +--- +title: 'InternalError: too much recursion' +slug: Web/JavaScript/Reference/Errors/Too_much_recursion +tags: + - Errors + - InternalError + - JavaScript +translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion +--- +
{{jsSidebar("Errors")}}
+ +

Pesan

+ +
Error: Out of stack space (Edge)
+InternalError: too much recursion (Firefox)
+RangeError: Maximum call stack size exceeded (Chrome)
+
+ +

Tipe error

+ +

{{jsxref("InternalError")}}.

+ +

Apa yang salah?

+ +

Fungsi yang memanggil dirinya sendiri disebut fungsi rekursif. Sekali satu kondisi telah ketemu, fungsi itu berhenti memanggil dirinya. Ini disebut base case.

+ +

Dalam beberapa cara, rekursi analog dengan loop. Keduanya mengeksekusi kode yang sama berulang kali, dan keduanya membutuhkan satu kondisi (untuk mencegah loop tak-terbatas, atau lebih tepatnya, rekursi tak-terbatas dalam hal ini). Ketika panggilan fungsi terlalu banyak, atau tak ada base case dalam fungsi, JavaScript akan melempar error ini.

+ +

Contoh

+ +

Fungsi rekursif ini berjalan 10 kali, per kondisi exit.

+ +
function loop(x) {
+  if (x >= 10) // "x >= 10" is the exit condition
+    return;
+  // do stuff
+  loop(x + 1); // the recursive call
+}
+loop(0);
+ +

Mengeset kondisi ini ke nilai extrem sangat tinggi, tak akan jalan:

+ +
function loop(x) {
+  if (x >= 1000000000000)
+    return;
+  // do stuff
+  loop(x + 1);
+}
+loop(0);
+
+// InternalError: too much recursion
+ +

Fungsi rekursif ini tak punya base case. Jika tak kondisi exit, function akan memanggil dirinya sendiri terus-terusan.

+ +
function loop(x) {
+ // The base case is missing
+
+loop(x + 1); // Recursive call
+}
+
+loop(0);
+
+// InternalError: too much recursion
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/functions/index.html b/files/id/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..adb0d13f05 --- /dev/null +++ b/files/id/web/javascript/reference/functions/index.html @@ -0,0 +1,596 @@ +--- +title: Functions +slug: Web/JavaScript/Reference/Functions +tags: + - Constructor + - Function + - Functions + - JavaScript + - NeedsTranslation + - Parameter + - TopicStub + - parameters +translation_of: Web/JavaScript/Reference/Functions +--- +
{{jsSidebar("Functions")}}
+ +

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

+ +

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

+ +

For more examples and explanations, see also the JavaScript guide about functions.

+ +

Description

+ +

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

+ +

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

+ +

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

+ +
/* Declare the function 'myFunc' */
+function myFunc(theObject) {
+  theObject.brand = "Toyota";
+}
+
+/*
+ * Declare variable 'mycar';
+ * create and initialize a new Object;
+ * assign reference to it to 'mycar'
+ */
+var mycar = {
+  brand: "Honda",
+  model: "Accord",
+  year: 1998
+};
+
+/* Logs 'Honda' */
+console.log(mycar.brand);
+
+/* Pass object reference to the function */
+myFunc(mycar);
+
+/*
+ * Logs 'Toyota' as the value of the 'brand' property
+ * of the object, as changed to by the function.
+ */
+console.log(mycar.brand);
+
+ +

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

+ +

Defining functions

+ +

There are several ways to define functions:

+ +

The function declaration (function statement)

+ +

There is a special syntax for declaring functions (see function statement for details):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The function expression (function expression)

+ +

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

+ +
function [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function.
+
statements
+
The statements comprising the body of the function.
+
+ +

Here is an example of an anonymous function expression (the name is not used):

+ +
var myFunction = function() {
+    statements
+}
+ +

It is also possible to provide a name inside the definition in order to create a named function expression:

+ +
var myFunction = function namedFunction(){
+    statements
+}
+
+ +

One of the benefits of creating a named function expression is that in case we encountered an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

+ +

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

+ +

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

+ +
(function() {
+    statements
+})();
+ +

IIFE are function expressions that are invoked as soon as the function is declared.

+ +

The generator function declaration (function* statement)

+ +

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function expression (function* expression)

+ +

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

+ +
function* [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function.
+
statements
+
The statements comprising the body of the function.
+
+ +

The arrow function expression (=>)

+ +

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

+ +
([param[, param]]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
+
statements or expression
+
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
+
+ +

The Function constructor

+ +
+

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function body.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

The GeneratorFunction constructor

+ +
+

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

+
+ +
+

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

+ +
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Function parameters

+ +

Default parameters

+ +

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

+ +

Rest parameters

+ +

The rest parameter syntax allows representing an indefinite number of arguments as an array. For more details, see rest parameters.

+ +

The arguments object

+ +

You can refer to a function's arguments within the function by using the arguments object. See arguments.

+ + + +

Defining method functions

+ +

Getter and setter functions

+ +

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

+ +
+
get
+
+

Binds an object property to a function that will be called when that property is looked up.

+
+
set
+
Binds an object property to a function to be called when there is an attempt to set that property.
+
+ +

Method definition syntax

+ +

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

Constructor vs. declaration vs. expression

+ +

Compare the following:

+ +

A function defined with the Function constructor assigned to the variable multiply:

+ +
var multiply = new Function('x', 'y', 'return x * y');
+ +

A function declaration of a function named multiply:

+ +
function multiply(x, y) {
+   return x * y;
+} // there is no semicolon here
+
+ +

A function expression of an anonymous function assigned to the variable multiply:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

A function expression of a function named func_name assigned to the variable multiply:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

Differences

+ +

All do approximately the same thing, with a few subtle differences:

+ +

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

+ +
var y = function x() {};
+alert(x); // throws an error
+
+ +

The function name also appears when the function is serialized via Function's toString method.

+ +

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.

+ +

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

+ +

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

+ +
function anonymous() {
+}
+
+ +

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

+ +
/*
+ * Declare and initialize a variable 'p' (global)
+ * and a function 'myFunc' (to change the scope) inside which
+ * declare a varible with same name 'p' (current) and
+ * define three functions using three different ways:-
+ *     1. function declaration
+ *     2. function expression
+ *     3. function constructor
+ * each of which will log 'p'
+ */
+var p = 5;
+function myFunc() {
+    var p = 9;
+
+    function decl() {
+        console.log(p);
+    }
+    var expr = function() {
+        console.log(p);
+    };
+    var cons = new Function('\tconsole.log(p);');
+
+    decl();
+    expr();
+    cons();
+}
+myFunc();
+
+/*
+ * Logs:-
+ * 9  - for 'decl' by function declaration (current scope)
+ * 9  - for 'expr' by function expression (current scope)
+ * 5  - for 'cons' by Function constructor (global scope)
+ */
+
+ +

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

+ +

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

+ +
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
+foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
+ +

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

+ + + +
var x = 0;               // source element
+if (x === 0) {           // source element
+   x = 10;               // not a source element
+   function boo() {}     // not a source element
+}
+function foo() {         // source element
+   var y = 20;           // source element
+   function bar() {}     // source element
+   while (y === 10) {    // source element
+      function blah() {} // not a source element
+      y++;               // not a source element
+   }
+}
+
+ +

Examples

+ +
// function declaration
+function foo() {}
+
+// function expression
+(function bar() {})
+
+// function expression
+x = function hello() {}
+
+
+if (x) {
+   // function expression
+   function world() {}
+}
+
+
+// function declaration
+function a() {
+   // function declaration
+   function b() {}
+   if (0) {
+      // function expression
+      function c() {}
+   }
+}
+
+ +

Block-level functions

+ +

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

+ +
'use strict';
+
+function f() {
+  return 1;
+}
+
+{
+  function f() {
+    return 2;
+  }
+}
+
+f() === 1; // true
+
+// f() === 2 in non-strict mode
+
+ +

Block-level functions in non-strict code

+ +

In a word: Don't.

+ +

In non-strict code, function declarations inside blocks behave strangely. For example:

+ +
if (shouldDefineZero) {
+   function zero() {     // DANGER: compatibility risk
+      console.log("This is zero.");
+   }
+}
+
+ +

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

+ +

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

+ +

A safer way to define functions conditionally is to assign a function expression to a variable:

+ +
var zero;
+if (shouldDefineZero) {
+   zero = function() {
+      console.log("This is zero.");
+   };
+}
+
+ +

Examples

+ +

Returning a formatted number

+ +

The following function returns a string containing the formatted representation of a number padded with leading zeros.

+ +
// This function returns a string padded with leading zeros
+function padZeros(num, totalLen) {
+   var numStr = num.toString();             // Initialize return value as string
+   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
+   for (var i = 1; i <= numZeros; i++) {
+      numStr = "0" + numStr;
+   }
+   return numStr;
+}
+
+ +

The following statements call the padZeros function.

+ +
var result;
+result = padZeros(42,4); // returns "0042"
+result = padZeros(42,2); // returns "42"
+result = padZeros(5,4);  // returns "0005"
+
+ +

Determining whether a function exists

+ +

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise, some other action is taken.

+ +
 if ('function' === typeof window.noFunc) {
+   // use noFunc()
+ } else {
+   // do something else
+ }
+
+ +

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.functions")}}

+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/concat/index.html b/files/id/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..c6a25609db --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,169 @@ +--- +title: Array.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +tags: + - Array +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +
{{JSRef}}
+ +

Method concat() mengembalikan sebuah array baru yang terdiri dari array yang dipanggil kemudian digabung dengan array dan/atau nilai yang ditambahkan pada argumen.

+ +

Syntax

+ +
var array_baru = array_lama.concat(value1[, value2[, ...[, valueN]]])
+ +

Parameter

+ +
+
valueN
+
Array dan/atau nilai untuk digabung menjadi array baru. Untuk detailnya lihat deskripsi dibawah.
+
+ +

Deskripsi

+ +

concat menciptakan array baru yang terdiri dari unsur - unsur dalam object yang disebut, berdasarkan urutannya, setiap argumen, elemen dari argumen tersebut(Jika argumen adalah array) atau argumennya sendiri (jika argumennya bukan array).

+ +

concat tidak mengubah this atau beberapa array yang tersedia sebagai argumen melainkan mengembalikan shallow copy yang berisi salinan dari elemen yang sama digabung dengan array yang asli. Elemen dari array asli disalin ke array baru sebagai berikut:

+ + + +
+

Catatan: Concatenating array/nilai akan membiarkan aslinya tidak tersentuh. Selanjutnya, setiap operasi pada array baru tidak akan mempengaruhi array yang asli, begitupun sebaliknya.

+
+ +

Contoh

+ +

Menggabungkan dua Array

+ +

Berikut kode untuk menggabunggkan dua array:

+ +
var huruf = ['a', 'b', 'c'],
+    angka = [1, 2, 3];
+
+var hurufAngka = huruf.concat(angka);
+
+console.log(hurufAngka); // Hasil: ['a', 'b', 'c', 1, 2, 3]
+
+ +

Menggabungkan tiga array

+ +

Berikut kode untuk mengabungkan tiga array:

+ +
var angka1 = [1, 2, 3],
+    angka2 = [4, 5, 6],
+    angka3 = [7, 8, 9];
+
+var angkaBaru = angka1.concat(angka2, angka3);
+
+console.log(angkaBaru); // Hasil: [1, 2, 3, 4, 5, 6, 7, 8, 9]
+
+ +

Menggabungkan nilai ke sebuah array

+ +

Berikut kode untuk menggabungkan tiga nilai ke sebuah array :

+ +
var huruf = ['a', 'b', 'c'];
+
+var hurufAngka = huruf.concat(1, [2, 3]);
+
+console.log(hurufAngka);
+// Hasil: ['a', 'b', 'c', 1, 2, 3]
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/filter/index.html b/files/id/web/javascript/reference/global_objects/array/filter/index.html new file mode 100644 index 0000000000..5c23313268 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,244 @@ +--- +title: Array.prototype.filter() +slug: Web/JavaScript/Reference/Global_Objects/Array/filter +tags: + - Array + - ECMAScript 5 + - JavaScript + - Metode + - Referensi + - polyfill + - purwarupa +translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter +--- +
{{JSRef}}
+ +

Fungsi filter() membuat array baru berisi elemen yang lolos pengecekan di dalam fungsi anonim yang dikirim sebagai parameter.

+ +
var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
+
+var longWords = words.filter(function(word){
+  return word.length > 6;
+});
+
+// Filtered array longWords is ["exuberant", "destruction", "present"]
+
+ +

Versi ES6

+ +
const words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
+
+let longWords = words.filter(word => word.length > 6);
+
+// Filtered array longWords is ["exuberant", "destruction", "present"]
+
+ +

Sintaksis

+ +
var newArray = arr.filter(callback[, thisArg])
+ +

Parameter-parameter

+ +
+
callback
+
Fungsi berupa tes untuk mengecek elemen yang ada di dalam array. Kembalikan nilai true untuk meloloskan element, false untuk tidak lolos, dan dapat memiliki tiga argumen:
+
+
+
element
+
Elemen saat ini yang sedang diproses.
+
index
+
Nilai indeks (posisi) dari elemen yang sedang diproses.
+
array
+
Array yang memanggil fungsi filter.
+
+
+
thisArg {{Optional_inline}}
+
Opsional. Objek yang akan digunakan sebagai this saat mengeksekusi callback.
+
+ +

Nilai balikan

+ +

Array baru yang berisi elemen lolos pengecekan.

+ +

Deskripsi

+ +

filter() akan memanggil fungsi callback sekali untuk tiap elemen di dalam array, dan membuat array baru dari semua nilai yang dianggap true dari hasil yang dikembalikan callbackcallback hanya dipanggil untuk indeks dari array yang berisi sebuah nilai; fungsi tidak akan dipanggil untuk indeks yang telah dihapus atau belum diisi nilai tertentu. Elemen array yang tidak lolos tes callback akan dilewati dan tidak dimasukkan ke dalam array baru.

+ +

callback dapat dipanggil dengan tiga argumen:

+ +
    +
  1. nilai dari elemen
  2. +
  3. indeks dari elemen
  4. +
  5. objek array yang diproses
  6. +
+ +

Jika parameter thisArg tersedia juga saat memanggil filter, itu akan digunakan sebagai nilai this di dalam callback.  Jika tidak disediakan, maka undefined yang digunakan sebagai nilai this. Nilai this yang dapat digunakan dalam callback ditentukan dari aturan umum penentuan this dalam fungsi.

+ +

filter() tidak mengubah array yang memanggil fungsi ini.

+ +

Kumpulan elemen yang akan diproses oleh filter() ditentukan sebelum pemanggilan pertama callback. Elemen yang ditambahkan ke array setelah pemanggilanfilter() dimulai tidak akan diproses oleh callback. Jika elemen yang sudah ada dalam array berubah, atau dihapus, nilai yang digunakan dalam callback adalah nilai pada saat filter() menggunakannya; elemen yang dihapus tidak akan diproses.

+ +

Contoh

+ +

Menyaring semua nilai kecil

+ +

Contoh berikut ini menggunakan filter() untuk membuat array yang menyaring semua nilai di bawah 10.

+ +
function isBigEnough(value) {
+  return value >= 10;
+}
+
+var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
+// filtered is [12, 130, 44]
+
+ +

Menyaring entri invalid dari JSON

+ +

Contoh berikut ini menggunakan filter() untuk membuat json tersaring berisi semua elemen id berupa angka bukan nol.

+ +
var arr = [
+  { id: 15 },
+  { id: -1 },
+  { id: 0 },
+  { id: 3 },
+  { id: 12.2 },
+  { },
+  { id: null },
+  { id: NaN },
+  { id: 'undefined' }
+];
+
+var invalidEntries = 0;
+
+function isNumber(obj) {
+  return obj!== undefined && typeof(obj) === 'number' && !isNaN(obj);
+}
+
+function filterByID(item) {
+  if (isNumber(item.id)) {
+    return true;
+  }
+  invalidEntries++;
+  return false;
+}
+
+var arrByID = arr.filter(filterByID);
+
+console.log('Filtered Array\n', arrByID);
+// Filtered Array
+// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]
+
+console.log('Number of Invalid Entries = ', invalidEntries);
+// Number of Invalid Entries = 4
+
+ +

Pencarian dalam array

+ +

Contoh berikut menggunakan filter() untuk menyaring isi array berdasarkan kriteria pencarian

+ +
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
+
+/**
+ * Array filters items based on search criteria (query)
+ */
+function filterItems(query) {
+  return fruits.filter(function(el) {
+      return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
+  })
+}
+
+console.log(filterItems('ap')); // ['apple', 'grapes']
+console.log(filterItems('an')); // ['banana', 'mango', 'orange']
+ +

Implementasi ES2015

+ +
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
+
+/**
+ * Array filters items based on search criteria (query)
+ */
+const filterItems = (query) => {
+  return fruits.filter((el) =>
+    el.toLowerCase().indexOf(query.toLowerCase()) > -1
+  );
+}
+
+console.log(filterItems('ap')); // ['apple', 'grapes']
+console.log(filterItems('an')); // ['banana', 'mango', 'orange']
+
+
+ +

Polyfill

+ +

filter() ditambahkan ke standar ECMA-262 baru pada edisi ke-5; sehingga fungsi ini mungkin tidak terdapat pada semua implementasi standar. Anda dapat mengatasi hal ini dengan menambahkan kode berikut pada awalan skrip Anda, memungkinkan penggunaan filter() di implementasi ECMA-262 yang belum mendukung. Algoritma ini persis sepadan dengan yang dispesifikasikan dalam ECMA-262, edisi ke-5, dengan asumsi fn.call dievaluasi ke nilai asli dari {{jsxref("Function.prototype.bind()")}}, dan {{jsxref("Array.prototype.push()")}} memiliki nilai aslinya.

+ +
if (!Array.prototype.filter)
+  Array.prototype.filter = function(func, thisArg) {
+    'use strict';
+    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
+        throw new TypeError();
+
+    var len = this.length >>> 0,
+        res = new Array(len), // preallocate array
+        t = this, c = 0, i = -1;
+    if (thisArg === undefined)
+      while (++i !== len)
+        // checks to see if the key was set
+        if (i in this)
+          if (func(t[i], i, t))
+            res[c++] = t[i];
+    else
+      while (++i !== len)
+        // checks to see if the key was set
+        if (i in this)
+          if (func.call(thisArg, t[i], i, t))
+            res[c++] = t[i];
+
+    res.length = c; // shrink down array to proper size
+    return res;
+  };
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas browser

+ +
+ + +

{{Compat("javascript.builtins.Array.filter")}}

+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/from/index.html b/files/id/web/javascript/reference/global_objects/array/from/index.html new file mode 100644 index 0000000000..7845da9755 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,248 @@ +--- +title: Array.from() +slug: Web/JavaScript/Reference/Global_Objects/Array/from +translation_of: Web/JavaScript/Reference/Global_Objects/Array/from +--- +
{{JSRef}}
+ +

Method Array.from() membuat sebuah instansi Array dari sebuah array-like atau objek iterable.

+ +

Di ES6, sintaks class memungkinkan untuk subclassing diantaranya built-in dan user defined classes; hasilnya , method statik class-side seperti Array.from  "diwariskan" oleh subclasses dari Array dan membuat instansi baru dari subclass, bukan Array.

+ +

Sintaks

+ +
Array.from(arrayLike[, mapFn[, thisArg]])
+
+ +

Parameter

+ +
+
arrayLike
+
 Array-like atau objek iterable untuk diubah menjadi array.
+
mapFn
+
Opsional. Fungsi Map untuk memanggil setiap elemen array.
+
thisArg
+
Opsional. Nilai untuk digunakan this ketika mengeksekusi mapFn.
+
+ +

Deskripsi

+ +

Array.from() memungkinkan anda membuat Arrays dari:

+ + + +

Array.from() memiliki parameter opsional mapFn, yang memungkinkan anda untuk mengeksekusi fungsi {{jsxref("Array.prototype.map", "map")}} pada setiap elemen array (atau objek subclass) yang akan dibuat. Jelasnya, Array.from(obj, mapFn, thisArg) sama dengan Array.from(obj).map(mapFn, thisArg), kecuali dengan tidak membuat array menengah. Ini sangat penting untuk setiap subclass array, seperti typed arrays, selama array menengah akan memiliki nilai yang terpisah agar bisa masuk ke tipe yang sesuai.

+ +

Properti length dari method from() adalah 1.

+ +

Contoh

+ +
// Array-like object (arguments) to Array
+function f() {
+  return Array.from(arguments);
+}
+
+f(1, 2, 3);
+// [1, 2, 3]
+
+
+// Any iterable object...
+// Set
+var s = new Set(["foo", window]);
+Array.from(s);
+// ["foo", window]
+
+
+// Map
+var m = new Map([[1, 2], [2, 4], [4, 8]]);
+Array.from(m);
+// [[1, 2], [2, 4], [4, 8]]
+
+
+// String
+Array.from("foo");
+// ["f", "o", "o"]
+
+
+// Using an arrow function as the map function to
+// manipulate the elements
+Array.from([1, 2, 3], x => x + x);
+// [2, 4, 6]
+
+
+// Generate a sequence of numbers
+Array.from({length: 5}, (v, k) => k);
+// [0, 1, 2, 3, 4]
+
+
+ +

Polyfill

+ +

Array.from telah di masukkan di standar ECMA-262 pada edisi ke-6; karena itu mungkin tidak bisa digunakan pada implementasi standar lain. Anda bisa menyiasatinya dengan menambahkan kode berikut ke awal script, memungkinkan penggunaan Array.from pada implementasi yang aslinya tidak mendukung.  Algoritma ini sama dengan yang di spesifikasikan di ECMA-262, edisi ke-6, dengan saumsi Object dan TypeError memiliki nilai tersendiri dan callback.call mengevaluasi nilai valur dari {{jsxref("Function.prototype.call")}}. Selain itu, sejak iterable tidak dapat di polyfill, implementasi ini tidak mendukung generik iterable seperti yang didefinisikan di edisi ke-6 di ECMA-262.

+ +
// Production steps of ECMA-262, Edition 6, 22.1.2.1
+// Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
+if (!Array.from) {
+  Array.from = (function () {
+    var toStr = Object.prototype.toString;
+    var isCallable = function (fn) {
+      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
+    };
+    var toInteger = function (value) {
+      var number = Number(value);
+      if (isNaN(number)) { return 0; }
+      if (number === 0 || !isFinite(number)) { return number; }
+      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
+    };
+    var maxSafeInteger = Math.pow(2, 53) - 1;
+    var toLength = function (value) {
+      var len = toInteger(value);
+      return Math.min(Math.max(len, 0), maxSafeInteger);
+    };
+
+    // The length property of the from method is 1.
+    return function from(arrayLike/*, mapFn, thisArg */) {
+      // 1. Let C be the this value.
+      var C = this;
+
+      // 2. Let items be ToObject(arrayLike).
+      var items = Object(arrayLike);
+
+      // 3. ReturnIfAbrupt(items).
+      if (arrayLike == null) {
+        throw new TypeError("Array.from requires an array-like object - not null or undefined");
+      }
+
+      // 4. If mapfn is undefined, then let mapping be false.
+      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
+      var T;
+      if (typeof mapFn !== 'undefined') {
+        // 5. else
+        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
+        if (!isCallable(mapFn)) {
+          throw new TypeError('Array.from: when provided, the second argument must be a function');
+        }
+
+        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
+        if (arguments.length > 2) {
+          T = arguments[2];
+        }
+      }
+
+      // 10. Let lenValue be Get(items, "length").
+      // 11. Let len be ToLength(lenValue).
+      var len = toLength(items.length);
+
+      // 13. If IsConstructor(C) is true, then
+      // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
+      // 14. a. Else, Let A be ArrayCreate(len).
+      var A = isCallable(C) ? Object(new C(len)) : new Array(len);
+
+      // 16. Let k be 0.
+      var k = 0;
+      // 17. Repeat, while k < len… (also steps a - h)
+      var kValue;
+      while (k < len) {
+        kValue = items[k];
+        if (mapFn) {
+          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
+        } else {
+          A[k] = kValue;
+        }
+        k += 1;
+      }
+      // 18. Let putStatus be Put(A, "length", len, true).
+      A.length = len;
+      // 20. Return A.
+      return A;
+    };
+  }());
+}
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-array.from', 'Array.from')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("45")}}{{CompatGeckoDesktop("32")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}9.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("32")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/index.html b/files/id/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..2b052487c4 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,484 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - Global Objects + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +

Objek JavaScript Array merupakan objek global yang berguna membangun himpunan; dimana merupakan objek level tinggi dan (seperti) daftar.

+ +

Membuat sebuah Array

+ +
var fruits = ["Apple", "Banana"];
+
+console.log(fruits.length);
+// 2
+
+ +

Akses (index) kedalam sebuah item Array

+ +
var first = fruits[0];
+// Apple
+
+var last = fruits[fruits.length - 1];
+// Banana
+
+ +

Perulangan pada Array

+ +
fruits.forEach(function (item, index, array) {
+  console.log(item, index);
+});
+// Apple 0
+// Banana 1
+
+ +

Menambahkan elemen pada bagian akhir sebuah Array

+ +
var newLength = fruits.push("Orange");
+// ["Apple", "Banana", "Orange"]
+
+ +

Menghapus elemen di akhir sebuah Array

+ +
var last = fruits.pop(); // remove Orange (from the end)
+// ["Apple", "Banana"];
+
+ +

Menghapus elemen di awal sebuah Array

+ +
var first = fruits.shift(); // remove Apple from the front
+// ["Banana"];
+
+ +

Menambahkan elemen di bagian awal sebuah Array

+ +
var newLength = fruits.unshift("Strawberry") // add to the front
+// ["Strawberry", "Banana"];
+
+ +

Mencari (nomor) index elemen pada sebuah Array

+ +
fruits.push("Mango");
+// ["Strawberry", "Banana", "Mango"]
+
+var pos = fruits.indexOf("Banana");
+// 1
+
+ +

Menghapus elemen berdasar posisi index

+ +
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
+// ["Strawberry", "Mango"]
+
+ +

Menduplikat sebuah Array

+ +
var shallowCopy = fruits.slice(); // this is how to make a copy
+// ["Strawberry", "Mango"]
+
+ +

Syntax

+ +
[element0, element1, ..., elementN]
+new Array(element0, element1[, ...[, elementN]])
+new Array(arrayLength)
+ +
+
elementN
+
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below).Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
+
arrayLength
+
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number. If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.
+
+ +

Description

+ +

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

+ +

Some people think that you shouldn't use an array as an associative array. In any case, you can use plain {{jsxref("Global_Objects/Object", "objects")}} instead, although doing so comes with its own caveats. See the post Lightweight JavaScript dictionaries with arbitrary keys as an example.

+ +

Accessing array elements

+ +

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1.

+ +
var arr = ['this is the first element', 'this is the second element'];
+console.log(arr[0]);              // logs 'this is the first element'
+console.log(arr[1]);              // logs 'this is the second element'
+console.log(arr[arr.length - 1]); // logs 'this is the second element'
+
+ +

Array elements are object properties in the same way that toString is a property, but trying to access an element of an array as follows throws a syntax error, because the property name is not valid:

+ +
console.log(arr.0); // a syntax error
+
+ +

There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named '3d', it can only be referenced using bracket notation. E.g.:

+ +
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
+console.log(years.0);   // a syntax error
+console.log(years[0]);  // works properly
+
+ +
renderer.3d.setTexture(model, 'character.png');     // a syntax error
+renderer['3d'].setTexture(model, 'character.png');  // works properly
+
+ +

Note that in the 3d example, '3d' had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. It is for this reason that '2' and '02' would refer to two different slots on the years object and the following example could be true:

+ +
console.log(years['2'] != years['02']);
+
+ +

Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation(but it can be accessed by dot notation in firefox 40.0a2 at least):

+ +
var promise = {
+  'var'  : 'text',
+  'array': [1, 2, 3, 4]
+};
+
+console.log(promise['array']);
+
+ +

Relationship between length and numerical properties

+ +

A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.

+ +
var fruits = [];
+fruits.push('banana', 'apple', 'peach');
+
+console.log(fruits.length); // 3
+
+ +

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:

+ +
fruits[5] = 'mango';
+console.log(fruits[5]); // 'mango'
+console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
+console.log(fruits.length); // 6
+
+ +

Increasing the {{jsxref("Array.length", "length")}}.

+ +
fruits.length = 10;
+console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
+console.log(fruits.length); // 10
+
+ +

Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.

+ +
fruits.length = 2;
+console.log(Object.keys(fruits)); // ['0', '1']
+console.log(fruits.length); // 2
+
+ +

This is explained further on the {{jsxref("Array.length")}} page.

+ +

Creating an array using the result of a match

+ +

The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:

+ +
// Match one d followed by one or more b's followed by one d
+// Remember matched b's and the following d
+// Ignore case
+
+var myRe = /d(b+)(d)/i;
+var myArray = myRe.exec('cdbBdbsbz');
+
+ +

The properties and elements returned from this match are as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property/ElementDescriptionExample
inputA read-only property that reflects the original string against which the regular expression was matched.cdbBdbsbz
indexA read-only property that is the zero-based index of the match in the string.1
[0]A read-only element that specifies the last matched characters.dbBd
[1], ...[n]Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.[1]: bB
+ [2]: d
+ +

Properties

+ +
+
Array.length
+
The Array constructor's length property whose value is 1.
+
{{jsxref("Array.@@species", "get Array[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("Array.prototype")}}
+
Allows the addition of properties to all array objects.
+
+ +

Methods

+ +
+
{{jsxref("Array.from()")}}
+
Creates a new Array instance from an array-like or iterable object.
+
{{jsxref("Array.isArray()")}}
+
Returns true if a variable is an array, if not false.
+
{{jsxref("Array.of()")}}
+
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
+
+ +

Array instances

+ +

All Array instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the Array constructor can be modified to affect all Array instances.

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
+ +

Methods

+ +

Mutator methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
+ +

Accessor methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
+ +

Iteration methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
+ +

Array generic methods

+ +
+

Array generics are non-standard, deprecated and will get removed near future. Note that you can not rely on them cross-browser. However, there is a shim available on GitHub.

+
+ +

Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable str is a letter, you would write:

+ +
function isLetter(character) {
+  return character >= 'a' && character <= 'z';
+}
+
+if (Array.prototype.every.call(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

+ +
if (Array.every(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.

+ +

These are not part of ECMAScript standards (though the ES6 {{jsxref("Array.from()")}} can be used to achieve this). The following is a shim to allow its use in all browsers:

+ +
// Assumes Array extras already present (one may use polyfills for these as well)
+(function() {
+  'use strict';
+
+  var i,
+    // We could also build the array of methods with the following, but the
+    //   getOwnPropertyNames() method is non-shimable:
+    // Object.getOwnPropertyNames(Array).filter(function(methodName) {
+    //   return typeof Array[methodName] === 'function'
+    // });
+    methods = [
+      'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
+      'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
+      'forEach', 'map', 'reduce', 'reduceRight', 'filter',
+      'some', 'every', 'find', 'findIndex', 'entries', 'keys',
+      'values', 'copyWithin', 'includes'
+    ],
+    methodCount = methods.length,
+    assignArrayGeneric = function(methodName) {
+      if (!Array[methodName]) {
+        var method = Array.prototype[methodName];
+        if (typeof method === 'function') {
+          Array[methodName] = function() {
+            return method.call.apply(method, arguments);
+          };
+        }
+      }
+    };
+
+  for (i = 0; i < methodCount; i++) {
+    assignArrayGeneric(methods[i]);
+  }
+}());
+
+ +

Examples

+ +

Creating an array

+ +

The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

+ +
var msgArray = [];
+msgArray[0] = 'Hello';
+msgArray[99] = 'world';
+
+if (msgArray.length === 100) {
+  console.log('The length is 100.');
+}
+
+ +

Creating a two-dimensional array

+ +

The following creates a chess board as a two dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.

+ +
var board = [
+  ['R','N','B','Q','K','B','N','R'],
+  ['P','P','P','P','P','P','P','P'],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  ['p','p','p','p','p','p','p','p'],
+  ['r','n','b','q','k','b','n','r'] ];
+
+console.log(board.join('\n') + '\n\n');
+
+// Move King's Pawn forward 2
+board[4][4] = board[6][4];
+board[6][4] = ' ';
+console.log(board.join('\n'));
+
+ +

Here is the output:

+ +
R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+p,p,p,p,p,p,p,p
+r,n,b,q,k,b,n,r
+
+R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , ,p, , ,
+ , , , , , , ,
+p,p,p,p, ,p,p,p
+r,n,b,q,k,b,n,r
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES6', '#sec-array-objects', 'Array')}}{{Spec2('ES6')}}New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}{{Spec2('ESDraft')}}New method added: {{jsxref("Array.prototype.includes()")}}
+ +

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/id/web/javascript/reference/global_objects/array/isarray/index.html b/files/id/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..152b6cdfd0 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,144 @@ +--- +title: Array.isArray() +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +tags: + - Array + - ECMAScript5 + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +
{{JSRef}}
+ +

Method Array.isArray() mengembalikan nilai true jika objek adalah array, false jika bukan.

+ +

Sintaks

+ +
Array.isArray(obj)
+ +

Parameter

+ +
+
obj
+
Objek yang di cek.
+
+ +

Deskripsi

+ +

Baca artikel “Determining with absolute accuracy whether or not a JavaScript object is an array” untuk detailnya.

+ +

Contoh

+ +
// semuanya mengembalikan nilai true
+Array.isArray([]);
+Array.isArray([1]);
+Array.isArray(new Array());
+// Sekedar fakta : Array.prototype sendiri adalah array:
+Array.isArray(Array.prototype);
+
+// semua mengembalikan nilai false
+Array.isArray();
+Array.isArray({});
+Array.isArray(null);
+Array.isArray(undefined);
+Array.isArray(17);
+Array.isArray('Array');
+Array.isArray(true);
+Array.isArray(false);
+Array.isArray({ __proto__: Array.prototype });
+
+ +

Polyfill

+ +

Jalankan kode berikut sebelum kode lain untuk membuat method Array.isArray() jika secara native tidak tersedia.

+ +
if (!Array.isArray) {
+  Array.isArray = function(arg) {
+    return Object.prototype.toString.call(arg) === '[object Array]';
+  };
+}
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/join/index.html b/files/id/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..8ddd3bb8ed --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,132 @@ +--- +title: Array.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - Array + - Method + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +
{{JSRef}}
+ +

Method join() menggabungkan semua elemen dari sebuah array menjadi sebuah string.

+ +

Syntax

+ +
str = arr.join([separator = ','])
+ +

Parameter

+ +
+
separator
+
Opsional. Menentukan string untuk memisahkan setiap elemen array. separator dapat di konersi ke string jika diperlukan. Jika dihilangkan, elemen array akan dipisahkan dengan koma, jika separator adalah string kosong, semua elemen digabungkan tanpa karakter pemisah.
+
+ +

Deskripsi

+ +

mengonversi string dari semua elemen array dengan menggabungkannya menjadi sebuah string. Jika elemen bernilai undefined atau null, akan dikonversi menjadi string kosong.

+ +

Contoh

+ +

Penggabungan array menggunakan empat cara yang berbeda

+ +

Berikut merupakan contoh membuat array, dengan tiga elemen, kemudian menggabungkan array dengan empa cara berbeda : menggunakan separator default, koma dan spasi, plus dan string kosong.

+ +
var a = ['Angin', 'Air', 'Api'];
+var variabel1 = a.join();      // Memberikan nilai 'Angin,Air,Api' pada variabel1
+var variabel2 = a.join(', ');  // Memberikan nilai 'Angin, Air, Api' pada variabel2
+var variabel3 = a.join(' + '); // Memberikan nilai 'Angin + Air + Api' pada variabel3
+var variabel4 = a.join('');    // Memberikan nilai 'AnginAirApi' pada variabel4
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Dasar{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/length/index.html b/files/id/web/javascript/reference/global_objects/array/length/index.html new file mode 100644 index 0000000000..6e8e9e3ae8 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/length/index.html @@ -0,0 +1,145 @@ +--- +title: Array.length +slug: Web/JavaScript/Reference/Global_Objects/Array/length +tags: + - Array + - JavaScript + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/length +--- +
{{JSRef}}
+ +

Properti array length merangkai atau mengembalikan angka dari sejumlah elemen pada array. berupa unsigned, 32-bit integer yang selalu lebih besar dari indeks array terbesar atau index array terakhir.

+ +
var items = ["sepatu", "kaos", "baju", "sweater"];
+items.length;
+
+// index terakhir "sweater" 3
+// returns 4
+ +

Deskripsi

+ +

Nilai properti length berupa integer positif dan nilainya lebih kecil dari 2 sampai 2 pangkat 32 (232).

+ +

Anda bisa merangkai properti length untuk memotong array kapanpun. Ketika anda memperpanjang array dengan mengubah properti length, nomor dari elemen sebenarnya tidak bertambah; contoh, jika anda merangkai length ke 3 ketika saat ini adalah 2, array tetap berisi 2 element. Dengan begitu, properti length tidak selalu menunjukkan jumlah angka dari nilai yang didefinisikan pada array. Lihat juga Hubungan antara length dan properti numerik.

+ +

{{js_property_attributes(1, 0, 0)}}

+ +

Contoh

+ +

Iterasi pada array

+ +

Pada contoh, numbers array diiterasikan melalui nilai properti array length. Nilai setiap elemen kemudian dikalikan.

+ +
var numbers = [1, 2, 3, 4, 5];
+var length = numbers.length;
+for (var i = 0; i < length; i++) {
+  numbers[i] *= 2;
+}
+// numbers is now [2, 4, 6, 8, 10]
+
+ +

Memendekan array

+ +

Pada contoh memendekkan array numbers ke panjang array 3 jika panjang array sebenarnya lebih besar dari 3.

+ +
var numbers = [1,2,3,4,5];
+
+if (numbers.length > 3) {
+  numbers.length = 3;
+}
+
+console.log(numbers); // [1, 2, 3]
+console.log(numbers.length); // 3
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/of/index.html b/files/id/web/javascript/reference/global_objects/array/of/index.html new file mode 100644 index 0000000000..49ca553133 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,129 @@ +--- +title: Array.of() +slug: Web/JavaScript/Reference/Global_Objects/Array/of +tags: + - Array + - JavaScript + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Array/of +--- +
{{JSRef}}
+ +

Method Array.of() membuat instansi Array baru denganjumlah variabel argumen.

+ +

Perbedaan antara Array.of() dan konstruktor Array pada penanganan argumen integer: Array.of(42) membuat sebuah array dengan sebuah elemen, 42, sedang Array(42) membuat array dengan 42 element, yang masing - masing undefined.

+ +

Sintaks

+ +
Array.of(element0[, element1[, ...[, elementN]]])
+ +

Parameter

+ +
+
elementN
+
Element yang digunakan untuk membuat array.
+
+ +

Deskripsi

+ +

Fungsi ini merupakan bagian dari ECMAScript 6 standard. Untuk informasi lengkap lihat Array.of and Array.from proposal dan Array.of polyfill.

+ +

Contoh

+ +
Array.of(1);         // [1]
+Array.of(1, 2, 3);   // [1, 2, 3]
+Array.of(undefined); // [undefined]
+
+ +

Polyfill

+ +

Menjalankan kode berikut sebelum kode lain membuat Array.of() jika secara native tidak tersedia.

+ +
if (!Array.of) {
+  Array.of = function() {
+    return Array.prototype.slice.call(arguments);
+  };
+}
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-array.of', 'Array.of')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(45)}}{{CompatGeckoDesktop("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(39)}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/pop/index.html b/files/id/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..f8dc9f0523 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,134 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +
{{JSRef}}
+ +

Method pop() menghapus elemen terakhir dari array dan mengembalikan elemen tersebut.

+ +

Syntaks

+ +
arr.pop()
+ +

Deskripsi

+ +

Method pop menghapus elemen terakhir pada array dan mengembalikan nilai ke pemanggil.

+ +

pop adalah desain generic; method ini dapat berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} ke objek yang menyerupai array. Objek yang tidak memiliki properti length mencerminkan akhir dari urutan, properti numerik yang berbasis zero mungkin tidak memiliki makna yang berarti.

+ +

jika anda menggunakan pop() pada array yang kosong, akan mengembalikan nilai {{jsxref("undefined")}}.

+ +

Contoh

+ +

Menghapus elemen terakhir pada array

+ +

Kode berikut membuat array myFish yang memiliki empat elemen, kemudian menghapus elemen teakhirnya.

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+
+console.log(myFish); // ['angel', 'clown', 'mandarin', 'sturgeon']
+
+var popped = myFish.pop();
+
+console.log(myFish); // ['angel', 'clown', 'mandarin' ]
+
+console.log(popped); // 'sturgeon'
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/reverse/index.html b/files/id/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..dca16b463e --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,127 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +tags: + - Array + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +
{{JSRef}}
+ +

Method reverse() membalikkan urutan array elemen. Elemen array pertama menjadi terakhir dan sebaliknya.

+ +

Sintaks

+ +
arr.reverse()
+ +

Parameter

+ +

None.

+ +

Deskripsi

+ +

Method reverse mengubah urutan elemen objek array, memutasi array, dan mengembalikan referensi ke array.

+ +

Contoh

+ +

Membalikan elemen di dalam array

+ +

Pada contoh membuat array myArray dengan tiga elemen,  kemudian membalikkan array.

+ +
var myArray = ['one', 'two', 'three'];
+myArray.reverse();
+
+console.log(myArray) // ['three', 'two', 'one']
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/shift/index.html b/files/id/web/javascript/reference/global_objects/array/shift/index.html new file mode 100644 index 0000000000..ac20d5cd60 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/shift/index.html @@ -0,0 +1,129 @@ +--- +title: Array.prototype.shift() +slug: Web/JavaScript/Reference/Global_Objects/Array/shift +translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift +--- +
{{JSRef}}
+ +

method shift() menghapus elemen pertama pada array dan mengembalikan elemen tersebut. Method ini mengubah panjang (jumlah elemen) array.

+ +

Sintaks

+ +
arr.shift()
+ +

Deskripsi

+ +

Method shift menghapus elemen pada index 0 dan menggeser nilai index setelahnya, kemudian mengembalikan nilai yang dihapus. Jika properti {{jsxref("Array.length", "length")}} bernilai 0, maka akan mengembalikan nilai {{jsxref("undefined")}}.

+ +

shift adalah desain generic; method ini dapat berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} pada objek yag menyerupai array. Objek yang tidak memiliki properti length akan dianggap terakhir dalam urutan, properti numerik berbasis zero mungkin tidak memiliki makna yang berarti.

+ +

Contoh

+ +

Menghapus Elemen dari sebuah Array

+ +

Kode berikut menampilkan array myFish sebelum dan sesudah menghapus elemen pertama. Juga menampilkan elemen yang dihapus:

+ +
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
+
+console.log('myFish sebelum: ' + myFish);
+// myFish sebelum: angel,clown,mandarin,surgeon
+
+var shifted = myFish.shift();
+
+console.log('myFish sesudah: ' + myFish);
+// myFish sesudah: clown,mandarin,surgeon
+
+console.log('Elemen yang dihapus: ' + shifted);
+// Elemen yang dihapus: angel
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ESDraft')}} 
+ +

Kompabiltas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/slice/index.html b/files/id/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..44f018ba65 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,152 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +
{{JSRef}}
+ +

Method slice() mengembalikan sebuah salinan dangkal dari sebagian array menjadi sebuah objek array baru yang dimulai dari start sampai end (end tidak termasuk) dimana start dan end merupakan index dari  item yang ada di  array tersebut. Tidak merubah array asli.

+ +
{{EmbedInteractiveExample("pages/js/array-slice.html")}}
+ + + +

Sintaks

+ +
arr.slice([start[, end]])
+
+ +

Parameter

+ +
+
start {{optional_inline}}
+
Indeks berbasis nol untuk memulai ekstraksi.
+

+ Indeks negatif dapat digunakan, menunjukkan offset dari akhir urutan.. slice(-2) mengekstrak dua elemen terakhir dari urutan.
+
Jika start tidak terdefinisi, slice memulai dari indeks ke 0.
+
Jika start lebih besar dari indeks urutan, array kosong akan dikembalikan.
+
end {{optional_inline}}
+
Indeks berbasis nol untuk mengakhiri ekstraksi. slice mengekstrak hingga tapi tidak termasuk end. Sebagai contoh, slice(1,4) mengekstrak elemen kedua menuju elemen ke-empat (indeks elemen 1, 2, dan 3).
+
+

Indeks negatif bisa digunakan,
+ menunjukkan offset dari akhir urutan. slice(2,-1) mengekstrak elemen ketiga menuju elemen kedua-ke-terakhir dalam urutan.

+
+
Jika end dihillangkan, slice mengekstrak melalui akhir dari urutan (arr.length).
+
Jika end lebih besar dari panjang urutan, slice mengkstrak melalui akhir urutan (arr.length).
+
+ +

Return value

+ +

Array baru berisi elemen yang diekstrak.

+ +

Deskripsi

+ +

slice does not alter the original array. It returns a shallow copy of elements from the original array. Elements of the original array are copied into the returned array as follows:

+ + + +

If a new element is added to either array, the other array is not affected.

+ +

Contoh

+ +

Return a portion of an existing array

+ +
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+let citrus = fruits.slice(1, 3)
+
+// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+// citrus contains ['Orange','Lemon']
+
+ +

Using slice

+ +

In the following example, slice creates a new array, newCar, from myCar. Both include a reference to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the change.

+ +
// Using slice, create newCar from myCar.
+let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }
+let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']
+let newCar = myCar.slice(0, 2)
+
+// Display the values of myCar, newCar, and the color of myHonda
+//  referenced from both arrays.
+console.log('myCar = ' + JSON.stringify(myCar))
+console.log('newCar = ' + JSON.stringify(newCar))
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+
+// Change the color of myHonda.
+myHonda.color = 'purple'
+console.log('The new color of my Honda is ' + myHonda.color)
+
+// Display the color of myHonda referenced from both arrays.
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+
+ +

This script writes:

+ +
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
+         'cherry condition', 'purchased 1997']
+newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
+myCar[0].color = red
+newCar[0].color = red
+The new color of my Honda is purple
+myCar[0].color = purple
+newCar[0].color = purple
+
+ +

Array-like objects

+ +

slice method can also be called to convert Array-like objects/collections to a new Array. You just {{jsxref("Function.prototype.bind", "bind")}} the method to the object. The {{jsxref("Functions/arguments", "arguments")}} inside a function is an example of an 'array-like object'.

+ +
function list() {
+  return Array.prototype.slice.call(arguments)
+}
+
+let list1 = list(1, 2, 3) // [1, 2, 3]
+
+ +

Binding can be done with the {{jsxref("Function.prototype.call", "call()")}} method of {{jsxref("Function.prototype")}} and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call.

+ +

Anyway, it can be simplified using {{jsxref("Function.prototype.bind", "bind")}}.

+ +
let unboundSlice = Array.prototype.slice
+let slice = Function.prototype.call.bind(unboundSlice)
+
+function list() {
+  return slice(arguments)
+}
+
+let list1 = list(1, 2, 3) // [1, 2, 3]
+ +

Spesifikasi

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}
+ +

Kompatibilitas Peramban

+ + + +

{{Compat("javascript.builtins.Array.slice")}}

+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/splice/index.html b/files/id/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..a0c7c1cb86 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,146 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +tags: + - Indonesia +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +
{{JSRef}}
+ +

Metode splice() mengubah konten dari array dengan menghapus elemen yang ada dan/atau menambah elemen baru.

+ +
{{EmbedInteractiveExample("pages/js/array-splice.html")}}
+ +

Syntax

+ +
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
+
+ +

Parameters

+ +
+
start
+
Indeks di mana untuk mulai mengubah array (dengan asal 0). Jika lebih besar dari panjang array, indeks awal sebenarnya akan diatur ke panjang array. Jika negatif, akan mulai banyak elemen dari akhir array (dengan asal -1) dan akan diset ke 0 jika nilai absolut lebih besar dari panjang array.
+
deleteCount {{optional_inline}}
+
Sebuah integer yang menunjukkan jumlah elemen array lama yang akan dihapus.
+
Jika deleteCount dihilangkan, atau jika nilainya lebih besar dari array.length - start (yaitu, jika lebih besar dari jumlah elemen yang tersisa dalam array, mulai dari start), maka semua elemen dari start sampai akhir dari array akan dihapus.
+
Jika deleteCount adalah 0 atau negatif, tidak ada elemen yang dihapus. Dalam kasus ini, Anda harus menentukan setidaknya satu elemen baru (lihat di bawah).
+
item1, item2, ... {{optional_inline}}
+
Elemen yang ditambahkan ke array, dimulai pada indeks awal. Jika kamu tidak menentukan elemen apapun, splice() hanya akan menghapus elemen-elemen dari array.
+
+ +

Return value

+ +

Array berisi elemen yang dihapus. Jika hanya satu elemen yang dihapus, array dari satu elemen dikembalikan. Jika tidak ada elemen yang dihapus, sebuah array kosong akan dikembalikan.

+ +

Deskripsi

+ +

Jika anda menentukan elemen yang berbeda untuk disisipkan daripada nomor yang anda hapus, array akan memiliki panjang yang berbeda ketika kamu memanggilnya nanti.

+ +

Contoh

+ +

Remove 0 elements from index 2, and insert "drum"

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2, 0, 'drum');
+
+// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
+// removed is [], no elements removed
+
+ +

Remove 1 element from index 3

+ +
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(3, 1);
+
+// removed is ["mandarin"]
+// myFish is ["angel", "clown", "drum", "sturgeon"]
+
+ +

Remove 1 element from index 2, and insert "trumpet"

+ +
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
+var removed = myFish.splice(2, 1, 'trumpet');
+
+// myFish is ["angel", "clown", "trumpet", "sturgeon"]
+// removed is ["drum"]
+ +

Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue"

+ +
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
+var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
+
+// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
+// removed is ["angel", "clown"]
+ +

Remove 2 elements from index 2

+ +
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
+var removed = myFish.splice(myFish.length - 3, 2);
+
+// myFish is ["parrot", "anemone", "sturgeon"]
+// removed is ["blue", "trumpet"]
+ +

Remove 1 element from index -2

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(-2, 1);
+
+// myFish is ["angel", "clown", "sturgeon"]
+// removed is ["mandarin"]
+ +

Remove all elements after index 2 (incl.)

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2);
+
+// myFish is ["angel", "clown"]
+// removed is ["mandarin", "sturgeon"]
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.splice")}}

+
+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/unshift/index.html b/files/id/web/javascript/reference/global_objects/array/unshift/index.html new file mode 100644 index 0000000000..4df2069f54 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,135 @@ +--- +title: Array.prototype.unshift() +slug: Web/JavaScript/Reference/Global_Objects/Array/unshift +translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift +--- +
{{JSRef}}
+ +

Method unshift() menambahkan satu atau lebih elemen ke indek awal array dan mengembalikan jumlah index array yang baru.

+ +

Sintaks

+ +
arr.unshift([element1[, ...[, elementN]]])
+ +

Parameter

+ +
+
elementN
+
Elemen yang akan di tambahkan di awal array.
+
+ +

Returns

+ +

Properti {{jsxref("Array.length", "length")}} baru dari objek teratas dimana method di panggil.

+ +

Deskripsi

+ +

Method unshift menambahkan nilai yang diberikan ke awal objek array.

+ +

unshift biasanya generic; method ini bisa berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} ke objek menyerupai array. Objek yang tidak memiliki properti length mencerminkan dari serangkaian urutan, properti numerik berbasis zero kemungkinan tidak berperilaku dengan cara yang berarti.

+ +

Contoh

+ +
var arr = [1, 2];
+
+arr.unshift(0); // result of call is 3, the new array length
+// arr is [0, 1, 2]
+
+arr.unshift(-2, -1); // = 5
+// arr is [-2, -1, 0, 1, 2]
+
+arr.unshift([-3]);
+// arr is [[-3], -2, -1, 0, 1, 2]
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/array/values/index.html b/files/id/web/javascript/reference/global_objects/array/values/index.html new file mode 100644 index 0000000000..dd77cc65a5 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/array/values/index.html @@ -0,0 +1,120 @@ +--- +title: Array.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Array/values +translation_of: Web/JavaScript/Reference/Global_Objects/Array/values +--- +
{{JSRef}}
+ +

Method values() mengembalikan objek Array Iterator baru yang berisi nilai setiap index pada array.

+ +

Sintaks

+ +
arr.values()
+ +

Contoh

+ +

Iterasi menggunakan for...of loop

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr.values();
+// your browser must support for..of loop
+// and let-scoped variables in for loops
+for (let letter of eArr) {
+  console.log(letter);
+}
+
+ +

Iterasi alternatif

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr.values();
+console.log(eArr.next().value); // w
+console.log(eArr.next().value); // y
+console.log(eArr.next().value); // k
+console.log(eArr.next().value); // o
+console.log(eArr.next().value); // p
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("51")}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatNo}}9
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("51")}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html b/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html new file mode 100644 index 0000000000..08e657aeec --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html @@ -0,0 +1,88 @@ +--- +title: Date.prototype.getFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +tags: + - Date + - JavaScript + - Metode + - Prototype + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +--- +
{{JSRef}}
+ +

Metode getFullYear() mengembanlikan tahun dari tanggal yang dispesifikasi, mengikuti waktu lokal.

+ +

Gunakan metode ini ketimbang metode {{jsxref("Date.prototype.getYear()", "getYear()")}}.

+ +
{{EmbedInteractiveExample("pages/js/date-getfullyear.html")}}
+ + + +

Syntax

+ +
dateObj.getFullYear()
+ +

Nilai kembali

+ +

Angka yang berkorespondensi ke tahuny dari tanggal yang diberikan, mengikuti waktu lokal.

+ +

Deskripsi

+ +

Nilai yang dikembalikan oleh getFullYear() is an absolute number. For dates between the years 1000 and 9999, getFullYear() returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000.

+ +

Contoh

+ +

Menggunakan getFullYear()

+ +

Contoh ini menggassign nilai empat-digit dari tahun saat ini ke variabel year.

+ +
var today = new Date();
+var year = today.getFullYear();
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomen
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi inisial. Diimplementasi di JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.10', 'Date.prototype.getFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas peramban

+ + + +

{{Compat("javascript.builtins.Date.getFullYear")}}

+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/date/index.html b/files/id/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..1fc6272dcf --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,261 @@ +--- +title: Date +slug: Web/JavaScript/Reference/Global_Objects/Date +tags: + - Date + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +
{{JSRef}}
+ +

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

+ +

Syntax

+ +
new Date();
+new Date(value);
+new Date(dateString);
+new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
+
+ +
+

Note: JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the {{jsxref("Operators/new", "new")}} operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.

+
+ +

Parameters

+ +
+

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

+
+ +
+

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}}) with the same arguments.

+
+ +
+
value
+
Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).
+
dateString
+
String value representing a date. The string should be in a format recognized by the {{jsxref("Date.parse()")}} method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601). +
+

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

+
+
+
year
+
Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999. See the {{anch("Example:_Two_digit_years_map_to_1900_-_1999", "example below")}}.
+
month
+
Integer value representing the month, beginning with 0 for January to 11 for December.
+
day
+
Optional. Integer value representing the day of the month.
+
hour
+
Optional. Integer value representing the hour of the day.
+
minute
+
Optional. Integer value representing the minute segment of a time.
+
second
+
Optional. Integer value representing the second segment of a time.
+
millisecond
+
Optional. Integer value representing the millisecond segment of a time.
+
+ +

Description

+ + + +

Properties

+ +
+
{{jsxref("Date.prototype")}}
+
Allows the addition of properties to a JavaScript Date object.
+
Date.length
+
The value of Date.length is 7. This is the number of arguments handled by the constructor.
+
+ +

Methods

+ +
+
{{jsxref("Date.now()")}}
+
Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
+
{{jsxref("Date.parse()")}}
+
Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC. +
+

Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.

+
+
+
{{jsxref("Date.UTC()")}}
+
Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC.
+
+ +

JavaScript Date instances

+ +

All Date instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the Date constructor can be modified to affect all Date instances.

+ +

Date.prototype Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}
+ +

Examples

+ +

Several ways to create a Date object

+ +

The following examples show several ways to create JavaScript dates:

+ +
+

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

+
+ +
var today = new Date();
+var birthday = new Date('December 17, 1995 03:24:00');
+var birthday = new Date('1995-12-17T03:24:00');
+var birthday = new Date(1995, 11, 17);
+var birthday = new Date(1995, 11, 17, 3, 24, 0);
+
+ +

Two digit years map to 1900 - 1999

+ +

In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.

+ +
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+// Deprecated method, 98 maps to 1998 here as well
+date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
+
+ +

Calculating elapsed time

+ +

The following examples show how to determine the elapsed time between two JavaScript dates in millisconds.

+ +

Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.

+ +
// using Date objects
+var start = Date.now();
+
+// the event to time goes here:
+doSomethingForALongTime();
+var end = Date.now();
+var elapsed = end - start; // elapsed time in milliseconds
+
+ +
// using built-in methods
+var start = new Date();
+
+// the event to time goes here:
+doSomethingForALongTime();
+var end = new Date();
+var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
+
+ +
// to test a function and get back its return
+function printElapsedTime(fTest) {
+  var nStartTime = Date.now(),
+      vReturn = fTest(),
+      nEndTime = Date.now();
+
+  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
+  return vReturn;
+}
+
+yourFunctionReturn = printElapsedTime(yourFunction);
+
+ +
+

Note: In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Some browsers can have issues when parsing dates: 3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings

+ +

[2] ISO8601 Date Format is not supported in Internet Explorer 8, and other version can have issues when parsing dates

diff --git a/files/id/web/javascript/reference/global_objects/date/now/index.html b/files/id/web/javascript/reference/global_objects/date/now/index.html new file mode 100644 index 0000000000..43760a275b --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,124 @@ +--- +title: Date.now() +slug: Web/JavaScript/Reference/Global_Objects/Date/now +tags: + - Date + - JavaScript + - Method + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/Date/now +--- +
{{JSRef}}
+ +

Method Date.now() mengembalikan jumlah milisekon sejak 1 Januari 1970 00:00:00 UTC.

+ +

Sintaks

+ +
var timeInMs = Date.now();
+ +

Parameter

+ +

None.

+ +

Deskripsi

+ +

Method now() mengembalikan nilaimillisekon sejak 1 January 1970 00:00:00 UTC hingga sekarang sebagai {{jsxref("Number")}}.

+ +

Karena now() adalah method static dari {{jsxref("Date")}}, anda bisa menggunakannya sebagai Date.now().

+ +

Polyfill

+ +

Method ini di bakukan pada ECMA-262 5th edition. Mesin yang belum diupdate untuk mendukung method ini bisa menggunkan shim berikut:

+ +
if (!Date.now) {
+  Date.now = function now() {
+    return new Date().getTime();
+  };
+}
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES6', '#sec-date.now', 'Date.now')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9")}}{{CompatIE("9")}}{{CompatOpera("10.50")}}{{CompatSafari("4")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/date/tojson/index.html b/files/id/web/javascript/reference/global_objects/date/tojson/index.html new file mode 100644 index 0000000000..cb951d5fa0 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/date/tojson/index.html @@ -0,0 +1,119 @@ +--- +title: Date.prototype.toJSON() +slug: Web/JavaScript/Reference/Global_Objects/Date/toJSON +tags: + - Date + - Method + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toJSON +--- +
{{JSRef}}
+ +

Method toJSON() mengembalikan string berdasarkan pada object {{jsxref("Date")}}.

+ +

Syntax

+ +
dateObj.toJSON()
+ +

Deskripsi

+ +

{{jsxref("Date")}} mengacu pada titik waktu tertentu. Memanggil toJSON() mengembalikan nilai ke string (menggunakan {{jsxref("Date.prototype.toISOString()", "toISOString()")}}) berdasarkan nilai pada object {{jsxref("Date")}}. Method ini biasanya ditujukan, secara default, guna menserialisasi object {{jsxref("Date")}} saat serialisasi {{Glossary("JSON")}}.

+ +

Contoh

+ +

Penggunaan toJSON()

+ +
var jsonDate = (new Date()).toJSON();
+var backToDate = new Date(jsonDate);
+
+console.log(jsonDate); //2015-10-26T07:46:36.611Z
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.9.5.44', 'Date.prototype.toJSON')}}{{Spec2('ES5.1')}}Definisi Inisial. Diimplementasikan dalam JavaScript 1.8.5.
{{SpecName('ES6', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/date/totimestring/index.html b/files/id/web/javascript/reference/global_objects/date/totimestring/index.html new file mode 100644 index 0000000000..90ebd23e68 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/date/totimestring/index.html @@ -0,0 +1,125 @@ +--- +title: Date.prototype.toTimeString() +slug: Web/JavaScript/Reference/Global_Objects/Date/toTimeString +tags: + - Date + - JavaScript + - Prototype + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toTimeString +--- +
{{JSRef}}
+ +

Method toTimeString() mengembalikan satuan waktu dari objek {{jsxref("Date")}} object dalam format yang dapat dibaca manusia.

+ +

Sintaks

+ +
dateObj.toTimeString()
+ +

Deskripsi

+ +

Instansi {{jsxref("Date")}} menunjuk pada titik waktu spesifik. Dengan memanggil {{jsxref("Date.prototype.toString()", "toString()")}} akan mengembalikan format tanggal dalam bentuk yang mudah dibaca manuasia dengan format tanggal English (Amerika). Di SpiderMonkey, Bagian tanggal terdiri dari (hari, bulan, dan tahun) di ikuti dengan waktu (Jam, menit, detik, dan waktu bagian). Terkadang kita hanya membutuhan bagian waktu dalam bentuk string; hal tersebut bisa di capai dengan menggunakan metod toTimeString().

+ +

Method toTimeString() sangatlah berguna karena berdasarkan engine (compiliant engine) yang di implementasikan ECMA-262 mungkin string yang diperoleh akan berbeda dari {{jsxref("Date.prototype.toString()", "toString()")}} untuk objek {{jsxref("Date")}}, dengan format tergantung dari implementasi; pendekatan bagian string sederhana kemungkinan tidak sama untuk engine yang berbeda.

+ +

Contoh

+ +

Dasar penggunaan of toTimeString()

+ +
var d = new Date(1993, 6, 28, 14, 39, 7);
+
+console.log(d.toString());     // logs Wed Jul 28 1993 14:39:07 GMT-0600 (PDT)
+console.log(d.toTimeString()); // logs 14:39:07 GMT-0600 (PDT)
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.9.5.4', 'Date.prototype.toTimeString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.totimestring', 'Date.prototype.toTimeString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.totimestring', 'Date.prototype.toTimeString')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/error/index.html b/files/id/web/javascript/reference/global_objects/error/index.html new file mode 100644 index 0000000000..c0fc3cec6f --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/error/index.html @@ -0,0 +1,231 @@ +--- +title: Error +slug: Web/JavaScript/Reference/Global_Objects/Error +tags: + - Error + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Error +--- +
{{JSRef}}
+ +

Konstruktor Error membuat sebuah objek error. Misal objek Error di lontarkan ketika terjadi runtime error. Objek Error juga dapat digunakan sebagai objek dasar dengan pengecualian yang ditentukan pengguna. Berikut untuk standard jenis built-in error.

+ +

Sintaks

+ +
new Error([message[, fileName[, lineNumber]]])
+ +

Parameter

+ +
+
message
+
Optional. Human-readable description of the error.
+
fileName {{non-standard_inline}}
+
Optional. The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that called the Error() constructor.
+
lineNumber {{non-standard_inline}}
+
Optional. The value for the lineNumber property on the created Error object. Defaults to the line number containing the Error() constructor invocation.
+
+ +

Description

+ +

Runtime errors result in new Error objects being created and thrown.

+ +

This page documents the use of the Error object itself and its use as a constructor function. For a list of properties and methods inherited by Error instances, see {{jsxref("Error.prototype")}}.

+ +

Error types

+ +

Besides the generic Error constructor, there are six other core error constructors in JavaScript. For client-side exceptions, see Exception Handling Statements.

+ +
+
{{jsxref("EvalError")}}
+
Creates an instance representing an error that occurs regarding the global function {{jsxref("Global_Objects/eval", "eval()")}}.
+
{{jsxref("InternalError")}} {{non-standard_inline}}
+
Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
+
{{jsxref("RangeError")}}
+
Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
+
{{jsxref("ReferenceError")}}
+
Creates an instance representing an error that occurs when de-referencing an invalid reference.
+
{{jsxref("SyntaxError")}}
+
Creates an instance representing a syntax error that occurs while parsing code in {{jsxref("Global_Objects/eval", "eval()")}}.
+
{{jsxref("TypeError")}}
+
Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
+
{{jsxref("URIError")}}
+
Creates an instance representing an error that occurs when {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} or {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} are passed invalid parameters.
+
+ +

Properties

+ +
+
{{jsxref("Error.prototype")}}
+
Allows the addition of properties to Error instances.
+
+ +

Methods

+ +

The global Error object contains no methods of its own, however, it does inherit some methods through the prototype chain.

+ +

Error instances

+ +
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Description')}}
+ +

Properties

+ +
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Properties')}}
+ +

Methods

+ +
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Methods')}}
+ +

Examples

+ +

Throwing a generic error

+ +

Usually you create an Error object with the intention of raising it using the {{jsxref("Statements/throw", "throw")}} keyword. You can handle the error using the {{jsxref("Statements/try...catch", "try...catch")}} construct:

+ +
try {
+  throw new Error('Whoops!');
+} catch (e) {
+  console.log(e.name + ': ' + e.message);
+}
+
+ +

Handling a specific error

+ +

You can choose to handle only specific error types by testing the error type with the error's {{jsxref("Object.prototype.constructor", "constructor")}} property or, if you're writing for modern JavaScript engines, {{jsxref("Operators/instanceof", "instanceof")}} keyword:

+ +
try {
+  foo.bar();
+} catch (e) {
+  if (e instanceof EvalError) {
+    console.log(e.name + ': ' + e.message);
+  } else if (e instanceof RangeError) {
+    console.log(e.name + ': ' + e.message);
+  }
+  // ... etc
+}
+
+ +

Custom Error Types

+ +

You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler. The common way to do this is demonstrated below.

+ +
+

Note that the thrown MyError will report incorrect lineNumber and fileName at least in Firefox.

+
+ +

See also the "What's a good way to extend Error in JavaScript?" discussion on Stackoverflow.

+ +
// Create a new object, that prototypically inherits from the Error constructor
+function MyError(message) {
+  this.name = 'MyError';
+  this.message = message || 'Default Message';
+  this.stack = (new Error()).stack;
+}
+MyError.prototype = Object.create(Error.prototype);
+MyError.prototype.constructor = MyError;
+
+try {
+  throw new MyError();
+} catch (e) {
+  console.log(e.name);     // 'MyError'
+  console.log(e.message);  // 'Default Message'
+}
+
+try {
+  throw new MyError('custom message');
+} catch (e) {
+  console.log(e.name);     // 'MyError'
+  console.log(e.message);  // 'custom message'
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.11', 'Error')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error-objects', 'Error')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/error/name/index.html b/files/id/web/javascript/reference/global_objects/error/name/index.html new file mode 100644 index 0000000000..6644fff80a --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/error/name/index.html @@ -0,0 +1,119 @@ +--- +title: Error.prototype.name +slug: Web/JavaScript/Reference/Global_Objects/Error/name +tags: + - Error + - JavaScript + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Error/name +--- +
{{JSRef}}
+ +

Properti name menyatakan nama dari jenis error. Nilai awalnya adalah "Error".

+ +

Deskripsi

+ +

Secara default, misalnya {{jsxref("Error")}} diberi nama "Error". Properti name, sebagai tambahan utuk properti {{jsxref("Error.prototype.message", "message")}}, digunakan oleh method {{jsxref("Error.prototype.toString()")}} untuk membuat sebuah pernyataan dalam bentuk string yang menyatakan error.

+ +

Contoh

+ +

Menggunakan custom error

+ +
var e = new Error('Inputan tidak lengkap'); // e.name nilainya 'Error'
+
+e.name = 'ParseError';
+throw e;
+// e.toString() akan mengembalikan 'ParseError: Inputan tidak lengkap'
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.11.4.2', 'Error.prototype.name')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error.prototype.name', 'Error.prototype.name')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error.prototype.name', 'Error.prototype.name')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{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}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/function/displayname/index.html b/files/id/web/javascript/reference/global_objects/function/displayname/index.html new file mode 100644 index 0000000000..952014983b --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/function/displayname/index.html @@ -0,0 +1,123 @@ +--- +title: Function.displayName +slug: Web/JavaScript/Reference/Global_Objects/Function/displayName +tags: + - Function + - JavaScript + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Function/displayName +--- +
{{JSRef}} {{non-standard_header}}
+ +

Properti function.displayName mengembalikan nama fungsi.

+ +

Deskripsi

+ +

Ketika didefinisikan, properti displayName mengembalikan nama dari sebuah fungsi:

+ +
function doSomething() {}
+
+console.log(doSomething.displayName); // "undefined"
+
+var popup = function(content) { console.log(content); };
+
+popup.displayName = 'Show Popup';
+
+console.log(popup.displayName); // "Show Popup"
+
+ +

Anda bisa mendefinisikan sebuah fungsi dengan sebuah display nama di {{jsxref("Functions", "function expression", "", 1)}}:

+ +
var object = {
+  someMethod: function() {}
+};
+
+object.someMethod.displayName = 'someMethod';
+
+console.log(object.someMethod.displayName); // logs "someMethod"
+
+try { someMethod } catch(e) { console.log(e); }
+// ReferenceError: someMethod is not defined
+
+ +

Anda bisa merubah  displayName dari sebuah fungsi secara dinamis:

+ +
var object = {
+  // anonymous
+  someMethod: function(value) {
+    this.displayName = 'someMethod (' + value + ')';
+  }
+};
+
+console.log(object.someMethod.displayName); // "undefined"
+
+object.someMethod('123')
+console.log(object.someMethod.displayName); // "someMethod (123)"
+
+ +

Contoh

+ +

Biasanya lebih banyak digunakan dengan console dan profiler melalui {{jsxref("Function.name", "func.name")}} untuk menampilkan nama function.

+ +

Dengan menuliskan kode berikut, maka seharusnya akan menampilkan "function My Function()":

+ +
var a = function() {};
+a.displayName = 'My Function';
+
+a; // "function My Function()"
+ +

Spesifikasi

+ +

Bukan bagian dari spesifikasi.

+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(13)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/id/web/javascript/reference/global_objects/function/index.html b/files/id/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..49d1c1a114 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,241 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - Constructor + - Function + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

Konstruktor Function membuat sebuah objek Function baru. Di Javascript setiap fungsi adalah sebuah objek Function.

+ +

Sintaks

+ +
new Function ([arg1[, arg2[, ...argN]],] functionBody)
+ +

Parameter

+ +
+
arg1, arg2, ... argN
+
Nama yang akan digunakan oleh fungsi sebagai nama formal argumen. Masing-masing harus berupa string yang sesuai dengan identifier JavaScript yang valid atau daftar string dipisahkan dengan koma; contohnya "x", "theValue", atau "a,b".
+
functionBody
+
String berisi sintaks JavaScript yang terdiri dari definisi fungsi.
+
+ +

Deskripsi

+ +

Objek  Function yang dibuat dengan konstruktor Function diuraikan ketika fungsi dibuat. Hal tersebut kurang efisien dibandingkan dengan mendeklarasikan fungsi dengan function expression atau function statement dan memanggilnya dengan kode Anda, karena fungsi-fungsi tersebut diuraikan dengan sisa kode.

+ +

Semua argumen yang diteruskan ke fungsi diperlakukan sebagai nama identifier parameter dalam fungsi yang akan dibuat, dalam urutan yang dilewatkan.

+ +
+

Catatan: Fungsi dibuat dengan konstruktor Function  jangan membuat penutup pada konteks kreasi mereka; Mereka selalu dibuat dalam ruang lingkup global. Saat menjalankannya, mereka hanya bisa mengakses variabel lokal mereka sendiri dan variabel global, bukan variabel dari ruang lingkup dimana konstruktor Function dipanggil. Berbeda dari menggunakan {{jsxref("eval")}} dengan kode untuk fungsi ekspresi.

+
+ +

memanggil konstruktor Function sebagai sebuah fungsi (tanpa menggunakan operatur baru) mempunyai efek yang sama seperti memanggilnya sebagai konstruktor

+ +

Properti dan Method Function

+ +

Objek Function global tidak memiliki method atau properti sendiri. Namun, fungsi itu sendiri mewarisi beberapa method dan properti melalui prototipe dari {{jsxref("Function.prototype")}}.

+ +

Objek prototipe Function

+ +

Properti

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
+ +

Method

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
+ +

Function instances

+ +

Function instances mewarisi method dan properti dari {{jsxref("Function.prototype")}}. Seperti halnya semua konstruktor, Anda dapat mengubah objek prototipe konstruktor untuk membuat perubahan pada semua Function instances.

+ +

Contoh

+ +

Menentukan arguman dengan konstruktor Function

+ +

Dibawah ini kode untuk membuat sebuah objek Function yang menggunakan dua argumen.

+ +
// Contoh dapat dijalankan langsung di konsol JavaScript Anda
+
+// Buat fungsi yang mengambil dua argumen dan mengembalikan jumlah argumen tersebut
+var adder = new Function('a', 'b', 'return a + b');
+
+// Memanggil fungsi
+adder(2, 6);
+// > 8
+
+ +

Argumen "a" dan "b" adalah nama argumen formal yang digunakan pada function body "return a + b".

+ +

Pintasan rekursif untuk memofikasi DOM secara masif

+ +

Membuat fungsi dengan konstruktor Function adalah salah satu cara dinamis untuk membuat objek baru dengan beberapa kode yang dapat dieksekusi ke dalam lingkup global dari suatu fungsi. Contoh berikut (pintasan rekursif untuk memodifikasi DOM secara masif) tidak dimungkinkan tanpa permintaan konstruktor Function untuk setiap kueri baru jika Anda ingin menghindari penutup tiap fungsi.

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example - a recursive shortcut to massively modify the DOM</title>
+<script type="text/javascript">
+var domQuery = (function() {
+  var aDOMFunc = [
+    Element.prototype.removeAttribute,
+    Element.prototype.setAttribute,
+    CSSStyleDeclaration.prototype.removeProperty,
+    CSSStyleDeclaration.prototype.setProperty
+  ];
+
+  function setSomething(bStyle, sProp, sVal) {
+    var bSet = Boolean(sVal), fAction = aDOMFunc[bSet | bStyle << 1],
+        aArgs = Array.prototype.slice.call(arguments, 1, bSet ? 3 : 2),
+        aNodeList = bStyle ? this.cssNodes : this.nodes;
+
+    if (bSet && bStyle) { aArgs.push(''); }
+    for (
+      var nItem = 0, nLen = this.nodes.length;
+      nItem < nLen;
+      fAction.apply(aNodeList[nItem++], aArgs)
+    );
+    this.follow = setSomething.caller;
+    return this;
+  }
+
+  function setStyles(sProp, sVal) { return setSomething.call(this, true, sProp, sVal); }
+  function setAttribs(sProp, sVal) { return setSomething.call(this, false, sProp, sVal); }
+  function getSelectors() { return this.selectors; };
+  function getNodes() { return this.nodes; };
+
+  return (function(sSelectors) {
+    var oQuery = new Function('return arguments.callee.follow.apply(arguments.callee, arguments);');
+    oQuery.selectors = sSelectors;
+    oQuery.nodes = document.querySelectorAll(sSelectors);
+    oQuery.cssNodes = Array.prototype.map.call(oQuery.nodes, function(oInlineCSS) { return oInlineCSS.style; });
+    oQuery.attributes = setAttribs;
+    oQuery.inlineStyle = setStyles;
+    oQuery.follow = getNodes;
+    oQuery.toString = getSelectors;
+    oQuery.valueOf = getNodes;
+    return oQuery;
+  });
+})();
+</script>
+</head>
+
+<body>
+
+<div class="testClass">Lorem ipsum</div>
+<p>Some text</p>
+<div class="testClass">dolor sit amet</div>
+
+<script type="text/javascript">
+domQuery('.testClass')
+  .attributes('lang', 'en')('title', 'Risus abundat in ore stultorum')
+  .inlineStyle('background-color', 'black')('color', 'white')('width', '100px')('height', '50px');
+</script>
+</body>
+
+</html>
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
+ +

Kesesuaian Browser

+ +
{{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}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/function/length/index.html b/files/id/web/javascript/reference/global_objects/function/length/index.html new file mode 100644 index 0000000000..901c11b336 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/function/length/index.html @@ -0,0 +1,148 @@ +--- +title: Function.length +slug: Web/JavaScript/Reference/Global_Objects/Function/length +tags: + - Function + - JavaScript + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Function/length +--- +
{{JSRef}}
+ +

Properti length menentukan jumlah argumen yang diharapkan oleh fungsi.

+ +
{{js_property_attributes(0,0,1)}}
+ +

Deskripsi

+ +

length merupakan properti dari objek fungsi, dan mengindikasikan berapa banyak argumen yang diharapkan fungsi, mis. jumlah parameter formal. Jumlah ini mengesampingkan {{jsxref("rest_parameters", "rest parameter", "", 1)}}. Sebaliknya, {{jsxref("Functions_and_function_scope/arguments/length", "arguments.length")}} adalah lokal untuk fungsi dan memberikan jumlah argumen sebenarnya ke fungsi.

+ +

Properti data dari constructor Function

+ +

Construktor {{jsxref("Function")}} sendiri adalah objek {{jsxref("Function")}}. data properti length bernilai 1. Properti atribut: Writable: false, Enumerable: false, Configurable: true.

+ +

Properti dari Function prototype object

+ +

Panjang properti dari prototype objek {{jsxref("Function")}} bernilai 0.

+ +

Contoh

+ +
console.log(Function.length); /* 1 */
+
+console.log((function()        {}).length); /* 0 */
+console.log((function(a)       {}).length); /* 1 */
+console.log((function(a, b)    {}).length); /* 2 etc. */
+
+console.log((function(...args) {}).length);
+// 0, rest parameter is not counted
+
+console.log((function(a, b = 1, c) {}).length);
+// 1, only parameters before the first one with
+// a default value is counted
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ES6')}}The configurable attribute of this property is now true.
{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatGeckoDesktop(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/function/name/index.html b/files/id/web/javascript/reference/global_objects/function/name/index.html new file mode 100644 index 0000000000..1a35d62020 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/function/name/index.html @@ -0,0 +1,191 @@ +--- +title: Function.name +slug: Web/JavaScript/Reference/Global_Objects/Function/name +tags: + - ECMAScript6 + - Function + - JavaScript + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Function/name +--- +
{{JSRef}}
+ +

Properti function.name mengembalikan nama fungsi.

+ +
{{js_property_attributes(0,0,1)}}
+ +
Perlu di ingat bahwa ini di dalam non-standard, implementasi pre-ES6 atribut configurable juga false.
+ +

Deskripsi

+ +

Properti name property mengembalikan nama sebuah fungsi , atau (sebelum implementasi ES6) string kosong untuk anonymous functions:

+ +
function doSomething() {}
+
+console.log(doSomething.name); // logs "doSomething"
+
+ +

Fungsi di buat menggunakan sintaks new Function(...) atau hanya Function(...) memiliki properti name di set empty string. Pada contoh anonymous functions dibuat, sehingga name mengembalikan empty string:

+ +
var f = function() {};
+var object = {
+  someMethod: function() {}
+};
+
+console.log(f.name == ''); // true
+console.log(object.someMethod.name == ''); // also true
+
+ +

Browser yang mengimplementasikan fungsi ES6 mengambil nama dari anonymous function dari posisi syntactic-nya. Contoh:

+ +
var f = function() {};
+console.log(f.name); // "f"
+ +

Anda bisa mendefinisikan sebuah fungsi dengan nama di {{jsxref("Operators/Function", "function expression", "", 1)}}:

+ +
var object = {
+  someMethod: function object_someMethod() {}
+};
+console.log(object.someMethod.name); // logs "object_someMethod"
+
+try { object_someMethod } catch(e) { console.log(e); }
+// ReferenceError: object_someMethod is not defined
+
+ +

Anda tidak bisa mengubah nama fungsi, Properti ini hanya bisa dibaca:

+ +
var object = {
+  // anonymous
+  someMethod: function() {}
+};
+
+object.someMethod.name = 'someMethod';
+console.log(object.someMethod.name); // empty string, someMethod is anonymous
+
+ +

Untuk mengubah, anda perlu menggunakan {{jsxref("Object.defineProperty()")}}.

+ +

Contoh

+ +

Anda bisa menggunakan obj.constructor.name untuk memeriksa "class" dari sebuah objek:

+ +
function a() {}
+
+var b = new a();
+
+console.log(b.constructor.name); // logs "a"
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-name', 'name')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-name', 'name')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(33.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatChrome(43.0)}}{{CompatGeckoDesktop(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Inferred names on anonymous functions{{CompatChrome(51.0)}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Inferred names on anonymous functions{{CompatNo}}{{CompatChrome(51.0)}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(51.0)}}
+
+ +

[1] See {{bug(883377)}}.

diff --git a/files/id/web/javascript/reference/global_objects/function/prototype/index.html b/files/id/web/javascript/reference/global_objects/function/prototype/index.html new file mode 100644 index 0000000000..d522a363e0 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/function/prototype/index.html @@ -0,0 +1,143 @@ +--- +title: Function.prototype +slug: Web/JavaScript/Reference/Global_Objects/Function/prototype +tags: + - Function + - JavaScript + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

Properti Function.prototype mewakili objek properti {{jsxref("Function")}} .

+ +

Deskripsi

+ +

Objek {{jsxref("Function")}} turunan dari Function.prototypeFunction.prototype tidak dapat di ubah.

+ +

Properti

+ +
+
{{jsxref("Function.arguments")}} {{deprecated_inline}}
+
Sebuah array berdasakan argumen yang diberikan ke sebuah fungsi. Ini telah diabaikan sebagai properti dari {{jsxref("Function")}}, gunakan objek {{jsxref("Functions/arguments", "arguments")}} yang tersedia di dalam fungsi saja.
+
{{jsxref("Function.arity")}} {{obsolete_inline}}
+
Digunakan untuk menentukan jumlah argumen yang diperlukan fungsi, tapi telah dihapus. Gunakan properti {{jsxref("Function.length", "length")}}.
+
{{jsxref("Function.caller")}} {{non-standard_inline}}
+
Menentukan fungsi yang dipanggil oleh fungsi yang sedang dijalankan saat ini.
+
{{jsxref("Function.length")}}
+
Menentukan jumlah argumen yang diperlukan oleh fungsi.
+
{{jsxref("Function.name")}}
+
Nama dari fungsi.
+
{{jsxref("Function.displayName")}} {{non-standard_inline}}
+
Tampilan nama fungsi.
+
Function.prototype.constructor
+
Menentukan fungsi yang membuat objek prototype. Lihat {{jsxref("Object.prototype.constructor")}} untuk lebih detailnya.
+
+ +

Method

+ +
+
{{jsxref("Function.prototype.apply()")}}
+
Memanggil fungsi dan menentukan nilai this berdasar nilai yang diberikan, argument bisa ditambahkan sebagai objek {{jsxref("Array")}}.
+
{{jsxref("Function.prototype.bind()")}}
+
Membuat fungsi baru dimana, ketika dipanggil, memiliki this yang diberi nilai yang tersedia, dengan urutan tertentu sesudah nilai yang tersedia ketika fungsi di jalankan.
+
{{jsxref("Function.prototype.call()")}}
+
Memanggil (menjalankan) sebuah fungsi dan memberi nilai this dari nilai yang tersedia, argumen bisa ditambahkan sebagaimana mestinya.
+
{{jsxref("Function.prototype.isGenerator()")}} {{non-standard_inline}}
+
Mengembalikan true jika fungsi adalah sebuah generator; selain itu akan mengembalikan  nilai false.
+
{{jsxref("Function.prototype.toSource()")}} {{non-standard_inline}}
+
Mengembalikan string berdasarkan kode sumber dari fungsi. Mengesampingkan method {{jsxref("Object.prototype.toSource")}}.
+
{{jsxref("Function.prototype.toString()")}}
+
Mengembalikan string berdasarkan kode sumber dari fungsi, mengesampingkan method {{jsxref("Object.prototype.toString")}}.
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1
{{SpecName('ES5.1', '#sec-15.3.5.2', 'Function.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-prototype', 'Function.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-instances-prototype', 'Function.prototype')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{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}}
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/index.html b/files/id/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..5259bde5b8 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/index.html @@ -0,0 +1,189 @@ +--- +title: Global Objek +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects +--- +
{{jsSidebar("Objects")}}
+ +

Pada bagian ini membahas standar javascript, objek built-in, Termasuk didalamnya method dan properti.

+ +
+

Istilah "Global Objek" (atau standar objek built-in)disini bukan berarti Global Objek. Disini global objek di artikan sebagai objek pada scope global (tapi hanya jika ECMAScript 5 mode strict tidak digunakan; pada kasus ini mengembalikan {{jsxref("undefined")}}).  Global objek sendiri bisa di akses menggunakan operator {{jsxref("Operators/this", "this")}} pada lingkup global. Bahkan, lingkup global terdiri dari properti pada global objek, termasuk peoperti yang diwariskan, jika ada.

+ +

Objek lain di lingkup global salah satunya dibuat oleh user script atau disediakan oleh aplikasi host. Objek host tersedia di konteks browser, didokumentasi di Referensi API. Untuk informasi lengkap tentang perbedaan antara DOM dan inti JavaScript, lihat Gambaran teknologi javaScript.

+ +

Objek standar berdasarkan kategori

+ +

Properti nilai

+ +

Properti global ini mengembalikan nilai simple; tidak memiliki properti ataupun method.

+ +
    +
  • {{jsxref("Global_Objects/Infinity", "Infinity")}}
  • +
  • {{jsxref("Global_Objects/NaN", "NaN")}}
  • +
  • {{jsxref("Global_Objects/undefined", "undefined")}}
  • +
  • {{jsxref("Global_Objects/null", "null")}} literal
  • +
+ +

Properti fungsi

+ +

Fungsi global—fungsi yang di panggil secara global bukan pada objek — langsung mengembalikan nilai ke pemenggil.

+ +
    +
  • {{jsxref("Global_Objects/eval", "eval()")}}
  • +
  • {{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}
  • +
  • {{jsxref("Global_Objects/isFinite", "isFinite()")}}
  • +
  • {{jsxref("Global_Objects/isNaN", "isNaN()")}}
  • +
  • {{jsxref("Global_Objects/parseFloat", "parseFloat()")}}
  • +
  • {{jsxref("Global_Objects/parseInt", "parseInt()")}}
  • +
  • {{jsxref("Global_Objects/decodeURI", "decodeURI()")}}
  • +
  • {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}
  • +
  • {{jsxref("Global_Objects/encodeURI", "encodeURI()")}}
  • +
  • {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}
  • +
  • {{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}
  • +
  • {{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}
  • +
+ +

Fundamental objek

+ +

Ini merupakan fundamental, objek dasar berdasarkan pada semua objek lain yang didasarkan. Ini termasuk objek yang mewakili objek umum, fungsi dan error.

+ +
    +
  • {{jsxref("Global_Objects/Object", "Object")}}
  • +
  • {{jsxref("Global_Objects/Function", "Function")}}
  • +
  • {{jsxref("Global_Objects/Boolean", "Boolean")}}
  • +
  • {{jsxref("Global_Objects/Symbol", "Symbol")}}
  • +
  • {{jsxref("Global_Objects/Error", "Error")}}
  • +
  • {{jsxref("Global_Objects/EvalError", "EvalError")}}
  • +
  • {{jsxref("Global_Objects/InternalError", "InternalError")}}
  • +
  • {{jsxref("Global_Objects/RangeError", "RangeError")}}
  • +
  • {{jsxref("Global_Objects/ReferenceError", "ReferenceError")}}
  • +
  • {{jsxref("Global_Objects/SyntaxError", "SyntaxError")}}
  • +
  • {{jsxref("Global_Objects/TypeError", "TypeError")}}
  • +
  • {{jsxref("Global_Objects/URIError", "URIError")}}
  • +
+ +

Nomor dan tanggal

+ +

Objek dasar yang mewakili angka, tanggal dan kalkulasi matematik.

+ +
    +
  • {{jsxref("Global_Objects/Number", "Number")}}
  • +
  • {{jsxref("Global_Objects/Math", "Math")}}
  • +
  • {{jsxref("Global_Objects/Date", "Date")}}
  • +
+ +

Pengolah teks

+ +

Objek yang mewakili string dan dukungan untuk memanipulasinya.

+ +
    +
  • {{jsxref("Global_Objects/String", "String")}}
  • +
  • {{jsxref("Global_Objects/RegExp", "RegExp")}}
  • +
+ +

Koleksi Index

+ +

Objek ini mewakili koleksi data berdasarkan nilai index. Ini termasuk (jenis) array dan konstruksi mirip array (array-like).

+ +
    +
  • {{jsxref("Global_Objects/Array", "Array")}}
  • +
  • {{jsxref("Global_Objects/Int8Array", "Int8Array")}}
  • +
  • {{jsxref("Global_Objects/Uint8Array", "Uint8Array")}}
  • +
  • {{jsxref("Global_Objects/Uint8ClampedArray", "Uint8ClampedArray")}}
  • +
  • {{jsxref("Global_Objects/Int16Array", "Int16Array")}}
  • +
  • {{jsxref("Global_Objects/Uint16Array", "Uint16Array")}}
  • +
  • {{jsxref("Global_Objects/Int32Array", "Int32Array")}}
  • +
  • {{jsxref("Global_Objects/Uint32Array", "Uint32Array")}}
  • +
  • {{jsxref("Global_Objects/Float32Array", "Float32Array")}}
  • +
  • {{jsxref("Global_Objects/Float64Array", "Float64Array")}}
  • +
+ +

Koleksi keyed

+ +

Objek ini merupakan koleksi yang menggunakan key; mengandung unsur yang iterable di urutan penyisipan.

+ +
    +
  • {{jsxref("Map")}}
  • +
  • {{jsxref("Set")}}
  • +
  • {{jsxref("WeakMap")}}
  • +
  • {{jsxref("WeakSet")}}
  • +
+ +

Koleksi vektor

+ +

{{Glossary("SIMD")}} tipe data vector adalah objek dimana data diatur arahnya.

+ +
    +
  • {{jsxref("SIMD")}} {{experimental_inline}}
  • +
  • {{jsxref("Float32x4", "SIMD.Float32x4")}} {{experimental_inline}}
  • +
  • {{jsxref("Float64x2", "SIMD.Float64x2")}} {{experimental_inline}}
  • +
  • {{jsxref("Int8x16", "SIMD.Int8x16")}} {{experimental_inline}}
  • +
  • {{jsxref("Int16x8", "SIMD.Int16x8")}} {{experimental_inline}}
  • +
  • {{jsxref("Int32x4", "SIMD.Int32x4")}} {{experimental_inline}}
  • +
  • {{jsxref("Uint8x16", "SIMD.Uint8x16")}} {{experimental_inline}}
  • +
  • {{jsxref("Uint16x8", "SIMD.Uint16x8")}} {{experimental_inline}}
  • +
  • {{jsxref("Uint32x4", "SIMD.Uint32x4")}} {{experimental_inline}}
  • +
  • {{jsxref("Bool8x16", "SIMD.Bool8x16")}} {{experimental_inline}}
  • +
  • {{jsxref("Bool16x8", "SIMD.Bool16x8")}} {{experimental_inline}}
  • +
  • {{jsxref("Bool32x4", "SIMD.Bool32x4")}} {{experimental_inline}}
  • +
  • {{jsxref("Bool64x2", "SIMD.Bool64x2")}} {{experimental_inline}}
  • +
+ +

Data terstruktur

+ +

Objek ini mewakili dan berinteraksi dengan buffer data terstruktur dan data yang dikodekan menggunakan JavaScript Object Notation (JSON).

+ +
    +
  • {{jsxref("ArrayBuffer")}}
  • +
  • {{jsxref("SharedArrayBuffer")}} {{experimental_inline}}
  • +
  • {{jsxref("Atomics")}} {{experimental_inline}}
  • +
  • {{jsxref("DataView")}}
  • +
  • {{jsxref("JSON")}}
  • +
+ +

Kontrol objek abstraksi 

+ +
    +
  • {{jsxref("Promise")}}
  • +
  • {{jsxref("Generator")}}
  • +
  • {{jsxref("GeneratorFunction")}}
  • +
+ +

Refleksi (Pantulan)

+ +
    +
  • {{jsxref("Reflect")}}
  • +
  • {{jsxref("Proxy")}}
  • +
+ +

Internasionalisasi

+ +

Penambahan inti ECMAScript untuk fungsi bahasa-sensitif.

+ +
    +
  • {{jsxref("Intl")}}
  • +
  • {{jsxref("Global_Objects/Collator", "Intl.Collator")}}
  • +
  • {{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}
  • +
  • {{jsxref("Global_Objects/NumberFormat", "Intl.NumberFormat")}}
  • +
+ +

Objek Non-standar

+ +
    +
  • {{jsxref("Iterator")}} {{non-standard_inline}}
  • +
  • {{jsxref("ParallelArray")}} {{non-standard_inline}}
  • +
  • {{jsxref("StopIteration")}} {{non-standard_inline}}
  • +
+ +

Lainnya

+ + +
+ +

 

diff --git a/files/id/web/javascript/reference/global_objects/isnan/index.html b/files/id/web/javascript/reference/global_objects/isnan/index.html new file mode 100644 index 0000000000..b7a6774528 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/isnan/index.html @@ -0,0 +1,186 @@ +--- +title: isNaN() +slug: Web/JavaScript/Reference/Global_Objects/isNaN +translation_of: Web/JavaScript/Reference/Global_Objects/isNaN +--- +
{{jsSidebar("Objects")}}
+ +

Fungsi isNaN() menentukan apakah nilai adalah sebuah {{jsxref("NaN")}} atau bukan. Catatan: pemaksaan pada fungsi isNaN memiliki aturan yang menarik. Anda mungkin ingin menggunakan {{jsxref("Number.isNaN()")}}, seperti yang didefinisikan dalam ECMAScript 2015.

+ +

Syntax

+ +
isNaN(value)
+ +

Parameters

+ +
+
value
+
Nilai yang akan di uji.
+
+ +

Return value

+ +

true Jika nilai yang di uji adalah {{jsxref("NaN")}}; jika tidak, false.

+ +

Deskripsi

+ +

Kebutuhan akan fungsi isNaN

+ +

Mungkin tidak seperti nilai lainnya dalam javascript, Ini tidak memungkinkan untuk mengandalkan operator persamaan (== dan ===) untuk menentukan bahwa nilai adalah {{jsxref("NaN")}} atau bukan, karena NaN == NaN dan NaN === NaN mengevaluasi ke false. Oleh karena itu, diperlukan adanya fungsi isNaN.

+ +

Asal Mula Nilai NaN

+ +

NilaiNaN dihasilkan saat operasi aritmatika menghasilkan nilai undefined atau unrepresentable. Nilai tersebut tidak harus mewakili kondisi overflowNaN juga dihasilkan dari percobaan pemaksaan ke nilai numerik dari nilai non-numerik yang tidak memiliki nilai numerik primitif yang tersedia.

+ +

Misalnya, membagi nol dengan nol menghasilkan sebuah NaN — namun membagi angka lain dengan nol tidak menghasilkan sebuah NaN.

+ +

Perilaku Khusus yang membingungkan

+ +

Karena versi paling awal dari spesifikasi fungsi isNaN , perilaku untuk argumen non-numerik menjadi membingungkan. Ketika argumen ke fungsi isNaN bukan bertipe Number, Nilainya akan dipaksakan terlebih dahulu ke tipe Number. Nilai yang dihasilkan kemudian diuji untuk menentukan apakah itu {{jsxref("NaN")}}. Jadi untuk non-angka yang jika dipaksakan pada hasil numerik menghasilkan nilai numerik non-NaN (terutama string kosong dan primitif boolean, yang jika dipaksakan memberi nilai numerik nol atau satu), nilai pengembalian "false" mungkin tidak terduga; String kosong, misalnya, pastinya "not a number". Kebingungan itu berawal dari kenyataan bahwa istilah "not a number", memiliki arti khusus untuk angka yang diwakili sebagai nilai floating-point IEEE-754. Fungsi harus diinterpretasikan sebagai penjawab pertanyaan, "apakah nilai ini, jika dipaksakan pada nilai numerik, nilai IEEE-754 'Not A Number'?"

+ +

Versi terbaru dari ECMAScript (ES2015) berisi fungsi {{jsxref("Number.isNaN()")}}. Number.isNaN(x) akan menjadi cara yang andal untuk menguji apakah x adalah NaN atau bukan. Bahkan dengan Number.isNaN, namun arti NaN tetap merupakan makna numerik yang tepat, dan bukan sekadar, "not a number". Sebagai alternatif, untuk ketidakhadiran Number.isNaN, ekspresi (x != x) adalah cara yang lebih dapat diandalkan untuk menguji apakah variabel x adalah NaN atau bukan, karena hasilnya tidak sesuai dengan false positive yang membuat isNaN tidak dapat diandalkan.

+ +

Anda bisa memikirkan isNaN sebagai:

+ +
var isNaN = function(value) {
+    return Number.isNaN(Number(value));
+}
+ +

Contoh

+ +
isNaN(NaN);       // true
+isNaN(undefined); // true
+isNaN({});        // true
+
+isNaN(true);      // false
+isNaN(null);      // false
+isNaN(37);        // false
+
+// strings
+isNaN('37');      // false: "37" dikonversi ke nomor 37 yang mana bukan NaN
+isNaN('37.37');   // false: "37.37" dikonversi ke nomor 37.37 yang mana bukan NaN
+isNaN('123ABC');  // true:  parseInt("123ABC") adalah 123 namun Number("123ABC") adalah NaN
+isNaN('');        // false: string kosing dikonversi ke 0 yang mana bukan NaN
+isNaN(' ');       // false: string dengan spasi dikonversi ke 0 yang mana bukan NaN
+
+// dates
+isNaN(new Date());                // false
+isNaN(new Date().toString());     // true
+
+// Ini adalah false positif dan alasan mengapa NaN tidak sepenuhnya dapat diandalkan
+isNaN('blabla');   // true: "blabla" dikonversi ke nomor.
+                   // Parsing ini sebagai nomor gagal dan mengembalikan NaN
+
+ +

Berguna dalam perilaku khusus

+ +

Ada cara penggunaan yang lebih berorientasi untuk memikirkan isNaN isNaN(): Jika isNaN(x) mengembalikan false, anda bisa menggunakan x dalam ekspresi aritmatika tidak membuat ekspresi mengembalikan NaN. Jika itu mengembalikantrue, x akan membuat setiap ekspresi aritmatika mengembalikan NaN. Ini berarti bahwa dalam JavaScript, isNaN(x) == true setara dengan x - 0 mengembalikan NaN (meskipun di JavaScript x - 0 == NaN selalu mengembalikan false, jadi anda tidak bisa mengujinya). Sebenarnya, isNaN(x), isNaN(x - 0), isNaN(Number(x)), Number.isNaN(x - 0), dan Number.isNaN(Number(x)) selalu kembali sama dan di JavaScriptisNaN(x) hanya bentuk sesingkat mungkin untuk mengungkapkan masing-masing istilah ini.

+ +

Anda dapat menggunakan ini, misalnya, untuk menguji apakah sebuah argumen terhadap suatu fungsi secara aritmatika dapat diolah (dapat digunakan "seperti" angka), atau jika tidak dan Anda harus memberikan nilai default atau yang lainnya. Dengan cara ini Anda dapat memiliki fungsi yang memanfaatkan fleksibilitas penuh JavaScript yang disediakan oleh nilai konversi secara implisit bergantung pada konteks.

+ +

Contoh

+ +
function increment(x) {
+  if (isNaN(x)) x = 0;
+  return x + 1;
+}
+
+// Efek yang sama dengan Number.isNaN():
+function increment(x) {
+  if (Number.isNaN(Number(x))) x = 0;
+  return x + 1;
+}
+
+// Dalam kasus berikut untuk argumen fungsi x,
+// isNaN(x)selalu salah, meski x memang bukan sebuah
+// nomor, namun bisa digunakan seperti itu dalam ekspresi
+// aritmatika
+increment('');            // 1: "" dikonversi ke 0
+increment(new String());  // 1: Objek String yang mewakili string kosong dikonversi menjadi 0
+increment([]);            // 1: [] dikonversi ke 0
+increment(new Array());   // 1: Objek array yang mewakili sebuah array kosong dikonversi menjadi 0
+increment('0');           // 1: "0" dikonversi ke 0
+increment('1');           // 2: "1" dikonversi ke 1
+increment('0.1');         // 1.1: "0.1" dikonversi ke 0.1
+increment('Infinity');    // Infinity: "Infinity" dikonversi ke Infinity
+increment(null);          // 1: null dikonversi ke 0
+increment(false);         // 1: false dikonversi ke 0
+increment(true);          // 2: true dikonversi ke 1
+increment(new Date());    // mengembalikan tanggal/waktu sekarang dalam milidetik ditambah 1
+
+// Dalam kasus berikut untuk argumen fungsi x,
+// isNaN(x) selalu false dan x memang angka
+increment(-1);            // 0
+increment(-0.1);          // 0.9
+increment(0);             // 1
+increment(1);             // 2
+increment(2);             // 3
+// ... dan seterusnya ...
+increment(Infinity);      // Infinity
+
+// Dalam kasus berikut untuk argumen fungsi x,
+// isNaN(x) selalu true dan x benar-benar bukan angka,
+// sehingga fungsi tersebut menggantikannya dengan 0 dan mengembalikan 1
+increment(String);            // 1
+increment(Array);             // 1
+increment('blabla');          // 1
+increment('-blabla');         // 1
+increment(0 / 0);               // 1
+increment('0 / 0');             // 1
+increment(Infinity / Infinity); // 1
+increment(NaN);               // 1
+increment(undefined);         // 1
+increment();                  // 1
+
+// isNaN(x) selalu sama dengan isNaN(Number(x)),
+// namun kehadirannya x adalah wajib disini!
+isNaN(x) == isNaN(Number(x)); // true untuk setiap nilai x, termasuk x == undefined,
+                              // karena isNaN(undefined) == true dan Number(undefined) mengembalikan NaN,
+                              // namun ...
+isNaN() == isNaN(Number());   // false, karena isNaN() == true dan Number() == 0
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.2.4', 'isNaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isnan-number', 'isNaN')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-isnan-number', 'isNaN')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.isNaN")}}

+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/json/index.html b/files/id/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..4f07030358 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,243 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +
{{JSRef}}
+ +

Didalam object JSON terdapat banyak method untuk memparse JavaScript Object Notation ({{glossary("JSON")}}) dan mengkonversi nilai ke JSON. Hal ini tidak dapat di gunakan atau dibangun, dan selain dari kedua sifat method tersebut tidak memiliki fungsi tersendiri.

+ +

Deskripsi

+ +

JavaScript Object Notation

+ +

JSON merupakan sebuah syntax untuk menserialisasi objects, array, angka, string, boolean, dan {{jsxref("null")}}. Hal ini dilihat berdasarkan pada syntax  javascript. Akan tetapi terpisah dari dari hal tersebut: beberapa javascript bukanlah JSON, dan beberapa JSON juga tidak dapat dikatakan sebagai Javascript. Lihat juga JSON: The JavaScript subset that isn't.

+ + + + + + + + + + + + + + + + + + + + + + + +
Perbedaan JavaScript dan JSON
Type pada JavaScriptPerbedaan dengan JSON
Object dan ArrayNama properti harus menggunakan string double quotes; tidak diakhiri dengan koma.
AngkaTidak diawali dengan nol; desimal harus di ikuti setidaknya satu digit.
String +

Hanya beberapa karakter tertentu yang menggunakan escape; Kontrol karakter tertentu tidak diperbolehkan; Pemisah baris Unicode (U+2028) dan pemisah paragraf (U+2029) dapat digunakan; string harus menggunakan double-quoted. Lihat contoh dimana {{jsxref("JSON.parse()")}} bisa digunakan dan {{jsxref("SyntaxError")}} dilemparkan ketika mengevaluasi kode sebagai javascript:

+ +
+var kode = '"\u2028\u2029"';
+JSON.parse(kode); // bisa digunakan.
+eval(kode); // gagal!
+
+
+ +

Syntax JSON lengkapnya sebagai berikut:

+ +
JSON = null
+    or true or false
+    or JSONNumber
+    or JSONString
+    or JSONObject
+    or JSONArray
+
+JSONNumber = - PositiveNumber
+          or PositiveNumber
+PositiveNumber = DecimalNumber
+              or DecimalNumber . Digits
+              or DecimalNumber . Digits ExponentPart
+              or DecimalNumber ExponentPart
+DecimalNumber = 0
+             or OneToNine Digits
+ExponentPart = e Exponent
+            or E Exponent
+Exponent = Digits
+        or + Digits
+        or - Digits
+Digits = Digit
+      or Digits Digit
+Digit = 0 through 9
+OneToNine = 1 through 9
+
+JSONString = ""
+          or " StringCharacters "
+StringCharacters = StringCharacter
+                or StringCharacters StringCharacter
+StringCharacter = any character
+                  except " or \ or U+0000 through U+001F
+               or EscapeSequence
+EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
+              or \u HexDigit HexDigit HexDigit HexDigit
+HexDigit = 0 through 9
+        or A through F
+        or a through f
+
+JSONObject = { }
+          or { Members }
+Members = JSONString : JSON
+       or Members , JSONString : JSON
+
+JSONArray = [ ]
+         or [ ArrayElements ]
+ArrayElements = JSON
+             or ArrayElements , JSON
+
+ +

Whitespace yang tidak signifikan dapat digunakan dimanasaja kecuali didalam JSONNumber (angka tidak dipisahkan dengan whitespace) atau JSONString (dimana ditafsirkan sebagai karakter yang sesuai dalam string; atau akan menyebabkan kesalahan). Karakter Tab (U+0009), carriage return (U+000D), line feed (U+000A), dan karakter spasi (U+0020) merupakan karakter whitespace yang valid.

+ +

Method

+ +
+
{{jsxref("JSON.parse()")}}
+
Memparse string sebagai JSON, biasanya mengubah nilai yang diberikan beserta sifatnya, dan mengembalikan nilai.
+
{{jsxref("JSON.stringify()")}}
+
Mengembalikan string JSON berdasarkan nilai spesifik, biasanya termasuk beberapa properti tertentu saja atau mengganti nilai properti secara user-defined.
+
+ +

Polyfill

+ +

Object JSON tidak didukung oleh browser lawas. Anda bisa menyiasatinya dengan memasukkan kode berikut di awal skrip Anda, memungkinkan penggunaan JSON objek dalam implementasi yang secara native tidak mendukung Object JSON (seperti Internet Explorer 6).

+ +

Algoritma berikut adalah tiruan dari objek JSON asli:

+ +
if (!window.JSON) {
+  window.JSON = {
+    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
+    stringify: (function () {
+      var toString = Object.prototype.toString;
+      var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
+      var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
+      var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
+      var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
+      return function stringify(value) {
+        if (value == null) {
+          return 'null';
+        } else if (typeof value === 'number') {
+          return isFinite(value) ? value.toString() : 'null';
+        } else if (typeof value === 'boolean') {
+          return value.toString();
+        } else if (typeof value === 'object') {
+          if (typeof value.toJSON === 'function') {
+            return stringify(value.toJSON());
+          } else if (isArray(value)) {
+            var res = '[';
+            for (var i = 0; i < value.length; i++)
+              res += (i ? ', ' : '') + stringify(value[i]);
+            return res + ']';
+          } else if (toString.call(value) === '[object Object]') {
+            var tmp = [];
+            for (var k in value) {
+              if (value.hasOwnProperty(k))
+                tmp.push(stringify(k) + ': ' + stringify(value[k]));
+            }
+            return '{' + tmp.join(', ') + '}';
+          }
+        }
+        return '"' + value.toString().replace(escRE, escFunc) + '"';
+      };
+    })()
+  };
+}
+
+ +

Lebih kompleks dari polyfills yang banyak dikenal untuk object JSON adalah JSON2 dan JSON3.

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}}Initial definition.
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/json/parse/index.html b/files/id/web/javascript/reference/global_objects/json/parse/index.html new file mode 100644 index 0000000000..5eb3f60424 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/json/parse/index.html @@ -0,0 +1,171 @@ +--- +title: JSON.parse() +slug: Web/JavaScript/Reference/Global_Objects/JSON/parse +tags: + - ECMAScript5 + - JSON + - Method + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse +--- +
{{JSRef}}
+ +

Method JSON.parse() memparse string ke JSON, biasanya mengubah nilai yang dihasilkan oleh parsing.

+ +

Sintaks

+ +
JSON.parse(text[, reviver])
+ +

Parameters

+ +
+
text
+
String yang akan di parse ke JSON. Lihat objek {{jsxref("JSON")}} untuk deskripsi lengkap sintaks JSON.
+
reviver {{optional_inline}}
+
Jika sebuah fungsi, mendeskripsikan bagaimana nilai asli dihasilkan oleh parsing berubah, sebelum dikembalikan.
+
+ +

Pemulangan

+ +

Mengembalikan {{jsxref("Object")}} sesuai dengan teks JSON yang diberikan.

+ +

Lontaran

+ +

Melontarkan pengecualian {{jsxref("SyntaxError")}} jika string yang di parse tidak sesuai JSON.

+ +

Contoh

+ +

Menggunakan JSON.parse()

+ +
JSON.parse('{}');              // {}
+JSON.parse('true');            // true
+JSON.parse('"foo"');           // "foo"
+JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
+JSON.parse('null');            // null
+
+ +

Menggunakan parameter reviver

+ +

Jika reviver telah ditentukan, nilai dihitung dengan parsing transformed sebelum dikembalikan. Khususnya, nilai yang terhitung, dan semua propertinya (dimulai dari properti yang paling bersarang dan berlanjut ke nilai asli), secara individu dijalankan melalui reviver, yang di panggil dengan objek yang berada di dalam properti yang akan diproses sebagai this dan dengan nama properti sebagai string dan nilai properti sebagai argumen. jika fungsi reviver mengembalikan {{jsxref("undefined")}} (tidak mengembalikan nilai, contoh, jika eksekusi gagal di akhir fungsi), properti akan dihapus dari objek. Jika tidak, properti akan didefinisikan ulang sebagai sebuah nilai kembali.

+ +

reviver dipanggil dengan string kosong dan nilai paling atas mengizinkan tranformsi dari nilai paling atas. Jadi untuk menangani kasus ini dengan baik, biasanya dengan mengembalikan nilai yang diberikan, atau JSON.parse() akan mengembalikan {{jsxref("undefined")}}.

+ +
JSON.parse('{"p": 5}', function(k, v) {
+  if (k === '') { return v; } // if topmost value, return it,
+  return v * 2;               // else return v * 2.
+});                           // { p: 10 }
+
+JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', function(k, v) {
+  console.log(k); // log the current property name, the last is "".
+  return v;       // return the unchanged property value.
+});
+
+// 1
+// 2
+// 4
+// 6
+// 5
+// 3
+// ""
+
+ +

JSON.parse() tidak mengizinkan trailing koma

+ +
// both will throw a SyntaxError
+JSON.parse('[1, 2, 3, 4, ]');
+JSON.parse('{"foo" : 1, }');
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Gecko-specific notes

+ +

Pada Gecko 29 {{geckoRelease("29")}}, string JSON yang gagal akan menampilkan pesan kesalahan yang lebih rinci tentang error dalam memparse. Hal ini sangat berguna ketika mendebug data JSON yang besar.

+ +
JSON.parse('[1, 2, 3, 4,]');
+// SyntaxError: JSON.parse: unexpected character at
+// line 1 column 13 of the JSON data
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/map/clear/index.html b/files/id/web/javascript/reference/global_objects/map/clear/index.html new file mode 100644 index 0000000000..2869835e02 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/map/clear/index.html @@ -0,0 +1,109 @@ +--- +title: Map.prototype.clear() +slug: Web/JavaScript/Reference/Global_Objects/Map/clear +translation_of: Web/JavaScript/Reference/Global_Objects/Map/clear +--- +
{{JSRef}}
+ +

Method clear() menghapus semua elemen yang ada pada objek Map.

+ +

Sintaks

+ +
myMap.clear();
+ +

Contoh

+ +

Menggunakan method clear

+ +
var myMap = new Map();
+myMap.set("bar", "baz");
+myMap.set(1, "foo");
+
+myMap.size;       // 2
+myMap.has("bar"); // true
+
+myMap.clear();
+
+myMap.size;       // 0
+myMap.has("bar")  // false
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar38{{CompatGeckoDesktop("19.0")}}11257.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasart{{CompatNo}}38{{CompatGeckoMobile("19.0")}}{{CompatNo}}{{CompatNo}}8
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/map/delete/index.html b/files/id/web/javascript/reference/global_objects/map/delete/index.html new file mode 100644 index 0000000000..ad9d1922b9 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/map/delete/index.html @@ -0,0 +1,114 @@ +--- +title: Map.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/Map/delete +translation_of: Web/JavaScript/Reference/Global_Objects/Map/delete +--- +
{{JSRef}}
+ +

Method  delete() menghapus elemen yang ditentukan dari objek Map.

+ +

Sintaks

+ +
myMap.delete(key);
+ +

Parameter

+ +
+
key
+
Diperlukan. Kunci dari elemen untuk menghapusnya dari objek Map.
+
+ +

Return value

+ +

Mengembalikan nilai true jika elemen yang ada di dalam objek Map ada dan telah dihapus, atau false jika elemen tidak ada.

+ +

Contoh

+ +

Menggunakan method delete

+ +
var myMap = new Map();
+myMap.set("bar", "foo");
+
+myMap.delete("bar"); // Returns true. Berhasil dihapus.
+myMap.has("bar");    // Returns false. Elemen "bar" sudah tidak tersedia.
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar38{{CompatGeckoDesktop("13.0")}}11257.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatNo}}38{{CompatGeckoMobile("13.0")}}{{CompatNo}}{{CompatNo}}8
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/map/index.html b/files/id/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..9e4a93cfa0 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,443 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +tags: + - ECMAScript6 + - JavaScript + - Map + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +
{{JSRef}}
+ +

The Map object is a simple key/value map. Any value (both objects and {{Glossary("Primitive", "primitive values")}}) may be used as either a key or a value.

+ +

Syntax

+ +
new Map([iterable])
+
+ +

Parameters

+ +
+
iterable
+
Iterable is an Array or other iterable object whose elements are key-value pairs (2-element Arrays). Each key-value pair is added to the new Map. null is treated as undefined.
+
+ +

Description

+ +

A Map object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of [key, value] for each iteration.

+ +

Key equality

+ +

Key equality is based on the "same-value" algorithm: NaN is considered the same as NaN (even though NaN !== NaN) and all other values are considered equal according to the semantics of the === operator. In earlier versions of the ECMAScript 6 draft -0 and +0 were considered distinct (even though -0 === +0), this has been changed in later versions and has been adapted in Gecko 29 {{geckoRelease("29")}} ({{bug("952870")}}) and a recent nightly Chrome.

+ +

Objects and maps compared

+ +

{{jsxref("Object", "Objects")}} are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this (and because there were no built-in alternatives), Objects have been used as Maps historically; however, there are important differences between Objects and Maps that make using a Map better:

+ + + +

This does not mean you should use Maps everywhere, objects still are used in most cases. Map instances are only useful for collections, and you should consider adapting your code where you have previously used objects for such. Objects shall be used as records, with fields and methods.
+ If you're still not sure which one to use, ask yourself the following questions:

+ + + +

Those all are signs that you want a Map for a collection. If in contrast you have a fixed amount of keys, operate on them individually, and distinguish between their usage, then you want an object.

+ +

Properties

+ +
+
Map.length
+
The value of the length property is 0.
+
{{jsxref("Map.@@species", "get Map[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("Map.prototype")}}
+
Represents the prototype for the Map constructor. Allows the addition of properties to all Map objects.
+
+ +

Map instances

+ +

All Map instances inherit from {{jsxref("Map.prototype")}}.

+ +

Properties

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}

+ +

Methods

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}

+ +

Examples

+ +

Using the Map object

+ +
var myMap = new Map();
+
+var keyString = "a string",
+    keyObj = {},
+    keyFunc = function () {};
+
+// setting the values
+myMap.set(keyString, "value associated with 'a string'");
+myMap.set(keyObj, "value associated with keyObj");
+myMap.set(keyFunc, "value associated with keyFunc");
+
+myMap.size; // 3
+
+// getting the values
+myMap.get(keyString);    // "value associated with 'a string'"
+myMap.get(keyObj);       // "value associated with keyObj"
+myMap.get(keyFunc);      // "value associated with keyFunc"
+
+myMap.get("a string");   // "value associated with 'a string'"
+                         // because keyString === 'a string'
+myMap.get({});           // undefined, because keyObj !== {}
+myMap.get(function() {}) // undefined, because keyFunc !== function () {}
+
+ +

Using NaN as Map keys

+ +

NaN can also be used as a key. Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works, because NaNs are indistinguishable from each other:

+ +
var myMap = new Map();
+myMap.set(NaN, "not a number");
+
+myMap.get(NaN); // "not a number"
+
+var otherNaN = Number("foo");
+myMap.get(otherNaN); // "not a number"
+
+ +

Iterating Maps with for..of

+ +

Maps can be iterated using a for..of loop:

+ +
var myMap = new Map();
+myMap.set(0, "zero");
+myMap.set(1, "one");
+for (var [key, value] of myMap) {
+  console.log(key + " = " + value);
+}
+// Will show 2 logs; first with "0 = zero" and second with "1 = one"
+
+for (var key of myMap.keys()) {
+  console.log(key);
+}
+// Will show 2 logs; first with "0" and second with "1"
+
+for (var value of myMap.values()) {
+  console.log(value);
+}
+// Will show 2 logs; first with "zero" and second with "one"
+
+for (var [key, value] of myMap.entries()) {
+  console.log(key + " = " + value);
+}
+// Will show 2 logs; first with "0 = zero" and second with "1 = one"
+
+ +

Iterating Maps with forEach()

+ +

Maps can be iterated using the forEach() method:

+ +
myMap.forEach(function(value, key) {
+  console.log(key + " = " + value);
+}, myMap)
+// Will show 2 logs; first with "0 = zero" and second with "1 = one"
+
+ +

Relation with Array objects

+ +
var kvArray = [["key1", "value1"], ["key2", "value2"]];
+
+// Use the regular Map constructor to transform a 2D key-value Array into a map
+var myMap = new Map(kvArray);
+
+myMap.get("key1"); // returns "value1"
+
+// Use the spread operator to transform a map into a 2D key-value Array.
+console.log(uneval([...myMap])); // Will show you exactly the same Array as kvArray
+
+// Or use the spread operator on the keys or values iterator to get
+// an array of only the keys or values
+console.log(uneval([...myMap.keys()])); // Will show ["key1", "key2"]
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-map-objects', 'Map')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support +

{{ CompatChrome(38) }} [1]

+
{{ CompatGeckoDesktop("13") }}11257.1
Constructor argument: new Map(iterable){{ CompatChrome(38) }}{{ CompatGeckoDesktop("13") }}{{CompatNo}}25{{CompatNo}}
iterable{{ CompatChrome(38) }}{{ CompatGeckoDesktop("17") }}{{CompatNo}}257.1
Map.clear(){{ CompatChrome(31) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("19")}}11257.1
Map.keys(), Map.values(), Map.entries(){{ CompatChrome(37) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("20")}}{{CompatNo}}257.1
Map.forEach(){{ CompatChrome(36) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("25")}}11257.1
Key equality for -0 and 0{{ CompatChrome(34) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("29")}}{{CompatNo}}25{{CompatNo}}
Constructor argument: new Map(null){{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatGeckoDesktop("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{ CompatGeckoDesktop("42") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{ CompatChrome(38) }} [1]{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}8
Constructor argument: new Map(iterable){{CompatNo}}{{ CompatChrome(38) }}{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
iterable{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("17") }}{{CompatNo}}{{CompatNo}}8
Map.clear(){{CompatNo}}{{ CompatChrome(31) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("19")}}{{CompatNo}}{{CompatNo}}8
Map.keys(), Map.values(), Map.entries(){{CompatNo}}{{ CompatChrome(37) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("20")}}{{CompatNo}}{{CompatNo}}8
Map.forEach(){{CompatNo}}{{ CompatChrome(36) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
Key equality for -0 and 0{{CompatNo}}{{ CompatChrome(34) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("29")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Constructor argument: new Map(null){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("42")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Starting with Chrome 31, the feature was available behind a preference. In chrome://flags, activate the entry “Enable Experimental JavaScript”.

+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/math/abs/index.html b/files/id/web/javascript/reference/global_objects/math/abs/index.html new file mode 100644 index 0000000000..c15b00b315 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/abs/index.html @@ -0,0 +1,145 @@ +--- +title: Math.abs() +slug: Web/JavaScript/Reference/Global_Objects/Math/abs +tags: + - Math + - abs + - math abs +translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs +--- +
{{JSRef}}
+ +

Fungsi Math.abs() mengembalikan nilai mutlak dari sebuah bilangan, yakni

+ +

Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ -x & \text{if} \quad x < 0 \end{cases}

+ +

Sintak

+ +
Math.abs(x)
+ +

Parameter

+ +
+
x
+
Sebuah bilangan.
+
+ +

Nilai kembali

+ +

Nilai mutlak dari bilangan yang diberikan.

+ +

Deskripsi

+ +

Karena abs() merupakan sebuah metode statis dari Math, anda harus menggunakannya/menulisnya sebagai berikut Math.abs(), Bukan sebagai metode dari sebuah object Math yang anda buat (Math bukanlah sebuah konstruktor).

+ +

Contoh

+ +

Prilaku dari Math.abs()

+ +

Mengabaikan objek kosong, sebuah array dengan lebih dari satu anggota, sebuah string non-numerik atau {{jsxref("undefined")}}/variabel kosong dikembalikan{{jsxref("NaN")}}. Mengabaikan {{jsxref("null")}}, sebuah string kosong atau sebuah array kosong akan menghasilkan 0.

+ +
Math.abs('-1');     // 1
+Math.abs(-2);       // 2
+Math.abs(null);     // 0
+Math.abs('');       // 0
+Math.abs([]);       // 0
+Math.abs([2]);      // 2
+Math.abs([1,2]);    // NaN
+Math.abs({});       // NaN
+Math.abs('string'); // NaN
+Math.abs();         // NaN
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan pada JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome untuk AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/math/ceil/index.html b/files/id/web/javascript/reference/global_objects/math/ceil/index.html new file mode 100644 index 0000000000..cba010ffdb --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,174 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Reference/Global_Objects/Math/ceil +tags: + - JavaScript + - Math + - Metode + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +
{{JSRef}}
+ +

Fungsi Math.ceil() adalah memberikan nilai integer lebih-besar-dari terkecil atau sama-dengan (pembulatan ke atas) nilai yang ditentukan.

+ +

Catatan: Nilai kembalian Math.ceil(null) adalah integer 0 dan tidak memberikan kesalahan NaN.

+ +
{{EmbedInteractiveExample("pages/js/math-ceil.html")}}
+ + + +

Sintaks

+ +
Math.ceil(x)
+ +

Parameter

+ +
+
x
+
Sebuah angka.
+
+ +

Nilai kembali

+ +

Nilai integer lebih-besar-dari terkecil atau sama-dengan (pembulatan ke atas) nilai yang ditentukan.

+ +

Deskripsi

+ +

Karena ceil() adalah sebuah metode statis dari Math, Anda harus selalu menggunakan sebagai Math.ceil(), bukan sebagai metode dari object  Math yang Anda buat (Math bukanlah sebuah konstruktor).

+ +

Contoh

+ +

Menggunakan Math.ceil()

+ +

Berikut adalah contoh penggunaan dari Math.ceil().

+ +
Math.ceil(.95);    // 1
+Math.ceil(4);      // 4
+Math.ceil(7.004);  // 8
+Math.ceil(-0.95);  // -0
+Math.ceil(-4);     // -4
+Math.ceil(-7.004); // -7
+
+ +

Penyesuaian desimal

+ +
// Closure
+(function() {
+  /**
+   * Penyesuaian desimal dari sebuah angka.
+   *
+   * @param {String}  type  Tipe dari penyesuaian.
+   * @param {Number}  value Angka.
+   * @param {Integer} exp   Eksponen (10 logaritma basis penyesuaian).
+   * @returns {Number} Nilai yang di sesuaikan.
+   */
+  function decimalAdjust(type, value, exp) {
+    // jika exp adalah undefined atau nol...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // Jika nilai adalah bukan sebuah angka atau bilangan integer...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomen
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan dalam JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas peramban

+ +
+ +
+ +

{{Compat("javascript.builtins.Math.ceil")}}

+ +

Lihat pula

+ + diff --git a/files/id/web/javascript/reference/global_objects/math/e/index.html b/files/id/web/javascript/reference/global_objects/math/e/index.html new file mode 100644 index 0000000000..79e9f21f4a --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/e/index.html @@ -0,0 +1,81 @@ +--- +title: Math.E +slug: Web/JavaScript/Reference/Global_Objects/Math/E +translation_of: Web/JavaScript/Reference/Global_Objects/Math/E +--- +
{{JSRef}}
+ +

Properti Math.E mewakili dasar logaritma alami, e,  mendekati 2.718.

+ +

Math.E=e2.718\mathtt{\mi{Math.E}} = e \approx 2.718

+ +
{{EmbedInteractiveExample("pages/js/math-e.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

Deskripsi

+ +

Karena E adalah sebuah properti matematika statis, saudara selalu menggunakannya sebagai Math.E, daripada sebagai sebuah properti dari objek matematika yang saudara buat. (Math bukan sebuah konstruktor).

+ +

Contoh

+ +

Menggunakan Math.E

+ +

Fungsi berikut menampilkan nilai e:

+ +
function getNapier() {
+  return Math.E;
+}
+
+getNapier(); // 2.718281828459045
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}} +

definisi inisial. Diimplementasikan dalam  JavaScript 1.0.

+
{{SpecName('ES5.1', '#sec-15.8.1.1', 'Math.E')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.e', 'Math.E')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.e', 'Math.E')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas browser

+ + + +

{{Compat("javascript.builtins.Math.E")}}

+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/math/floor/index.html b/files/id/web/javascript/reference/global_objects/math/floor/index.html new file mode 100644 index 0000000000..ecd6e89cdd --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/floor/index.html @@ -0,0 +1,210 @@ +--- +title: Math.floor() +slug: Web/JavaScript/Reference/Global_Objects/Math/floor +tags: + - Math + - math floor + - pembulatan + - pembulatan bilangan + - pembulatan kebawah javascript +translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor +--- +
{{JSRef}}
+ +

Fungsi Math.floor() mengembalikan bilangan bulat terbesar yang kurang dari atau sama dengan bilangan yang diberikan.

+ +

Sintaks

+ +
Math.floor(x)
+ +

Parameter

+ +
+
x
+
Sebuah bilangan.
+
+ +

Nilai kembali

+ +

Sebuah bilangan yang merepresentasikan bilangan bulat terbesar yang kurang dari atau sama dengan nilai yang diberikan

+ +

Deskripsi

+ +

Karena floor() adalah sebuah metode statis dari Math, sintaks yang harus anda gunakan adalah Math.floor(), bukan sebagai metode dari obyek Math yang anda buat (Math bukanlah sebuah konstruktor).

+ +

Contoh

+ +

Penggunaan Math.floor()

+ +
Math.floor( 45.95); //  45
+Math.floor( 45.05); //  45
+Math.floor(  4   ); //   4
+Math.floor(-45.05); // -46
+Math.floor(-45.95); // -46
+
+ +

Penyesuaian desimal

+ +
// Closure
+(function() {
+  /**
+   * Penyesuaian desimal dari sebuah bilangan.
+   *
+   * @param {String}  type  Jenis penyesuaian.
+   * @param {Number}  value Nomor.
+   * @param {Integer} exp   Eksponen (10 logaritma dari penyesuaian dasar).
+   * @returns {Number} Nilai yang disesuaikan.
+   */
+  function decimalAdjust(jenis, nilai, eks) {
+    // Jika eks adalah undefined(belum didefinisikan) atau kosong...
+    if (typeof eks === 'undefined' || +eks === 0) {
+      return Math[jenis](nilai);
+    }
+    nilai = +nilai;
+    eks= +eks;
+    // Jika nilai bukan sebuah angka atau eks bukan sebuah bilangan integer...
+    if (isNaN(nilai) || !(typeof eks === 'number' && eks % 1 === 0)) {
+      return NaN;
+    }
+    // Pengalihan
+    nilai = nilai.toString().split('e');
+    nilai = Math[jenis](+(nilai[0] + 'e' + (nilai[1] ? (+nilai[1] - eks) : -eks)));
+    // pengalihan kembali
+    nilai = nilai.toString().split('e');
+    return +(nilai[0] + 'e' + (nilai[1] ? (+nilai[1] + eks) : eks));
+  }
+
+  // Desimal bulat
+  if (!Math.round10) {
+    Math.round10 = function(nilai, eks) {
+      return decimalAdjust('round', nilai, eks);
+    };
+  }
+  // Desimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(nilai, eks) {
+      return decimalAdjust('floor', nilai, eks);
+    };
+  }
+  // Desimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(nilai, eks) {
+      return decimalAdjust('ceil', nilai, eks);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan pada JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas browser

+ +
{{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}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/math/index.html b/files/id/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..4d9bb6a9bb --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,213 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +tags: + - JavaScript + - Math + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +
{{JSRef}}
+ +

Math merupakan objek built-in yang memiliki properti dan method untuk perhitungan konstan dan fungsi. bukan Fungsi Objek.

+ +

Description

+ +

Tidak seperti global objects lain, Math bukanlah constructor. Semua properti dan method dari Math adalah static. You refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument. Constants are defined with the full precision of real numbers in JavaScript.

+ +

Properties

+ +
+
{{jsxref("Math.E")}}
+
Euler's constant and the base of natural logarithms, approximately 2.718.
+
{{jsxref("Math.LN2")}}
+
Natural logarithm of 2, approximately 0.693.
+
{{jsxref("Math.LN10")}}
+
Natural logarithm of 10, approximately 2.303.
+
{{jsxref("Math.LOG2E")}}
+
Base 2 logarithm of E, approximately 1.443.
+
{{jsxref("Math.LOG10E")}}
+
Base 10 logarithm of E, approximately 0.434.
+
{{jsxref("Math.PI")}}
+
Ratio of the circumference of a circle to its diameter, approximately 3.14159.
+
{{jsxref("Math.SQRT1_2")}}
+
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
+
{{jsxref("Math.SQRT2")}}
+
Square root of 2, approximately 1.414.
+
+ +

Method

+ +
+

Note that the trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) expect or return angles in radians. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

+
+ +
+

Note that a lot of the math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.

+
+ +
+
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
+
Returns the absolute value of a number.
+
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
+
Returns the arccosine of a number.
+
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
+
Returns the hyperbolic arccosine of a number.
+
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
+
Returns the arcsine of a number.
+
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
+
Returns the hyperbolic arcsine of a number.
+
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
+
Returns the arctangent of a number.
+
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
+
Returns the hyperbolic arctangent of a number.
+
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
+
Returns the arctangent of the quotient of its arguments.
+
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
+
Returns the cube root of a number.
+
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
+
Returns the smallest integer greater than or equal to a number.
+
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
+
Returns the number of leading zeroes of a 32-bit integer.
+
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
+
Returns the cosine of a number.
+
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
+
Returns the hyperbolic cosine of a number.
+
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
+
Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
+
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
+
Returns subtracting 1 from exp(x).
+
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
+
Returns the largest integer less than or equal to a number.
+
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
+
Returns the nearest single precision float representation of a number.
+
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
+
Returns the square root of the sum of squares of its arguments.
+
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
+
Returns the result of a 32-bit integer multiplication.
+
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
+
Returns the natural logarithm (loge, also ln) of a number.
+
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
+
Returns the natural logarithm of 1 + x (loge, also ln) of a number.
+
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
+
Returns the base 10 logarithm of a number.
+
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
+
Returns the base 2 logarithm of a number.
+
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
+
Returns the largest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
+
Returns the smallest of zero or more numbers.
+
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
+
Returns base to the exponent power, that is, baseexponent.
+
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
+
Returns a pseudo-random number between 0 and 1.
+
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
+
Returns the value of a number rounded to the nearest integer.
+
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
+
Returns the sign of the x, indicating whether x is positive, negative or zero.
+
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
+
Returns the sine of a number.
+
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
+
Returns the hyperbolic sine of a number.
+
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
+
Returns the positive square root of a number.
+
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
+
Returns the tangent of a number.
+
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
+
Returns the hyperbolic tangent of a number.
+
Math.toSource() {{non-standard_inline}}
+
Returns the string "Math".
+
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
+
Returns the integral part of the number x, removing any fractional digits.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/math/ln10/index.html b/files/id/web/javascript/reference/global_objects/math/ln10/index.html new file mode 100644 index 0000000000..04e4fe5468 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/ln10/index.html @@ -0,0 +1,81 @@ +--- +title: Math.LN10 +slug: Web/JavaScript/Reference/Global_Objects/Math/LN10 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LN10 +--- +
{{JSRef}}
+ +

Properti Math.LN10 mewakili logaritma alami dari 10, mendekati 2.302:

+ +

Math.LN10=ln(10)2.302\mathtt{\mi{Math.LN10}} = \ln(10) \approx 2.302

+ +
{{EmbedInteractiveExample("pages/js/math-ln10.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

Deskripsi

+ +

Karena LN10 adalah sebuah properti matematika statis, saudara selalu menggunakannya sebagai Math.LN10, daripada sebagai sebuah properti objek matematika yang saudara buat (Math bukan sebuah konstruktor).

+ +

Contoh

+ +

+

Menggunakan Math.LN10

+

+ +

Fungsi berikut menampilkan log alami dari 10:

+ +
function getNatLog10() {
+  return Math.LN10;
+}
+
+getNatLog10(); // 2.302585092994046
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecisifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi inisial. Diimplementasikan di JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.2', 'Math.LN10')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas browser

+ + + +

{{Compat("javascript.builtins.Math.LN10")}}

+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/math/max/index.html b/files/id/web/javascript/reference/global_objects/math/max/index.html new file mode 100644 index 0000000000..aeb1b207ce --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/max/index.html @@ -0,0 +1,144 @@ +--- +title: Math.max() +slug: Web/JavaScript/Reference/Global_Objects/Math/max +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/max +--- +
{{JSRef}}
+ +

Fungsi Math.max() mengembalikan nilai terbesar dari zero atau lebih besar.

+ +

Sintaks

+ +
Math.max([value1[, value2[, ...]]])
+ +

Parameter

+ +
+
value1, value2, ...
+
Nomor.
+
+ +

Deskripsi

+ +

Karena max() merupakan method static dari Math, anda perlu menggunakan Math.max(), daripada sebagai method dari objek Math yang anda buat (Math bukan constructor).

+ +

Jika tidak diberi argumen, hasilnya akan -{{jsxref("Infinity")}}.

+ +

Jika setidaknya satu argumen tidak dapat dikonversi ke angka, maka hasilnya {{jsxref("NaN")}}.

+ +

Contoh

+ +

Penggunaan Math.max()

+ +
Math.max(10, 20);   //  20
+Math.max(-10, -20); // -10
+Math.max(-10, 20);  //  20
+
+ +

Pada contoh menggunakan fungsi {{jsxref("Function.prototype.apply()")}} untuk mencari nilai elemen maksimum pada sebuah numeric array. getMaxOfArray([1, 2, 3]) sama halnya dengan Math.max(1, 2, 3), tapi anda bisa menggunakan getMaxOfArray() pada programmatikal pembuatan array untuk semua ukuran.

+ +
function getMaxOfArray(numArray) {
+  return Math.max.apply(null, numArray);
+}
+
+ +

Atau dengan {{jsxref("Operators/Spread_operator", "spread operator")}} baru, mencari nilai terbesar menjadi lebih mudah.

+ +
var arr = [1, 2, 3];
+var max = Math.max(...arr);
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.max', 'Math.max')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{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}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/math/min/index.html b/files/id/web/javascript/reference/global_objects/math/min/index.html new file mode 100644 index 0000000000..eb557f36bf --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/min/index.html @@ -0,0 +1,150 @@ +--- +title: Math.min() +slug: Web/JavaScript/Reference/Global_Objects/Math/min +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/min +--- +
{{JSRef}}
+ +

Function Math.min() mengembalikan nilai terkecil dari zero atau lebih kecil.

+ +

Sintaks

+ +
Math.min([value1[, value2[, ...]]])
+ +

Parameter

+ +
+
value1, value2, ...
+
Nomor.
+
+ +

Deskripsi

+ +

Karena min() merupakan static method dari Math, anda perlu menggunakan  Math.min(), daripada sebagai method dari objek Math yang anda buat (Math bukanlah konstruktor).

+ +

Jika tidak diberi argumen, hasilnya adalah {{jsxref("Infinity")}}.

+ +

Jika setidaknya satu argumen tidak bisa di konversi ke angka, maka hasilnya{{jsxref("NaN")}}.

+ +

Contoh

+ +

Menggunakan Math.min()

+ +

Mencari nilai terkecil diantara x dan y dan menyimpannya di variabel z:

+ +
var x = 10, y = -20;
+var z = Math.min(x, y);
+
+ +

Mengambil nilai dengan Math.min()

+ +

Math.min() biasa digunakan untuk mengambil nilai yang terkecil atau sama berdasarkan batasan yang ada. contoh sebagai berikut.

+ +
var x = f(foo);
+
+if (x > boundary) {
+  x = boundary;
+}
+
+ +

bisa ditulis sebagai berikut

+ +
var x = Math.min(f(foo), boundary);
+
+ +

{{jsxref("Math.max()")}} bisa digunakan sama halnya denga mengambil nilai pada setiap batasan.

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.12', 'Math.min')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.min', 'Math.min')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.min', 'Math.min')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{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}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/math/pow/index.html b/files/id/web/javascript/reference/global_objects/math/pow/index.html new file mode 100644 index 0000000000..878fde0e04 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/math/pow/index.html @@ -0,0 +1,53 @@ +--- +title: Math.pow +slug: Web/JavaScript/Reference/Global_Objects/Math/pow +translation_of: Web/JavaScript/Reference/Global_Objects/Math/pow +--- +

Ringkasan

+

Mengembalikan bilangan terhadap Pangkat exponent,  yaitu, bilanganeksponen.

+ + + + + + + + + + + + + + + + +
Method dari Math
Diimplementasikan padaJavaScript 1.0
Edisi ECMAScriptECMAScript 1st Edition
+

Sintaks

+
Math.pow(bilangan, eksponen) 
+

Parameter

+
+
+ bilangan
+
+ Bilangan pokok.
+
+ eksponen
+
+ Eksponen yang digunakan untuk memangkatkan bilangan pokok.
+
+

Deskripsi

+

Karena pow adalah sebuah static method dari Math, anda senantiasa menggunakannya sebagai Math.pow(), daripada sebagai sebuah method dari sebuah Objek Math yang anda buat.

+

Contoh

+

Contoh: Penggunaan Math.pow

+
function raisePower(x,y) {
+   return Math.pow(x,y)
+}
+

Jika x adalah 7 dan y adalah 2, raisePower mengembalikan 49 (7 dipangkatkan 2).

+

Lihat juga

+ diff --git a/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html new file mode 100644 index 0000000000..6ac06ec718 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html @@ -0,0 +1,133 @@ +--- +title: Object.getPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +--- +
{{JSRef}}
+ +

Metode Object.getPrototypeOf() mengembalikan nilai prototipe dari obyek yang disebutkan (misalnya,  nilai dari properti internal [[Prototype]]).

+ +

Sintaks

+ +
Object.getPrototypeOf(obj)
+ +

Parameter

+ +
+
obj
+
Obyek yang memiliki prototipe.
+
+ +

Nilai kembali

+ +

Prototipe dari obyek yang diberikan. Jika tidak ada property yang ditemukan, {{jsxref("null")}} yang akan dikembalikan.

+ +

Contoh

+ +
var proto = {};
+var obj = Object.create(proto);
+Object.getPrototypeOf(obj) === proto; // true
+
+ +

Catatan

+ +

Dalam ES5, akan melemparkan eksepsi {{jsxref("TypeError")}} jika parameter obj parameter bukanlah sebuah obyek. Dalam ES6, parameter akan dipaksa menjadi {{jsxref("Object")}}.

+ +
Object.getPrototypeOf("foo");
+// TypeError: "foo" is not an object (ES5 code)
+Object.getPrototypeOf("foo");
+// String.prototype                  (ES6 code)
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}Definisi awal.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas perambah

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Catatan khusus Opera

+ +

Meskipun Opera dengan versi yang lebih lama belum mendukung Object.getPrototypeOf(), Opera mendukung properti non-standar {{jsxref("Object.proto", "__proto__")}} sejak Opera 10.50.

+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/object/index.html b/files/id/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..cc79ab6890 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,221 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - Object + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef}}
+ +

Konstruktor Object membuat sebuah pembungkus objek.

+ +

Sintaks

+ +
// Persiapan literasi objek
+{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
+
+// Panggil konstruktor
+new Object([value])
+ +

Parameter

+ +
+
nameValuePair1, nameValuePair2, ... nameValuePairN
+
Pasangan dari nama (strings) dan nilai dimana nama dipisahkan dari nilai menggunakan titik dua (colon).
+
value
+
Nilai bebas.
+
+ +

Keterangan

+ +

Konstruktor Object membuat sebuah pembungkus objek dari nilai yang diberikan. Jika nilainya {{jsxref("null")}} atau {{jsxref("undefined")}}, maka akan menghasilkan dan mengembalikan objek kosong. Sebaliknya, akan mengembalikan sebuah objek dari Type yang bergantung pada nilai yang diberikan. Jika nilai adalah objek, maka nilai akan langsung dikembalikan.

+ +

Ketika memanggil konteks non-constructor, Object berperilaku seperti layaknya new Object().

+ +

Lihat juga object initializer / literal syntax.

+ +

Properti dari konstruktor Object

+ +
+
Object.length
+
Bernilai 1.
+
{{jsxref("Object.prototype")}}
+
Memungkinkan untuk menambahkan properti ke semua objek dari type Object.
+
+ +

Method dari konstruktor Object

+ +
+
{{jsxref("Object.assign()")}}
+
Membuat objek baru dengan menyalin nilai dari semua properti enumerable dari satu atau lebih sumber ke sebuah objek target.
+
{{jsxref("Object.create()")}}
+
Membuat objek baru dengan prototype dan properti objek tertentu.
+
{{jsxref("Object.defineProperty()")}}
+
Menambahkan nama properti berdasarkan deskripsi yang diberikan oleh descriptor pada sebuah objek.
+
{{jsxref("Object.defineProperties()")}}
+
Menambahkan nama properti yang dideskripsikan descriptors pada sebuah object.
+
{{jsxref("Object.entries()")}} {{experimental_inline}}
+
Mengembalikan sebuah array dari enumerable objek dengan  pasangan properti [key, value].
+
{{jsxref("Object.freeze()")}}
+
Membekukan objek: kode lain tidak dapat dihapus atau diubah oleh semua properti.
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
Mengembalikan sebuah properti descriptor untuk nama propeti pada sebuah object.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
Mengembalikan array berisi nama dari semua objek yang diberikan own enumerable dan properti non-enumerable.
+
{{jsxref("Object.getOwnPropertySymbols()")}}
+
Mengembalikan sebuah array dari semua properti simbol yang ditemukan secara langsung atas objek yang diberikan.
+
{{jsxref("Object.getPrototypeOf()")}}
+
Mengembalikan prototype dari objek tertentu.
+
{{jsxref("Object.is()")}}
+
Membandingkan dua nilai yang berbeda (mis. the same)
+
{{jsxref("Object.isExtensible()")}}
+
Menentukan apakah memperluas objek di perbolehkan.
+
{{jsxref("Object.isFrozen()")}}
+
Menentukan apakah objek telah beku.
+
{{jsxref("Object.isSealed()")}}
+
Menentukan apakah objek adalah sealed.
+
{{jsxref("Object.keys()")}}
+
Menegembalikan array berisi nama dari semua objek properti own enumerable.
+
{{jsxref("Object.preventExtensions()")}}
+
Mencegah ekstensi dari sebuah objek.
+
{{jsxref("Object.seal()")}}
+
Mencegah kode lain dari penghapusan properti dari sebuah objek.
+
{{jsxref("Object.setPrototypeOf()")}}
+
Mengatur prototype (mis., internal properti [[Prototype]])
+
{{jsxref("Object.values()")}} {{experimental_inline}}
+
Mengembalikan array dari objek nilai own enumerable.
+
+ +

Perumpamaan Object dan Object prototype objek

+ +

Pada JavaScript, semua objek diturunkan dari Object; dan semua objek mewarisi method dan property dari {{jsxref("Object.prototype")}}, meskipun hal tersebut telah di-override (diganti). Sebagai contoh, prototipe konstruktor lain mengesampingkan properti konstruktor dan menyediakan metode toString() yang spesifik. Perubahan ke objek prototipe Object disebarkan ke semua objek kecuali properti dan metode yang telah diubah sebelumnya diganti di sepanjang rantai prototipe.

+ +

Properti

+ +
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}
+ +

Method

+ +
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}
+ +

Contoh

+ +

Using Object given undefined and null types

+ +

Dibawah ini adalah contoh menyimpan objek kosong pada variabel o:

+ +
var o = new Object();
+
+ +
var o = new Object(undefined);
+
+ +
var o = new Object(null);
+
+ +

Using Object to create Boolean objects

+ +

Dibawah ini adalah contoh menyimpan objek {{jsxref("Boolean")}} pada variabel o:

+ +
// equivalent to o = new Boolean(true);
+var o = new Object(true);
+
+ +
// equivalent to o = new Boolean(false);
+var o = new Object(Boolean());
+
+ +

Rincian Teknis

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diterapkan di JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}}-
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}} +

Penambahan Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is

+
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Penambahan Object.entries, Object.values, dan Object.getOwnPropertyDescriptors.
+ +

Kesesuaian browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/object/keys/index.html b/files/id/web/javascript/reference/global_objects/object/keys/index.html new file mode 100644 index 0000000000..cc1c7dc1a9 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/object/keys/index.html @@ -0,0 +1,197 @@ +--- +title: Object.keys() +slug: Web/JavaScript/Reference/Global_Objects/Object/keys +translation_of: Web/JavaScript/Reference/Global_Objects/Object/keys +--- +
{{JSRef}}
+ +

Object.keys() Metode mengembalikan array dari objek yang diberikan sendiri enumerable properti, dalam urutan yang sama seperti yang disediakan oleh loop {{jsxref("Statements/for...in", "for...in")}} (perbedaan adalah bahwa sebuah loop for-in enumerates properti dalam mata rantai prototipe juga).

+ +

Syntax

+ +
Object.keys(obj)
+ +

Parameters

+ +
+
obj
+
Objek yang propertinya sendiri enumerable yang harus dikembalikan.
+
+ +

Description

+ +

Object.keys() mengembalikan array yang elemen string yang sesuai dengan properti enumerable yang ditemukan langsung pada objek. Urutan properti adalah sama dengan yang diberikan oleh perulangan / looping melalui properti dari objek secara manual.

+ +

Examples

+ +
var arr = ['a', 'b', 'c'];
+console.log(Object.keys(arr)); // console: ['0', '1', '2']
+
+// array like object
+var obj = { 0: 'a', 1: 'b', 2: 'c' };
+console.log(Object.keys(obj)); // console: ['0', '1', '2']
+
+// array like object with random key ordering
+var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
+console.log(Object.keys(an_obj)); // console: ['2', '7', '100']
+
+// getFoo is property which isn't enumerable
+var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
+my_obj.foo = 1;
+
+console.log(Object.keys(my_obj)); // console: ['foo']
+
+ +

Jika Anda ingin semua properti, bahkan tidak enumerables, lihat {{jsxref("Object.getOwnPropertyNames()")}}.

+ +

Notes

+ +

Dalam ES5, jika argumen untuk metode ini bukan merupakan objek (primitive), maka akan menyebabkan {{jsxref("TypeError")}}. Dalam ES6, argumen tidak-objek akan dipaksa untuk sebuah objek.

+ +
Object.keys("foo");
+// TypeError: "foo" is not an object (ES5 code)
+
+Object.keys("foo");
+// ["0", "1", "2"]                   (ES6 code)
+
+ +

Polyfill

+ +

Untuk menambahkan kompatibel Object.keys dukungan dalam lingkungan yang lebih tua yang tidak native mendukung itu, copy potongan berikut:

+ +
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
+if (!Object.keys) {
+  Object.keys = (function() {
+    'use strict';
+    var hasOwnProperty = Object.prototype.hasOwnProperty,
+        hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
+        dontEnums = [
+          'toString',
+          'toLocaleString',
+          'valueOf',
+          'hasOwnProperty',
+          'isPrototypeOf',
+          'propertyIsEnumerable',
+          'constructor'
+        ],
+        dontEnumsLength = dontEnums.length;
+
+    return function(obj) {
+      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
+        throw new TypeError('Object.keys called on non-object');
+      }
+
+      var result = [], prop, i;
+
+      for (prop in obj) {
+        if (hasOwnProperty.call(obj, prop)) {
+          result.push(prop);
+        }
+      }
+
+      if (hasDontEnumBug) {
+        for (i = 0; i < dontEnumsLength; i++) {
+          if (hasOwnProperty.call(obj, dontEnums[i])) {
+            result.push(dontEnums[i]);
+          }
+        }
+      }
+      return result;
+    };
+  }());
+}
+
+ +

Harap dicatat bahwa kode di atas termasuk kunci non-enumerable di  IE7 (dan mungkin IE8), ketika lewat di sebuah objek dari berbagai window.

+ +

Untuk Browser sederhana Polyfill, lihat Javascript - Object.keys Browser Compatibility.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.keys', 'Object.keys')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.keys', 'Object.keys')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html b/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html new file mode 100644 index 0000000000..3899fef48f --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html @@ -0,0 +1,185 @@ +--- +title: Object.preventExtensions() +slug: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +translation_of: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +--- +
{{JSRef}}
+ +

Metode Object.preventExtensions() mencegah properti-properti baru untuk ditambahkan pada sebuah obyek (mencegah ekstensi di masa depan pada sebuah obyek).

+ +

Sintaks

+ +
Object.preventExtensions(obj)
+ +

Parameter

+ +
+
obj
+
Obyek yang akan dibuat menjadi non-ekstensibel.
+
+ +

Pengembalian nilai

+ +

Obyek yang telah dibuat non-ekstensibel.

+ +

Deskripsi

+ +

 

+ +

Sebuah obyek disebut ekstensibel jika properti baru dapat ditambahkan ke dalamnya . Object.preventExtensions() menandai suatu obyek untuk menjadi tidak ekstensibel, sehingga tidak akan pernah memiliki properti diluar properti-properti yang dimiliki sebelum ditandai sebagai non-ekstensibel. Perhatikan bahwa properti-properti obyek non-ekstensibel, secara umum, masih dapat dihapus. Mencoba untuk menambah properti baru ke obyek non-ekstensibel akan gagal, baik secara diam-diam atau dengan melemparkan {{jsxref("TypeError")}} (paling umum, tetapi tidak secara eksklusif,  ketika berada di {{jsxref("Functions_and_function_scope/Strict_mode", "strict mode", "", 1)}}).

+ +

Object.preventExtensions() hanya mencegah penambahan properti sendiri . Sifat masih bisa ditambahkan ke prototipe obyek. Namun, memanggil Object.preventExtensions() pada obyek juga akan mencegah ekstensi / penambahan properti {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}}.

+ +

Jika ada cara untuk mengubah suatu obyek ekstensibel untuk satu non-ekstensibel, tidak ada cara untuk melakukan yang sebaliknya di ECMAScript 5 .

+ +

Contoh

+ +
// Object.preventExtensions returns the object being made non-extensible.
+var obj = {};
+var obj2 = Object.preventExtensions(obj);
+obj === obj2; // true
+
+// Objects are extensible by default.
+var empty = {};
+Object.isExtensible(empty); // === true
+
+// ...but that can be changed.
+Object.preventExtensions(empty);
+Object.isExtensible(empty); // === false
+
+// Object.defineProperty throws when adding a new property to a non-extensible object.
+var nonExtensible = { removable: true };
+Object.preventExtensions(nonExtensible);
+Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // throws a TypeError
+
+// In strict mode, attempting to add new properties to a non-extensible object throws a TypeError.
+function fail() {
+  'use strict';
+  nonExtensible.newProperty = 'FAIL'; // throws a TypeError
+}
+fail();
+
+// EXTENSION (only works in engines supporting __proto__
+// (which is deprecated. Use Object.getPrototypeOf instead)):
+// A non-extensible object's prototype is immutable.
+var fixed = Object.preventExtensions({});
+fixed.__proto__ = { oh: 'hai' }; // throws a TypeError
+
+ +

Catatan

+ +

Pada ES5, jika argumen pada fungsi metode ini adalah bukan sebuah obyek (sebuah tipe data primitif), maka hal itu akan menyebabkan {{jsxref("TypeError")}}. Pada ES6, sebuah argumen non-obyek akan diperlakukan seperti obyek tersebut obyek biasa yang non-ekstensibel, dan langsung mengembalikan nilai. 

+ +
Object.preventExtensions(1);
+// TypeError: 1 is not an object (ES5 code)
+
+Object.preventExtensions(1);
+// 1                             (ES6 code)
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.2.3.10', 'Object.preventExtensions')}}{{Spec2('ES5.1')}}Definisi awal. Terimplementasi pada JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ESDraft')}} 
+ +

Browser kompatibilitas

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("6")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
ES6 behavior for non-object argument{{CompatChrome("44")}}{{CompatGeckoDesktop("35.0")}}{{CompatIE("11")}}{{CompatOpera("31")}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ES6 behavior for non-object argument{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("35.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/promise/catch/index.html b/files/id/web/javascript/reference/global_objects/promise/catch/index.html new file mode 100644 index 0000000000..f2d5e38e8f --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/catch/index.html @@ -0,0 +1,127 @@ +--- +title: Promise.prototype.catch() +slug: Web/JavaScript/Reference/Global_Objects/Promise/catch +tags: + - ECMAScript6 + - Method + - Promise + - Prototype + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch +--- +
{{JSRef}}
+ +

Method catch() mengembalikan Promise dan hanya setuju jika kasusnya gagal. Sama halnya dengan memenggil method {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}}.

+ +

Sintaks

+ +
p.catch(onRejected);
+
+p.catch(function(reason) {
+   // rejection
+});
+
+ +

Parameter

+ +
+
onRejected
+
 {{jsxref("Function")}} dipanggil ketika Promise ditolak. Fungsi ini memiliki satu argumen, alasan penolakan.
+
+ +

Deskripsi

+ +

Method catch sangat berguna untuk menangani error di gabungan promis anda.

+ +

Contoh

+ +

Penggunaan method catch

+ +
var p1 = new Promise(function(resolve, reject) {
+  resolve('Success');
+});
+
+p1.then(function(value) {
+  console.log(value); // "Success!"
+  throw 'oh, no!';
+}).catch(function(e) {
+  console.log(e); // "oh, no!"
+}).then(function(){
+  console.log('after a catch the chain is restored');
+}, function () {
+  console.log('Not fired due to the catch');
+});
+
+// The following behaves the same as above
+p1.then(function(value) {
+  console.log(value); // "Success!"
+  return Promise.reject('oh, no!');
+}).catch(function(e) {
+  console.log(e); // "oh, no!"
+}).then(function(){
+  console.log('after a catch the chain is restored');
+}, function () {
+  console.log('Not fired due to the catch');
+});
+
+
+ +

Promis tidak dapat mendeteksi error pada asynchronous callback

+ +
var p1 = new Promise(function(resolve, reject) {
+  throw 'Uh-oh!';
+});
+
+p1.catch(function(e) {
+  console.log(e); // "Uh-oh!"
+});
+
+
+var p2 = new Promise(function(resolve, reject) {
+  setTimeout(function() {
+    throw 'Uncaught Exception!';
+  }, 1000);
+});
+
+p2.catch(function(e) {
+  console.log(e); // This is never called
+});
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +

 

+ + + +

{{Compat("javascript.builtins.Promise.catch")}}

+ +

 

+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/promise/index.html b/files/id/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..240915ba23 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,317 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +tags: + - ECMAScript6 + - JavaScript + - NeedsTranslation + - Promise + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +
{{JSRef}}
+ +

The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.

+ +

Syntax

+ +
new Promise( /* executor */ function(resolve, reject) { ... } );
+ +

Parameters

+ +
+
executor
+
A function that will be passed to other functions via the arguments resolve and reject. The executor function is executed immediately by the Promise implementation which provides the resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions are bound to the promise and calling them fulfills or rejects the promise, respectively. The executor is expected to initiate some asynchronous work and then, once that completes, call either the resolve or reject function to resolve the promise's final value or else reject it if an error occurred.
+
+ +

Description

+ +

A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.

+ +

A Promise is in one of these states:

+ + + +

A pending promise can become either fulfilled with a value, or rejected with a reason (error). When either of these happens, the associated handlers queued up by a promise's then method are called. (If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.)

+ +

As the {{jsxref("Promise.then", "Promise.prototype.then()")}} and {{jsxref("Promise.catch", "Promise.prototype.catch()")}} methods return promises, they can be chained—an operation called composition.

+ +

+ +
+

Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises — this means that the promise is settled, or it is locked into a promise chain. Domenic Denicola's States and fates contains more details about promise terminology.

+
+ +

Properties

+ +
+
Promise.length
+
Length property whose value is 1 (number of constructor arguments).
+
{{jsxref("Promise.prototype")}}
+
Represents the prototype for the Promise constructor.
+
+ +

Methods

+ +
+
{{jsxref("Promise.all", "Promise.all(iterable)")}}
+
Returns a promise that either resolves when all of the promises in the iterable argument have resolved or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise resolves, it is resolved with an array of the values from the resolved promises in the iterable. If the returned promise rejects, it is rejected with the reason from the promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises together.
+
{{jsxref("Promise.race", "Promise.race(iterable)")}}
+
Returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.
+
+ +
+
{{jsxref("Promise.reject", "Promise.reject(reason)")}}
+
Returns a Promise object that is rejected with the given reason.
+
+ +
+
{{jsxref("Promise.resolve", "Promise.resolve(value)")}}
+
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. Generally, if you want to know if a value is a promise or not - {{jsxref("Promise.resolve", "Promise.resolve(value)")}} it instead and work with the return value as a promise.
+
+ +

Promise prototype

+ +

Properties

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}

+ +

Methods

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}

+ +

Examples

+ +

Creating a Promise

+ + + +

This small example shows the mechanism of a Promise. The testPromise() method is called each time the {{HTMLElement("button")}} is clicked. It creates a promise that will resolve, using {{domxref("window.setTimeout()")}}, to the promise count (number starting from 1) every 1-3 seconds, at random. The Promise() constructor is used to create the promise.

+ +

The fulfillment of the promise is simply logged, via a fulfill callback set using {{jsxref("Promise.prototype.then()","p1.then()")}}. A few logs shows how the synchronous part of the method is decoupled of the asynchronous completion of the promise.

+ +
'use strict';
+var promiseCount = 0;
+
+function testPromise() {
+    var thisPromiseCount = ++promiseCount;
+
+    var log = document.getElementById('log');
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Started (<small>Sync code started</small>)<br/>');
+
+    // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s)
+    var p1 = new Promise(
+        // The resolver function is called with the ability to resolve or
+        // reject the promise
+        function(resolve, reject) {
+            log.insertAdjacentHTML('beforeend', thisPromiseCount +
+                ') Promise started (<small>Async code started</small>)<br/>');
+            // This is only an example to create asynchronism
+            window.setTimeout(
+                function() {
+                    // We fulfill the promise !
+                    resolve(thisPromiseCount);
+                }, Math.random() * 2000 + 1000);
+        }
+    );
+
+    // We define what to do when the promise is resolved/fulfilled with the then() call,
+    // and the catch() method defines what to do if the promise is rejected.
+    p1.then(
+        // Log the fulfillment value
+        function(val) {
+            log.insertAdjacentHTML('beforeend', val +
+                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
+        })
+    .catch(
+        // Log the rejection reason
+        function(reason) {
+            console.log('Handle rejected promise ('+reason+') here.');
+        });
+
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Promise made (<small>Sync code terminated</small>)<br/>');
+}
+ + + +

This example is executed when clicking the button. You need a browser supporting Promise. By clicking several times the button in a short amount of time, you'll even see the different promises being fulfilled one after the other.

+ +

{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}

+ +

Example using new XMLHttpRequest()

+ +

Creating a Promise

+ +

This example shows the implementation of a method which uses a Promise to report the success or failure of an {{domxref("XMLHttpRequest")}}.

+ +
'use strict';
+
+// A-> $http function is implemented in order to follow the standard Adapter pattern
+function $http(url){
+
+  // A small example of object
+  var core = {
+
+    // Method that performs the ajax request
+    ajax : function (method, url, args) {
+
+      // Creating a promise
+      var promise = new Promise( function (resolve, reject) {
+
+        // Instantiates the XMLHttpRequest
+        var client = new XMLHttpRequest();
+        var uri = url;
+
+        if (args && (method === 'POST' || method === 'PUT')) {
+          uri += '?';
+          var argcount = 0;
+          for (var key in args) {
+            if (args.hasOwnProperty(key)) {
+              if (argcount++) {
+                uri += '&';
+              }
+              uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
+            }
+          }
+        }
+
+        client.open(method, uri);
+        client.send();
+
+        client.onload = function () {
+          if (this.status >= 200 && this.status < 300) {
+            // Performs the function "resolve" when this.status is equal to 2xx
+            resolve(this.response);
+          } else {
+            // Performs the function "reject" when this.status is different than 2xx
+            reject(this.statusText);
+          }
+        };
+        client.onerror = function () {
+          reject(this.statusText);
+        };
+      });
+
+      // Return the promise
+      return promise;
+    }
+  };
+
+  // Adapter pattern
+  return {
+    'get' : function(args) {
+      return core.ajax('GET', url, args);
+    },
+    'post' : function(args) {
+      return core.ajax('POST', url, args);
+    },
+    'put' : function(args) {
+      return core.ajax('PUT', url, args);
+    },
+    'delete' : function(args) {
+      return core.ajax('DELETE', url, args);
+    }
+  };
+};
+// End A
+
+// B-> Here you define its functions and its payload
+var mdnAPI = 'https://developer.mozilla.org/en-US/search.json';
+var payload = {
+  'topic' : 'js',
+  'q'     : 'Promise'
+};
+
+var callback = {
+  success : function(data){
+     console.log(1, 'success', JSON.parse(data));
+  },
+  error : function(data){
+     console.log(2, 'error', JSON.parse(data));
+  }
+};
+// End B
+
+// Executes the method call
+$http(mdnAPI)
+  .get(payload)
+  .then(callback.success)
+  .catch(callback.error);
+
+// Executes the method call but an alternative way (1) to handle Promise Reject case
+$http(mdnAPI)
+  .get(payload)
+  .then(callback.success, callback.error);
+
+// Executes the method call but an alternative way (2) to handle Promise Reject case
+$http(mdnAPI)
+  .get(payload)
+  .then(callback.success)
+  .then(undefined, callback.error);
+
+ +

Loading an image with XHR

+ +

Another simple example using Promise and XMLHttpRequest to load an image is available at the MDN GitHub promise-test repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

 

+ +
+ + +

{{Compat("javascript.builtins.Promise")}}

+
+ +

 

+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/promise/reject/index.html b/files/id/web/javascript/reference/global_objects/promise/reject/index.html new file mode 100644 index 0000000000..180fcc5571 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/reject/index.html @@ -0,0 +1,81 @@ +--- +title: Promise.reject() +slug: Web/JavaScript/Reference/Global_Objects/Promise/reject +tags: + - ECMAScript6 + - Method + - Promise + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/reject +--- +
{{JSRef}}
+ +

Method Promise.reject(reason) mengembalikan objek Promise yang ditolak dengan alasan yang diberikan.

+ +

Sintaks

+ +
Promise.reject(reason);
+ +

Parameter

+ +
+
reason
+
Alasan kenapa Promise ditolak.
+
+ +

Deskripsi

+ +

Fungsi static Promise.reject mengembalikan Promise yang ditolak. Untuk keperluan debugging dan seleksi penankapan error, sangat berguna untuk membuat reason pada instanceof {{jsxref("Error")}}.

+ +

Contoh

+ +

Penggunaan mthod static Promise.reject()

+ +
Promise.reject("Testing static reject").then(function(reason) {
+  // not called
+}, function(reason) {
+  console.log(reason); // "Testing static reject"
+});
+
+Promise.reject(new Error("fail")).then(function(error) {
+  // not called
+}, function(error) {
+  console.log(error); // Stacktrace
+});
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ + + +

{{Compat("javascript.builtins.Promise.reject")}}

+ +

 

+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/promise/resolve/index.html b/files/id/web/javascript/reference/global_objects/promise/resolve/index.html new file mode 100644 index 0000000000..d958ab4d52 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/resolve/index.html @@ -0,0 +1,140 @@ +--- +title: Promise.resolve() +slug: Web/JavaScript/Reference/Global_Objects/Promise/resolve +tags: + - ECMAScript6 + - JavaScript + - Method + - Promise +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/resolve +--- +
{{JSRef}}
+ +

Method Promise.resolve(value) mengembalikan objek {{jsxref("Promise.then")}} yang diselesaikan dengan nilai yang diberikan. jika nilainya thenable (mis. memiliki {{jsxref("Promise.then", "\"then\" method")}}), promise yang dikembalikan akan "mengikuti" thenable-nya, menggunakan keadaan ini; sebaliknya promise akan dikembalikan sesuai nilai yang terpenuhi.

+ +

Sintaks

+ +
Promise.resolve(value);
+Promise.resolve(promise);
+Promise.resolve(thenable);
+
+ +

Parameter

+ +
+
value
+
Argumen untuk diselesaikan oleh Promise. Dapat juga sebuah Promise atau thenable untuk diselesaikan.
+
+ +

Deskripsi

+ +

Fungsi statis Promise.resolve mengembalikan Promise yang terselesaikan.

+ +

Contoh

+ +

Penggunaan method static Promise.resolve

+ +
Promise.resolve("Success").then(function(value) {
+  console.log(value); // "Success"
+}, function(value) {
+  // not called
+});
+
+ +

Penyelesaian pada array

+ +
var p = Promise.resolve([1,2,3]);
+p.then(function(v) {
+  console.log(v[0]); // 1
+});
+
+ +

Penyelesaian pada Promise lain

+ +
var original = Promise.resolve(true);
+var cast = Promise.resolve(original);
+cast.then(function(v) {
+  console.log(v); // true
+});
+
+ +

Penyelesaian thenables dan throwing Errors

+ +
// Resolving a thenable object
+var p1 = Promise.resolve({
+  then: function(onFulfill, onReject) { onFulfill("fulfilled!"); }
+});
+console.log(p1 instanceof Promise) // true, object casted to a Promise
+
+p1.then(function(v) {
+    console.log(v); // "fulfilled!"
+  }, function(e) {
+    // not called
+});
+
+// Thenable throws before callback
+// Promise rejects
+var thenable = { then: function(resolve) {
+  throw new TypeError("Throwing");
+  resolve("Resolving");
+}};
+
+var p2 = Promise.resolve(thenable);
+p2.then(function(v) {
+  // not called
+}, function(e) {
+  console.log(e); // TypeError: Throwing
+});
+
+// Thenable throws after callback
+// Promise resolves
+var thenable = { then: function(resolve) {
+  resolve("Resolving");
+  throw new TypeError("Throwing");
+}};
+
+var p3 = Promise.resolve(thenable);
+p3.then(function(v) {
+  console.log(v); // "Resolving"
+}, function(e) {
+  // not called
+});
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +

 

+ + + +

{{Compat("javascript.builtins.Promise.resolve")}}

+ +

 

+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/promise/then/index.html b/files/id/web/javascript/reference/global_objects/promise/then/index.html new file mode 100644 index 0000000000..5a1e275c8c --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/promise/then/index.html @@ -0,0 +1,132 @@ +--- +title: Promise.prototype.then() +slug: Web/JavaScript/Reference/Global_Objects/Promise/then +tags: + - ECMAScript6 + - JavaScript + - Method + - Promise + - Prototype + - Referensi +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/then +--- +
{{JSRef}}
+ +

Method then() mengembalikan {{domxref("Promise")}}. Menggunakan dua argumen: fungsi callback untuk kasus sukses dan gagal pada Promise.

+ +

Sintaks

+ +
p.then(onFulfilled, onRejected);
+
+p.then(function(value) {
+   // fulfillment
+  }, function(reason) {
+  // rejection
+});
+
+ +

Parameter

+ +
+
onFulfilled
+
{{jsxref("Function")}} dipanggil ketika Promise dipenuhi. Fungsi ini memiliki satu argumen, value pemenuhan.
+
onRejected
+
{{jsxref("Function")}} dipangil ketika Promise ditolak. fungsi ini memiliki satau argumen, alasan penolakan.
+
+ +

Deskripsi

+ +

Kedua method then dan {{jsxref("Promise.prototype.catch()")}} megembalikan promis, juga dapat dirantaikan — operasi yang disebut composition.

+ +

Contoh

+ +

Meggunakan method then

+ +
var p1 = new Promise(function(resolve, reject) {
+  resolve("Success!");
+  // or
+  // reject ("Error!");
+});
+
+p1.then(function(value) {
+  console.log(value); // Success!
+}, function(reason) {
+  console.log(reason); // Error!
+});
+
+ +

Perantaian

+ +

Karena method then mengembalikan Promise, anda bisa merantaikan pemanggilan then.

+ +
var p2 = new Promise(function(resolve, reject) {
+  resolve(1);
+});
+
+p2.then(function(value) {
+  console.log(value); // 1
+  return value + 1;
+}).then(function(value) {
+  console.log(value); // 2
+});
+
+p2.then(function(value) {
+  console.log(value); // 1
+});
+
+ +

Anda juga bisa menggunakan perantaian untuk melaksanakan satu fungsi dengan sebuah Promise berbasis API diatas fungsi lainnya.

+ +
function fetch_current_data() {
+  // The fetch() API returns a Promise.  This function
+  // exposes a similar API, except the fulfillment
+  // value of this function's Promise has had more
+  // work done on it.
+  return fetch("current-data.json").then((response) => {
+    if (response.headers.get("content-type") != "application/json") {
+      throw new TypeError();
+    }
+    var j = response.json();
+    // maybe do something with j
+    return j; // fulfillment value given to user of
+              // fetch_current_data().then()
+  });
+}
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ + + +

{{Compat("javascript.builtins.Promise.then")}}

+ +

 

+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/regexp/index.html b/files/id/web/javascript/reference/global_objects/regexp/index.html new file mode 100644 index 0000000000..8bd6dce4b9 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/regexp/index.html @@ -0,0 +1,231 @@ +--- +title: RegExp +slug: Web/JavaScript/Reference/Global_Objects/RegExp +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp +--- +
{{JSRef}}

The RegExpobjek digunakan untuk pencocokan teks dengan pola.

+ +

Untuk pengantar ekspresi reguler, baca bab Ekspresi Reguler di Panduan JavaScript .

+ +

Deskripsi

+ +

Notasi dan konstruktor literal

+ +

Ada dua cara untuk membuat RegExpobjek: notasi literal dan konstruktor .

+ + + +

Tiga ekspresi berikut membuat ekspresi reguler yang sama:

+ +
/ab+c/i
+new RegExp(/ab+c/, 'i') // literal notation
+new RegExp('ab+c', 'i') // constructor
+
+ +

Notasi literal menghasilkan kompilasi dari ekspresi reguler ketika ekspresi dievaluasi. Gunakan notasi literal ketika ekspresi reguler akan tetap konstan. Misalnya, jika Anda menggunakan notasi literal untuk membuat ekspresi reguler yang digunakan dalam satu lingkaran, ekspresi reguler tidak akan dikompilasi ulang pada setiap iterasi.

+ +

Konstruktor objek ekspresi reguler — misalnya, new RegExp('ab+c')—menghasilkan kompilasi runtime dari ekspresi reguler. Gunakan fungsi konstruktor ketika Anda tahu pola ekspresi reguler akan berubah, atau Anda tidak tahu pola dan mendapatkannya dari sumber lain, seperti input pengguna.

+ +

Bendera dalam konstruktor

+ +

Dimulai dengan ECMAScript 6, new RegExp(/ab+c/, 'i')tidak lagi melempar a TypeError"can't supply flags when constructing one RegExp from another") ketika argumen pertama adalah a RegExpdan flagsargumen kedua hadir. Sebagai RegExpgantinya, argumen baru dibuat.

+ +

Saat menggunakan fungsi konstruktor, aturan pelolosan string normal (mendahului karakter khusus \ketika disertakan dalam string) diperlukan.

+ +

Misalnya, yang berikut ini setara:

+ +
let re = /\w+/
+let re = new RegExp('\\w+')
+
+ +

Properti Reg-suka seperti Perl

+ +

Perhatikan bahwa beberapa RegExpproperti memiliki nama panjang dan pendek (seperti Perl). Kedua nama selalu merujuk pada nilai yang sama. (Perl adalah bahasa pemrograman tempat JavaScript memodelkan ekspresi regulernya.). Lihat juga properti yang sudah usang RegExp.

+ +

Konstruktor

+ +
+
RegExp()
+
Menciptakan RegExpobjek baru .
+
+ +

Sifat statis

+ +
+
get RegExp[@@species]
+
The constructor function that is used to create derived objects.
+
RegExp.lastIndex
+
The index at which to start the next match.
+
+ +

Instance properties

+ +
+
RegExp.prototype.flags
+
A string that contains the flags of the RegExp object.
+
RegExp.prototype.dotAll
+
Whether . matches newlines or not.
+
RegExp.prototype.global
+
Whether to test the regular expression against all possible matches in a string, or only against the first.
+
RegExp.prototype.ignoreCase
+
Whether to ignore case while attempting a match in a string.
+
RegExp.prototype.multiline
+
Whether or not to search in strings across multiple lines.
+
RegExp.prototype.source
+
The text of the pattern.
+
RegExp.prototype.sticky
+
Whether or not the search is sticky.
+
RegExp.prototype.unicode
+
Whether or not Unicode features are enabled.
+
+ +

Instance methods

+ +
+
RegExp.prototype.compile()
+
(Re-)compiles a regular expression during execution of a script.
+
RegExp.prototype.exec()
+
Executes a search for a match in its string parameter.
+
RegExp.prototype.test()
+
Tests for a match in its string parameter.
+
RegExp.prototype.toString()
+
Returns a string representing the specified object. Overrides the Object.prototype.toString() method.
+
RegExp.prototype[@@match]()
+
Performs match to given string and returns match result.
+
RegExp.prototype[@@matchAll]()
+
Returns all matches of the regular expression against a string.
+
RegExp.prototype[@@replace]()
+
Replaces matches in given string with new substring.
+
RegExp.prototype[@@search]()
+
Searches the match in given string and returns the index the pattern found in the string.
+
RegExp.prototype[@@split]()
+
Splits given string into an array by separating the string into substring.
+
+ +

Examples

+ +

Using a regular expression to change data format

+ +

The following script uses the replace() method of the String instance to match a name in the format first last and output it in the format last, first.

+ +

In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

+ +
let re = /(\w+)\s(\w+)/
+let str = 'John Smith'
+let newstr = str.replace(re, '$2, $1')
+console.log(newstr)
+
+ +

This displays "Smith, John".

+ +

Using regular expression to split lines with different line endings/ends of line/line breaks

+ +

The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.

+ +
let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'
+let lines = text.split(/\r\n|\r|\n/)
+console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
+
+ +

Note that the order of the patterns in the regular expression matters.

+ +

Using regular expression on multiple lines

+ +
let s = 'Please yes\nmake my day!'
+
+s.match(/yes.*day/);
+// Returns null
+
+s.match(/yes[^]*day/);
+// Returns ["yes\nmake my day"]
+
+ +

Using a regular expression with the sticky flag

+ +

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at RegExp.prototype.lastIndex.

+ +
let str = '#foo#'
+let regex = /foo/y
+
+regex.lastIndex = 1
+regex.test(str)      // true
+regex.lastIndex = 5
+regex.test(str)      // false (lastIndex is taken into account with sticky flag)
+regex.lastIndex      // 0 (reset after match failure)
+ +

The difference between the sticky flag and the global flag

+ +

With the sticky flag y, the next match has to happen at the lastIndex position, while with the global flag g, the match can happen at the lastIndex position or later:

+ +
re = /\d/y;
+while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex);
+
+// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
+// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
+// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
+//   ... and no more match.
+ +

With the global flag g, all 6 digits would be matched, not just 3.

+ +

Regular expression and Unicode characters

+ +

As mentioned above, \w or \W only matches ASCII based characters; for example, a to zA to Z0 to 9, and _.

+ +

To match characters from other languages such as Cyrillic or Hebrew, use \uhhhh, where hhhh is the character's Unicode value in hexadecimal.

+ +

This example demonstrates how one can separate out Unicode characters from a word.

+ +
let text = 'Образец text на русском языке'
+let regex = /[\u0400-\u04FF]+/g
+
+let match = regex.exec(text)
+console.log(match[0])        // logs 'Образец'
+console.log(regex.lastIndex) // logs '7'
+
+let match2 = regex.exec(text)
+console.log(match2[0])       // logs 'на' [did not log 'text']
+console.log(regex.lastIndex) // logs '15'
+
+// and so on
+
+ +

The Unicode property escapes feature introduces a solution, by allowing for a statement as simple as \p{scx=Cyrl}. One can also use an external resource for getting the complete Unicode block range for different scripts, such as Regexp-Unicode-block.

+ +

Extracting sub-domain name from URL

+ +
let url = 'http://xxx.domain.com'
+console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'
+
+ +

Instead of using regular expressions for parsing URLs, it is usually better to use the browsers built-in URL parser by using the URL API.

+ +

Specifications

+ + + + + + + + + + + + +
Specification
ECMAScript (ECMA-262)
+ The definition of 'RegExp' in that specification.
+ +

Browser compatibility

+ +

{{Compat("javascript.builtins.RegExp")}}

+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/concat/index.html b/files/id/web/javascript/reference/global_objects/string/concat/index.html new file mode 100644 index 0000000000..0ba2b2a156 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/concat/index.html @@ -0,0 +1,134 @@ +--- +title: String.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/String/concat +tags: + - JavaScript + - Referensi + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/concat +--- +
{{JSRef}}
+ +

Method concat() menggabungkan dua teks atau lebih menjadi sebuah string baru.

+ +

Syntax

+ +
str.concat(string2, string3[, ..., stringN])
+ +

Parameter

+ +
+
string2...stringN
+
String untuk menggabungkan string.
+
+ +

Deskripsi

+ +

Fungsi concat() menggabungkan teks dari satu atau lebih string dan mengembalikanya menjadi sebuah string. Perubahan pada salah satu teks tidak mempengaruhi string lainnya.

+ +

Contoh

+ +

Penggunaan concat()

+ +

Untuk menggabungkan string menjadi sebuah string baru seperti pada contoh dibawah.

+ +
var halo = 'Halo, ';
+console.log(halo.concat('Didik', ' semoga hari ini menyenangkan.'));
+
+/* Halo, Didik semoga hari ini menyenangkan. */
+
+ +

Performa

+ +

Sangat disarankan untuk menggunakan {{jsxref("Operators/Assignment_Operators", "assignment operators", "", 1)}} (+, +=) pada method concat(). lihat test performa berikut ini.

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.6', 'String.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome untuk AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html b/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html new file mode 100644 index 0000000000..786e32883e --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html @@ -0,0 +1,143 @@ +--- +title: String.fromCharCode() +slug: Web/JavaScript/Reference/Global_Objects/String/fromCharCode +tags: + - JavaScript + - Method + - Metode + - Reference + - Referensi + - String + - Unicode +translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCharCode +--- +
{{JSRef}}
+ +

Metode statis String.fromCharCode() mengembalikan sebuah string yang dibuat dari barisan nilai Unicode tertentu.

+ +

Sintak

+ +
String.fromCharCode(num1[, ...[, numN]])
+ +

Parameter

+ +
+
num1, ..., numN
+
Barisan dari angka-angka yang merupakan nilai Unicode.Jangkauannya antara 0 sampai dengan 65535(0xFFFF).Nomor yang lebih besar dari 0xFFFF dipotong.Tidak ada cek validasi yang dilakukan.   
+
+ +

Nilai kembalian

+ +

Sebuah string yang di dalamnya terdapat karakter-karakter sesuai nilai Unicode dari barisan angka yang diberikan.

+ +

Deskripsi

+ +

Metode ini mengembalikan sebuah string dan bukan objek {{jsxref("String")}}.

+ +

Karena fromCharCode() merupakan metode statis dari {{jsxref("String")}}, Anda selalu bisa menggunakannya sebagai String.fromCharCode(), daripada sebagai metode dari objek {{jsxref("String")}} yang Anda buat.

+ +

Contoh

+ +

Menggunakan fromCharCode()

+ +

Contoh di bawah ini mengembalikan string "ABC".

+ +
String.fromCharCode(65, 66, 67);  // "ABC"
+
+ +

Membuatnya bekerja dengan nilai yang lebih tinggi

+ +

Meskipu nilai Unicode yang umum dapat digambarkan dengan satu angka 16-bit (seperti yang diharapkan pada awal mula standarisasi JavaScript) dan fromCharCode() dapat digunakan untuk mengembalikan sebuah karakter dari nilai yang paling umum (misal. nilai UCS-2 yang merupakan bagian dari UTF-16 dengan karakter yang paling umum digunakan). Untuk menghadapi SEMUA nilai Unicode yang sah (hingga 21 bit), fromCharCode() sendiri tidak dapat menghadapinya. Semenjak nilai code point karakter yang lebih tinggi menggunakan dua angka "pengganti"  (dengan nilai yang lebih rendah) untuk membuat sebuah karakter tunggal, {{jsxref("String.fromCodePoint()")}} (bagian dari draf ES6) dapat digunakan untuk menggunakan sepasang angka tersebut, sehingga dapat menampilkan karakter dengan nilai yang lebih tinggi.

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan dalam JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.3.2', 'StringfromCharCode')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ESDraft')}}
+ +

Kompabilitas peramban

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html b/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html new file mode 100644 index 0000000000..dc4024f941 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html @@ -0,0 +1,149 @@ +--- +title: String.fromCodePoint() +slug: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint +tags: + - ECMAScript 2015 + - JavaScript + - Metode + - Referensi + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint +--- +
{{JSRef}}
+ +

Metode String.fromCodePoint() mengembalikan string yang dibuat dengan menggunakan urutan titik kode yang ditentukan.

+ +
{{EmbedInteractiveExample("pages/js/string-fromcodepoint.html")}}
+ + + +

Syntax

+ +
String.fromCodePoint(num1[, ...[, numN]])
+ +

Parameters

+ +
+
num1, ..., numN
+
Urutan Poin Kode
+
+ +

Return value

+ +

String yang dibuat dengan menggunakan urutan titik kode yang ditentukan.

+ +

Exceptions

+ + + +

Description

+ +

Metode ini mengembalikan string dan bukan sebuah objek. {{jsxref("String")}} .

+ +

Karena fromCodePoint() adalah metode statik dari {{jsxref("String")}}, dan anda selalu menggunakannya sebagai String.fromCodePoint(), alih-alih sebagai sebuah metode yang anda buat {{jsxref("String")}}

+ +

Examples

+ +

Using fromCodePoint()

+ +
String.fromCodePoint(42);       // "*"
+String.fromCodePoint(65, 90);   // "AZ"
+String.fromCodePoint(0x404);    // "\u0404"
+String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
+String.fromCodePoint(194564);   // "\uD87E\uDC04"
+String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
+
+String.fromCodePoint('_');      // RangeError
+String.fromCodePoint(Infinity); // RangeError
+String.fromCodePoint(-1);       // RangeError
+String.fromCodePoint(3.14);     // RangeError
+String.fromCodePoint(3e-2);     // RangeError
+String.fromCodePoint(NaN);      // RangeError
+
+ +
// String.fromCharCode() sendiri tidak bisa mendapatkan karakter pada titik kode tinggi seperti itu
+// Disisi lain, dapat juga mengembalikan karakter 4-byte dan juga
+// yang biasa 2-byte (i.e., dapat mengembalikan satu karakter yang sebenarnya sudah dimiliki
+// string 2 daripada 1!)
+console.log(String.fromCodePoint(0x2F804)); // atau 194564 dalam bilangan desimal
+
+ +

Polyfill

+ +

Metode String.fromCodePoint telah ditambahkan ke ECMAScript 2015 dan mungkin belum didukung di semua browser web atau lingkungannya. Gunakan kode dibawah ini untuk polyfill:

+ +
if (!String.fromCodePoint) (function(stringFromCharCode) {
+    var fromCodePoint = function(_) {
+      var codeUnits = [], codeLen = 0, result = "";
+      for (var index=0, len = arguments.length; index !== len; ++index) {
+        var codePoint = +arguments[index];
+        // correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
+        // The surrounding `!(...)` is required to correctly handle `NaN` cases
+        // The (codePoint>>>0) === codePoint clause handles decimals and negatives
+        if (!(codePoint < 0x10FFFF && (codePoint>>>0) === codePoint))
+          throw RangeError("Invalid code point: " + codePoint);
+        if (codePoint <= 0xFFFF) { // BMP code point
+          codeLen = codeUnits.push(codePoint);
+        } else { // Astral code point; split in surrogate halves
+          // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
+          codePoint -= 0x10000;
+          codeLen = codeUnits.push(
+            (codePoint >> 10) + 0xD800,  // highSurrogate
+            (codePoint % 0x400) + 0xDC00 // lowSurrogate
+          );
+        }
+        if (codeLen >= 0x3fff) {
+          result += stringFromCharCode.apply(null, codeUnits);
+          codeUnits.length = 0;
+        }
+      }
+      return result + stringFromCharCode.apply(null, codeUnits);
+    };
+    try { // IE 8 only supports `Object.defineProperty` on DOM elements
+      Object.defineProperty(String, "fromCodePoint", {
+        "value": fromCodePoint, "configurable": true, "writable": true
+      });
+    } catch(e) {
+      String.fromCodePoint = fromCodePoint;
+    }
+}(String.fromCharCode));
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}{{Spec2('ES2015')}}Definisi Awal
{{SpecName('ESDraft', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.fromCodePoint")}}

+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/index.html b/files/id/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..35f78502d5 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,371 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript6 + - JavaScript + - Reference + - Referensi + - Referensı(2) + - Référence(2) + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef("Global_Objects", "String")}}
+ +

Ringkasan

+ +

Objek global String adalah sebuah pembangun untuk string, atau sebuah rangkaian dari karakter.

+ +

Sintak

+ +

String secara harfiah berbentuk:

+ +
'string text'
+"string text"
+"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ்"
+
+ +

Sejak ECMAScript 6 String secara harfiah dapat juga menjadi Template Strings:

+ +
`hello world`
+`hello!
+ world!`
+`hello ${who}`
+escape `<a>${who}</a>`
+ +

Selain karakter biasa yang dapat dicetak, karakter spesial dapat disandikan dengan notasi lepas:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KodeKeluaran
\0karakter NUL
\'petik satu
\"petik dua
\\garis miring
\nbaris baru
\rcarriage return
\vtab vertikal
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXkarakter Latin-1
+ +

Atau, menggunakan objek global String langsung:

+ +
String(benda)
+new String(benda)
+
+ +

Parameter

+ +
+
benda
+
Apapun yang akan diubah ke string.
+
+ +

Deskripsi

+ +

String berguna untuk membawa data yang dapat diitampilkan dalam bentuk teks. Beberapa operasi yang paling sering digunakan dalam string adalah untuk memeriksa {{jsxref("String.length", "panjangnya")}}, untuk membuat dan menggabungkannya dengan operator string + dan +=, mengecek adanya atau lokasi dari substring dengan metode {{jsxref("String.prototype.indexOf()", "indexOf()")}}, atau mendapatkan substring dengan metode {{jsxref("String.prototype.substring()", "substring()")}}.

+ +

Akses karakter

+ +

Ada dua cara untuk mengakses sebuah karakter dalam string. Cara yang pertama adalah metode {{jsxref("String.prototype.charAt()", "charAt()")}}:

+ +
return 'cat'.charAt(1); // mengembalikan "a"
+
+ +

Cara yang lain (diperkenalkan dalam ECMAScript 5) adalah menganggap string sebagai objek mirip-susunan, di mana setiap karakter disesuaikan dengan indeks angka:

+ +
return 'cat'[1]; // mengembalikan "a"
+
+ +

Untuk akses karakter dengan menggunakan notasi kurung, mencoba untuk menghapus atau menetapkan nilai ke propertinya tidak akan berhasil. Properti yang terlibat tidak dapat ditulis maupun diubah. (Lihat {{jsxref("Object.defineProperty()")}} untuk informasi lebih.)

+ +

Membandingkan string

+ +

Pengembang C mempunyai fungsi strcmp() untuk membandingkan string. Dalam JavaScript, Anda cukup menggunakan operas kurang dari dan lebih dari:

+ +
var a = 'a';
+var b = 'b';
+if (a < b) { // benar
+  print(a + ' kurang dari ' + b);
+} else if (a > b) {
+  print(a + ' lebih dari ' + b);
+} else {
+  print(a + ' sama dengan ' + b);
+}
+
+ +

Hasil yang serupa dapat didapatkan dengan metode {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} yang diwariskan oleh benda String.

+ +

Perbedaan antara string primitif dan objek String

+ +

Ingat bahwa JavaScript membedakan nilai antara objek String dan string primitif. (Serupa dengan {{jsxref("Global_Objects/Boolean", "Boolean")}} dan {{jsxref("Global_Objects/Number", "Angka")}}.)

+ +

String yang harfiah (ditandai dengan petik satu atau dua) dan string yang dikembalikan dari panggilan String dalam sebuah konteks non-pembangun (misal, tanpa menggunakan kata kunci {{jsxref("Operators/new", "new")}}) adalah string primitif. JavaScript secara otomatis mengubah primitif ke objek String, jadi mungkin untuk menggunakan metode objek String untuk string primitif. Dalam konteks di mana sebuah metode dipanggil pada string primitif atau sebuah pembacaan properti terjadi, JavaScript akan secara otomatis membungkus string primitif dan memanggil metode tersebut atau melakukan pembacaan properti.

+ +
var s_prim = 'foo';
+var s_obj = new String(s_prim);
+
+console.log(typeof s_prim); // "string"
+console.log(typeof s_obj);  // "object"
+
+ +

String primitif dan objek String juga memberikan hasil berbeda saat menggunakan {{jsxref("Global_Objects/eval", "eval()")}}. Primitif melewati eval sebagai kode sumber; Objek String dianggap semua objek lain, dengan mengembalikan objek tersebut. Sebagai contoh:

+ +
var s1 = '2 + 2';             // membuat sebuah string primitif
+var s2 = new String('2 + 2'); // membuat sebuah objek String
+console.log(eval(s1));        // mengembalikan angka 4
+console.log(eval(s2));        // mengembalikan string "2 + 2"
+
+ +

Untuk itu, kode mungkin berhenti saat menemui objek String saat mengharapkan string primitif, meskipun secara umum pembuat tidak perlu khawatir tentang perbedaannya.

+ +

Sebuah objek String dapat selalu diubah menjadi kawan primitifnya dengan metode {{jsxref("String.prototype.valueOf()", "valueOf()")}}.

+ +
console.log(eval(s2.valueOf())); // mengembalikan angka 4
+
+ +
Catatan: Untuk kemungkinan lain ke string dalam JavaScript, mohon baca artikel tentang StringView — a C-like representation of strings based on typed arrays (bahasa Inggris).
+ +

Properti

+ +
+
{{jsxref("String.prototype")}}
+
Membolehkan penambahan properti ke sebuahobjek String.
+
+ +
{{jsOverrides("Function", "Properties", "prototype")}}
+ +

Metode

+ +
+
{{jsxref("String.fromCharCode()")}}
+
Mengembalikan sebuah string yang dibuat dengan menggunakan nilai urutan Unicode.
+
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
+
Mengembalikan sebuah string dibuat dengan menggunakan urutan code points.
+
{{jsxref("String.raw()")}} {{experimental_inline}}
+
Mengembalikan sebuah string yang dibuat dari sebuah templat string mentah.
+
+ +
{{jsOverrides("Function", "Methods", "fromCharCode", "fromCodePoint", "raw")}}
+ +

Metode umum String

+ +

Metode benda String juga terdapat dalam Firefox sejak JavaScript 1.6 (meskipun bukan bagian dari standar ECMAScript) salam objek String untuk menerapkan metode String ke objek lain:

+ +
var num = 15;
+console.log(String.replace(num, /5/, '2'));
+
+ +

{{jsxref("Global_Objects/Array", "Metode umum", "#Metode_umum_Array", 1)}} juga terdapat dalam metode {{jsxref("Global_Objects/Array", "Array")}}.

+ +

Berikut ini sebuah pengisi untuk memberikan dukungan ke peramban yang tidak mendukung:

+ +
/*globals define*/
+// Menganggap semua metode String telah ada
+(function() {
+  'use strict';
+
+  var i,
+    methods = [
+      'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
+      'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
+      'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
+      'toLocaleUpperCase', 'localeCompare', 'match', 'search',
+      'replace', 'split', 'substr', 'concat', 'slice'
+    ],
+    methodCount = methods.length,
+    assignStringGeneric = function(methodName) {
+      var method = String.prototype[methodName];
+      String[methodName] = function(arg1) {
+        return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
+      };
+    };
+
+  for (i = 0; i < methodCount; i++) {
+    assignStringGeneric(methods[i]);
+  }
+}());
+
+ +

Benda String

+ +

Properti

+ +
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properti')}}
+ +

Metode

+ +

Metode yang tidak terkait dengan HTML

+ +
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Metode_yang_tidak_terkait_dengan_HTML')}}
+ +

Metode pembungkus HTML

+ +
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Metode_pembungkus_HTML')}}
+ +

Contoh

+ +

Contoh: Pengubahan String

+ +

Ini mungkin untuk menggunakan String sebagai alternatif "lebih aman" dari {{jsxref("String.prototype.toString()", "toString()")}}, meskipun masih dapat secara normal memanggil toString(), ini juga bekerja untuk {{jsxref("Global_Objects/null", "null")}} dan {{jsxref("Global_Objects/undefined", "undefined")}}. Sebagai contoh:

+ +
var outputStrings = [];
+for (var i = 0, n = inputValues.length; i < n; ++i) {
+  outputStrings.push(String(inputValues[i]));
+}
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
ECMAScript 1st Edition.StandardDefinisi pertama.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string-objects', 'String')}}{{Spec2('ES6')}} 
+ +

Kompatibilitas peramban

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("0.2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown()}}{{CompatGeckoDesktop("40")}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("40")}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/indexof/index.html b/files/id/web/javascript/reference/global_objects/string/indexof/index.html new file mode 100644 index 0000000000..3b7f7d0965 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/indexof/index.html @@ -0,0 +1,190 @@ +--- +title: String.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/indexOf +translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf +--- +
{{JSRef}}
+ +

indexOf() method mengembalikan sebuah index saat memanggil objek  {{jsxref("String")}} pertama kali dengan value yang di tentukan, bermula dari pencarian pada fromIndex. Dan pencarian ini akan mengembalikan index dari karakter pada String,  dan akan mengembalikan -1 ketika pencarian indexOf ini tak menemukan karakter yang cocok/ value yang sesuai.

+ +

Syntax

+ +
str.indexOf(searchValue[, fromIndex])
+ +

Parameters

+ +
+
searchValue
+
Sebuah string yang me-representasikan dari nilai yang ingin di cari.
+
fromIndex {{optional_inline}}
+
Index bermulai dari awal hingga bergerak ke depan sepanjang string. Index bisa berupa bilangan bulat atau apa pun. Nilai standarnya adalah 0, jadi seluruh index dari array akan dicari. Jika fromIndex < 0 seluruh string dicari. Jika fromIndex >= str.length, string tidak dicari dan -1 sebagai kembaliannya. Kecuali kalau searchValue adalah string kosong, maka str.length sebagai kembaliannya.
+
+ +

Deskripsi

+ +

Karakter dalam sebuah string di indeks berurutan dari kiri ke kanan. Index pada karakter pertama yaitu 0, dan index pada karakter terakhir dalam sebuah String di sebut stringName is stringName.length - 1.

+ +
'Blue Whale'.indexOf('Blue');     // mengembalikan  0
+'Blue Whale'.indexOf('Blute');    // mengembalikan -1
+'Blue Whale'.indexOf('Whale', 0); // mengembalikan  5
+'Blue Whale'.indexOf('Whale', 5); // mengembalikan  5
+'Blue Whale'.indexOf('', 9);      // mengembalikan  9
+'Blue Whale'.indexOf('', 10);     // mengembalikan 10
+'Blue Whale'.indexOf('', 11);     // mengembalikan 10
+
+ +

Case-sensitivity

+ +

The indexOf() method sangat case sensitive. Sebagai contoh, expression berikut ini mengembalikan -1:

+ +
'Blue Whale'.indexOf('blue'); // mengembalikan -1
+
+ +

Checking occurrences/ Memeriksa suatu kejadian

+ +

Catat bahwa  '0' tak bernilai true dan '-1' bukan bernilali false. Oleh karena-nya, ketika memeriksa apakah sebuah String  Therefore, when checking if a specific string exists within another string the correct way to check would be:

+ +
'Blue Whale'.indexOf('Blue') !== -1; // true
+'Blue Whale'.indexOf('Bloe') !== -1; // false
+
+ +

Examples

+ +

Using indexOf() and lastIndexOf()

+ +

The following example uses indexOf() and {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} to locate values in the string "Brave new world".

+ +
var anyString = 'Brave new world';
+
+console.log('The index of the first w from the beginning is ' + anyString.indexOf('w'));
+// logs 8
+console.log('The index of the last w from the beginning is ' + anyString.lastIndexOf('w'));
+// logs 10
+
+console.log('The index of "new" from the beginning is ' + anyString.indexOf('new'));
+// logs 6
+console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new'));
+// logs 6
+
+ +

indexOf() and case-sensitivity

+ +

The following example defines two string variables. The variables contain the same string except that the second string contains uppercase letters. The first {{domxref("console.log()")}} method displays 19. But because the indexOf() method is case sensitive, the string "cheddar" is not found in myCapString, so the second console.log() method displays -1.

+ +
var myString    = 'brie, pepper jack, cheddar';
+var myCapString = 'Brie, Pepper Jack, Cheddar';
+
+console.log('myString.indexOf("cheddar") is ' + myString.indexOf('cheddar'));
+// logs 19
+console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar'));
+// logs -1
+
+ +

Using indexOf() to count occurrences of a letter in a string

+ +

The following example sets count to the number of occurrences of the letter e in the string str:

+ +
var str = 'To be, or not to be, that is the question.';
+var count = 0;
+var pos = str.indexOf('e');
+
+while (pos !== -1) {
+  count++;
+  pos = str.indexOf('e', pos + 1);
+}
+
+console.log(count); // displays 4
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/length/index.html b/files/id/web/javascript/reference/global_objects/string/length/index.html new file mode 100644 index 0000000000..6975d8b7d3 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/length/index.html @@ -0,0 +1,126 @@ +--- +title: String.length +slug: Web/JavaScript/Reference/Global_Objects/String/length +translation_of: Web/JavaScript/Reference/Global_Objects/String/length +--- +
{{JSRef}}
+ +

Properti length mewakili panjang string.

+ +

Syntax

+ +
str.length
+ +

Deskripsi

+ +

Properti ini mengembalikan jumlah unit kode dalam string. {{interwiki("wikipedia", "UTF-16")}}, Format string yang digunakan oleh javascript, Menggunakan 16-bit unit kode tunggal untuk mewakili karakter yang paling umum, tapi perlu menggunakan dua unit kode untuk unit karakter tertentu, sehingga dapat terjadi kemungkinan nilai yang dikembalikan oleh ​​​length tidak sesuai dengan jumlah karakter pada string.

+ +

Untuk string kosong, jumlahnya 0.

+ +

Properti static String.length mengembalikan nilai 1.

+ +

Contoh

+ +

Penggunaan Dasar

+ +
var x = 'Mozilla';
+var kosong = '';
+
+console.log('Mozilla memiliki ' + x.length + ' unit kode');
+/* "Mozilla memiliki 7 unit kode" */
+
+console.log('String kosong memiliki jumlah unit kode ' + kosong.length);
+/* "String kosong memiliki jumlah unit kode 0" */
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi Inisial. Diimplementasikan dalam JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/link/index.html b/files/id/web/javascript/reference/global_objects/string/link/index.html new file mode 100644 index 0000000000..914eff9955 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/link/index.html @@ -0,0 +1,130 @@ +--- +title: String.prototype.link() +slug: Web/JavaScript/Reference/Global_Objects/String/link +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/link +--- +
{{JSRef}}
+ +

Method link() membuat sebuah string seperti halnya kode untuk sebuah elemen HTML {{HTMLElement("a")}} untuk digunakan sebagai link hypertext ke URL lain.

+ +

Sintaks

+ +
str.link(url)
+ +

Parameters

+ +
+
url
+
String yang menentukan atribut href dai tag <a>; harus merupakan URL yang valid (relative ataupun absolute), dengan setiap karakter & harus ditulis &amp;, dan setiap karakter " harus ditulis &quot;.
+
+ +

Deskripsi

+ +

Menggunakan method link() untuk membuat snippet HTML untuk sebuah link hypertext. Mengembalikan string  yang kemudian dapat di tambahkan ke dokumen html menggunakan {{domxref("document.write()")}} atau {{domxref("element.innerHTML")}}.

+ +

Link yang dibuat menggunakan method link() akan menjadi elemen di array links dari sebuah objek document. Lihat juga {{domxref("document.links")}}.

+ +

Contoh

+ +

Penggunaan link()

+ +

Pada contoh berikut menampilkan kata "MDN" sebagai sebuah link hypertext yang mengembalikan pengguna ke halaman Mozilla Developer Network.

+ +
var hotText = 'MDN';
+var URL = 'https://developer.mozilla.org/';
+
+console.log('Klik untuk kembali ke ' + hotText.link(URL));
+// Klik untuk kembali ke <a href="https://developer.mozilla.org/">MDN</a>
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-string.prototype.link', 'String.prototype.link')}}{{Spec2('ES6')}}Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
{{SpecName('ESDraft', '#sec-string.prototype.link', 'String.prototype.link')}}{{Spec2('ESDraft')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Catatan Gecko-specific

+ + + +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/purwarupa/index.html b/files/id/web/javascript/reference/global_objects/string/purwarupa/index.html new file mode 100644 index 0000000000..3570a3627a --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/purwarupa/index.html @@ -0,0 +1,221 @@ +--- +title: String.prototype +slug: Web/JavaScript/Reference/Global_Objects/String/purwarupa +tags: + - JavaScript + - Property + - Prototype + - Reference + - Referensi + - String + - purwarupa +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

Properti String.prototype mewakili objek prototype {{jsxref("Global_Objects/String", "String")}}.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Deskripsi

+ +

Semua benda {{jsxref("Global_Objects/String", "String")}} diwariskan dari String.prototype. Perubahan ke objek purwarupa String disebarkan ke semua benda {{jsxref("Global_Objects/String", "String")}}.

+ +

Properti

+ +
+
String.prototype.constructor
+
Menentukan fungsi yang membuat sebuah purwarupa dari objek.
+
{{jsxref("String.prototype.length")}}
+
Menggambarkan panjang dari string.
+
N
+
Digunakan untuk mengakses karakter pada posisi ke-N di mana N adalah sebuah bilangan bulat positif antara 0 dan nilai dari {{jsxref("String.length", "panjang")}} dikurangi satu. Nilai ini baca-saja.
+
+ +

Metode

+ +

Metode yang tidak terkait dengan HTML

+ +
+
{{jsxref("String.prototype.charAt()")}}
+
Mengembalikan karakter pada indeks yang diberikan.
+
{{jsxref("String.prototype.charCodeAt()")}}
+
Mengembalikan sebuah angka yang menggambarkan nilai Unicode dari karakter pada indeks yang diberikan.
+
{{jsxref("String.prototype.codePointAt()")}} {{experimental_inline}}
+
Mengembalikan sebuah bilangan bulat non negatif yang merupakan nilai penyandian code point UTF-16 pada posisi yang diberikan.
+
{{jsxref("String.prototype.concat()")}}
+
Menggabungkan teks dari dua string dan mengembalikan sebuah string baru.
+
{{jsxref("String.prototype.includes()")}} {{experimental_inline}}
+
Menentukan apakah satu string mungkin terdapat pada string lain.
+
{{jsxref("String.prototype.endsWith()")}} {{experimental_inline}}
+
Menentukan apakah sebuah string berakhir dengan karakter dari string lain.
+
{{jsxref("String.prototype.indexOf()")}}
+
Mengembalikan indeks pada objek {{jsxref("Global_Objects/String", "String")}} terpanggil dari pertemuan pertama dari nilai yang diberikan, atau -1 jika tidak ditemukan.
+
{{jsxref("String.prototype.lastIndexOf()")}}
+
Mengembalikan indeks pada objek {{jsxref("Global_Objects/String", "String")}} terpanggil dari pertemuan terakhir dari nilai yang diberikan, atau -1 jika tidak ditemukan.
+
{{jsxref("String.prototype.localeCompare()")}}
+
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
+
{{jsxref("String.prototype.match()")}}
+
Digunakan untuk mencocokkan sebuah regular expression pada string.
+
{{jsxref("String.prototype.normalize()")}} {{experimental_inline}}
+
Mengembalikan Unicode Normalization Form dari string terpanggil.
+
{{jsxref("String.prototype.quote()")}} {{obsolete_inline}}
+
Membungkus string dalam petik ganda (""").
+
{{jsxref("String.prototype.repeat()")}} {{experimental_inline}}
+
Mengembalikan sebuah string yang tersiri dari elemen-elemen dari objek yang diulangi sebanyak yang diberikan.
+
{{jsxref("String.prototype.replace()")}}
+
Digunakan untuk mencari kecocokkan antara sebuah regular expression dan sebuah string, dan untuk menggantikan substring yang cocok dengan substring yang baru.
+
{{jsxref("String.prototype.search()")}}
+
Menjalankan pencarian untuk sebuah kecocokan antara sebuah regular expression dan sebuah string yang diberikan.
+
{{jsxref("String.prototype.slice()")}}
+
Menghasilkan sebuah bagian dari string dan mengembalikan sebuah string baru.
+
{{jsxref("String.prototype.split()")}}
+
Memisahkan sebuah objek {{jsxref("Global_Objects/String", "String")}} ke dalam sebuah susunan dari string dengan memisahkan string ke dalam substring.
+
{{jsxref("String.prototype.startsWith()")}} {{experimental_inline}}
+
Menentukan apakah sebuah string dimulai dengan karakter dari string lain.
+
{{jsxref("String.prototype.substr()")}}
+
Mengembalikan karakter-karakter dalam sebuah string yang dimulai dari indeks yang diberikan sebanyak jumlah karakter yang diberikan.
+
{{jsxref("String.prototype.substring()")}}
+
Mengembalikan karakter-karakter dalam sebuah string antara dua indeks ke dalam string.
+
{{jsxref("String.prototype.toLocaleLowerCase()")}}
+
Karakter-karakter di dalam string diubah menjadi huruf kecil dengan menjunjung tempat sekarang. Kebanyakan bahasa akan mengembalikan hasil yang sama seperti {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}.
+
{{jsxref("String.prototype.toLocaleUpperCase()")}}
+
Karakter-karakter di dalam string diubah menjadi huruf kapital dengan menjunjung tempat sekarang. Kebanyakan bahasa akan mengembalikan hasil yang sama seperti {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}}.
+
{{jsxref("String.prototype.toLowerCase()")}}
+
Mengembalikan nilai string terpanggil yang diubah menjadi huruf kecil.
+
{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}}
+
Mengembalikan sebuah objek harfiah yang menggambarkan objek yang diberikan; Anda dapat menggunakan nilai ini untuk membuat sebuah objek baru. Mengesampingkan metode {{jsxref("Object.prototype.toSource()")}}.
+
{{jsxref("String.prototype.toString()")}}
+
Mengembalikan sebuah string menggambarkan objek yang diberikan. Mengesampingkan metode {{jsxref("Object.prototype.toString()")}}.
+
{{jsxref("String.prototype.toUpperCase()")}}
+
Mengembalikan nilai string terpanggil yang diubah menjadi huruf kapital.
+
{{jsxref("String.prototype.trim()")}}
+
Memotong whitespace dari permulaan dan akhir string. Bagian dari standar ECMAScript 5.
+
{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}
+
Memotong whitespace dari sisi kiri dari string.
+
{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}
+
Memotong whitespace dari sisi kanan dari string.
+
{{jsxref("String.prototype.valueOf()")}}
+
Mengembalikan nilai primitif dari objek yang diberikan. Mengesampingkan metode {{jsxref("Object.prototype.valueOf()")}}.
+
{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}} {{experimental_inline}}
+
Mengembalikan sebuah objek Iterator baru yang mengulangi melewati code points dari nilai String, mengembalikan setiap code point sebagai sebuah nilai String.
+
+ +

Metode pembungkus HTML

+ +

Metode-metode ini merupakan penggunaan terbatas, karena mereka hanya memberikan sebuah subset dari tag dan atribut HTML yang tersedia.

+ +
+
{{jsxref("String.prototype.anchor()")}}
+
{{htmlattrxref("name", "a", "<a name=\"name\">")}} (menarget hiperteks)
+
{{jsxref("String.prototype.big()")}} {{deprecated_inline}}
+
{{HTMLElement("big")}}
+
{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}
+
{{HTMLElement("blink")}}
+
{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}
+
{{HTMLElement("b")}}
+
{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}
+
{{HTMLElement("tt")}}
+
{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}
+
{{htmlattrxref("color", "font", "<font color=\"color\">")}}
+
{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}
+
{{htmlattrxref("size", "font", "<font size=\"size\">")}}
+
{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}
+
{{HTMLElement("i")}}
+
{{jsxref("String.prototype.link()")}}
+
{{htmlattrxref("href", "a", "<a href=\"url\">")}} (tautan ke URL)
+
{{jsxref("String.prototype.small()")}} {{deprecated_inline}}
+
{{HTMLElement("small")}}
+
{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}
+
{{HTMLElement("strike")}}
+
{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}
+
{{HTMLElement("sub")}}
+
{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}
+
{{HTMLElement("sup")}}
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
ECMAScript 1st Edition.StandardDefinisi awal.
{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ES6')}} 
+ +

Kompatibilitas peramban

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/split/index.html b/files/id/web/javascript/reference/global_objects/string/split/index.html new file mode 100644 index 0000000000..21f19d353f --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/split/index.html @@ -0,0 +1,241 @@ +--- +title: String.prototype.split() +slug: Web/JavaScript/Reference/Global_Objects/String/split +tags: + - JavaScript + - Method + - Prototype + - Reference + - Regular Expressions + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/split +--- +
{{JSRef}}
+ +

Method split() membagi sebuah objek {{jsxref("String")}} ke sebuah array string dengan memisahkannya menjadi substring.

+ +

Sintaks

+ +
str.split([separator[, limit]])
+ +

Parameter

+ +
+
separator
+
Opsional. Menentukan karakter yang digunakan untuk memisahkan string. separator dapat berupa string atau sebuah {{jsxref("Global_Objects/RegExp", "regular expression", "", 1)}}. Jika separator dihilangkan / tidak digunakan, array yang dikembalikan akan terdiri dari satu elemen yang berisi seluruh string. Jika separator dikosongkan atau empty string, str akan dikonversikan sebagai sebuah array dari karakter.
+
limit
+
+

Opsional. Nilai integer yang digunakan untuk menentukan jumlah batas yang dapat ditemukan. Method split() tetap membagi pada setiap kecocokan pada separator, sampai jumlah pembagi item sama dengan limit atau string jatuh lebih pendek dari separator.

+
+
+ +

Deskripsi

+ +

Method split() mengembalikan array baru.

+ +

Saat ditemukan, separator akan dihapus dari string dan substrings akan di kembalikan ke dalam array. Jika separator tidak ditemukan atau di hilangkan, array terdiri satu elemen array yang terdiri dari keseluruhan string. Jika separator merupakan empty string, str dikonversi menjadi sebuah array karakter.

+ +

Jika separator adalah ekspesi reguler yang terdapat tanda kurung , maka setiap kali separator cocok, hasilnya (termasuk hasil yang tidak didefinisikan) dari penangkap tanda kurung akan di sambungkan ke dalam output array. Namun, tidak semua browser mendukung kemampuan ini.

+ +

{{Note("Ketika string kosong, method split() mengembalikan array berisi satu string kosong, dari pada array kosong. Jika string dan separator keduanya string kosong, array kosong akan dikembalikan.")}}

+ +

Contoh

+ +

Penggunaan split()

+ +

Contoh berikut menjelaskan fungsi yang membagi string ke dalam sebuah array string menggunakan separator tertentu. Setelah memisahkan string , fungsi menampilkan pesan yang menunjukan string asli (sebelum dibagi), separator yang digunakan, jumlah elemen pada array, dan elemen array secara individual.

+ +
function splitString(stringToSplit, separator) {
+  var arrayOfStrings = stringToSplit.split(separator);
+
+  console.log('The original string is: "' + stringToSplit + '"');
+  console.log('The separator is: "' + separator + '"');
+  console.log('The array has ' + arrayOfStrings.length + ' elements: ' + arrayOfStrings.join(' / '));
+}
+
+var tempestString = 'Oh brave new world that has such people in it.';
+var monthString = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec';
+
+var space = ' ';
+var comma = ',';
+
+splitString(tempestString, space);
+splitString(tempestString);
+splitString(monthString, comma);
+
+ +

Contoh ini menghasilkan output berikut:

+ +
The original string is: "Oh brave new world that has such people in it."
+The separator is: " "
+The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it.
+
+The original string is: "Oh brave new world that has such people in it."
+The separator is: "undefined"
+The array has 1 elements: Oh brave new world that has such people in it.
+
+The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
+The separator is: ","
+The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec
+
+ +

Menghapus spasi dari string

+ +

Pada contoh berikut, split() mencari 0 atau lebih spasi diikuti semikolon, dan di ikuti 0 atau lebih spasi dan, saat ditemukan, menghapus spasi dari string. nameList merupakan array yang dikembalikan dari hasil split().

+ +
var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ';
+
+console.log(names);
+
+var re = /\s*;\s*/;
+var nameList = names.split(re);
+
+console.log(nameList);
+
+ +

Dua baris log ini; log baris pertama string asli, dan log baris kedua array yang dihasilkan.

+ +
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
+[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand " ]
+
+ +

Mengembalikan batas jumlah pembagi

+ +

Pada contoh berikut, split() mencari 0 atau lebih spasi didalam string dan mengembalikan 3 pembagian pertama yang ditemukan.

+ +
var myString = 'Hello World. How are you doing?';
+var splits = myString.split(' ', 3);
+
+console.log(splits);
+
+ +

Script ini akan menampilkan seperti berikut:

+ +
Hello,World.,How
+
+ +

Tanda kurung

+ +

Jika separator terdapat tanda kurung, hasil yang cocok akan dikembalikan ke dalam array.

+ +
var myString = 'Hello 1 word. Sentence number 2.';
+var splits = myString.split(/(\d)/);
+
+console.log(splits);
+
+ +

Script tersebut menampilkan seperti berikut:

+ +
[ 'Hello ', '1', ' word. Sentence number ', '2', '.' ]
+
+ +

Membalikkan String menggunakan split()

+ +
var str = 'asdfghjkl';
+var strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
+// split() returns an array on which reverse() and join() can be applied
+
+ +

Bonus: Gunakan operator {{jsxref("Operators/Comparison_Operators", "===", "#Identity_strict_equality_(===)")}} untuk mengetahui apakah string asli adalah palindrome.

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.5.4.14', 'String.prototype.split')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
+ + + + + + + +
Dukungan dasar 
+
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html new file mode 100644 index 0000000000..69fdfd1bec --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html @@ -0,0 +1,121 @@ +--- +title: String.prototype.toLowerCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +--- +
{{JSRef}}
+ +

Method toLowerCase() mengembalikan nilai string yang dipanggil yang telah dikonversi ke lowercase (huruf kecil).

+ +

Sintaks

+ +
str.toLowerCase()
+ +

Deskripsi

+ +

Method toLowerCase() mengembaikan nilai dari string yang telah dikonversi ke lowercase. toLowerCase() tidak berdampak pada nilai string pada variabel str itu sendiri.

+ +

Contoh

+ +

Penggunaan toLowerCase()

+ +
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/tostring/index.html b/files/id/web/javascript/reference/global_objects/string/tostring/index.html new file mode 100644 index 0000000000..dba9c9f792 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/tostring/index.html @@ -0,0 +1,118 @@ +--- +title: String.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/String/toString +translation_of: Web/JavaScript/Reference/Global_Objects/String/toString +--- +
{{JSRef}}
+ +

Method toString() mengembalikan sebuah string berdasarkan objek spesifik.

+ +

Sintaks

+ +
str.toString()
+ +

Deskripsi

+ +

Objek {{jsxref("String")}} akan menimpa method toString() dari objek {{jsxref("Object")}}; bukan turunan {{jsxref("Object.prototype.toString()")}}. Untuk objek {{jsxref("String")}}, method toString() mengembalikan sebuah string berdasarkan objek dan seperti halnya pada method {{jsxref("String.prototype.valueOf()")}}.

+ +

Contoh

+ +

Penggunaan toString()

+ +

Pada contoh menampilkan nilai string dari sebuah objek {{jsxref("String")}}:

+ +
var x = new String('Halo Dunia');
+
+console.log(x.toString()); // logs 'Halo Dunia'
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.5.4.2', 'String.prototype.toString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.tostring', 'String.prototype.toString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.tostring', 'String.prototype.toString')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/global_objects/string/touppercase/index.html b/files/id/web/javascript/reference/global_objects/string/touppercase/index.html new file mode 100644 index 0000000000..bf8182a590 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/string/touppercase/index.html @@ -0,0 +1,115 @@ +--- +title: String.prototype.toUpperCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +translation_of: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +--- +
{{JSRef}}
+ +

Method toUpperCase() mengembalikan nilai string pemanggil dikonversi ke huruf besar.

+ +

Sintaks

+ +
str.toUpperCase()
+ +

Deskripsi

+ +

Method toUpperCase() mengembalikan nilai string diconversikan ke huruf besar. toUpperCase() tidak mempengaruhi nilai string itu sendiri.

+ +

Contoh

+ +

Penggunaan toUpperCase()

+ +
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.18', 'String.prototype.toUpperCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas browser

+ +
{{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}}
+
+ +

Lihat Pula

+ + diff --git a/files/id/web/javascript/reference/global_objects/typedarray/index.html b/files/id/web/javascript/reference/global_objects/typedarray/index.html new file mode 100644 index 0000000000..e0b8d942c1 --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/typedarray/index.html @@ -0,0 +1,344 @@ +--- +title: TypedArray +slug: Web/JavaScript/Reference/Global_Objects/TypedArray +tags: + - JavaScript + - NeedsTranslation + - TopicStub + - TypedArray + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray +--- +
{{JSRef}}
+ +

A TypedArray object describes an array-like view of an underlying binary data buffer. There is no global property named TypedArray, nor is there a directly visible TypedArray constructor.  Instead, there are a number of different global properties, whose values are typed array constructors for specific element types, listed below. On the following pages you will find common properties and methods that can be used with any typed array containing elements of any type.

+ +

Syntax

+ +
new TypedArray(length);
+new TypedArray(typedArray);
+new TypedArray(object);
+new TypedArray(buffer [, byteOffset [, length]]);
+
+where TypedArray() is one of:
+
+Int8Array();
+Uint8Array();
+Uint8ClampedArray();
+Int16Array();
+Uint16Array();
+Int32Array();
+Uint32Array();
+Float32Array();
+Float64Array();
+
+ +

Parameters

+ +
+
length
+
When called with a length argument, a typed array containing length zeroes is created.
+
typedArray
+
When called with a typedArray argument, which can be an object of any of the typed array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array.
+
object
+
When called with an object argument, a new typed array is created as if by the TypedArray.from() method.
+
buffer, byteOffset, length
+
When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified {{jsxref("ArrayBuffer")}}. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view.  If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed.
+
+ +

Description

+ +

ECMAScript 6 defines a TypedArray constructor that serves as the [[Prototype]] of all TypedArray constructors.  This constructor is not directly exposed: there is no global %TypedArray% or TypedArray property.  It is only directly accessible through Object.getPrototypeOf(Int8Array.prototype) and similar.  All TypedArrays constructors inherit common properties from the %TypedArray% constructor function.  Additionally, all typed array prototypes (TypedArray.prototype) have %TypedArray%.prototype as their [[Prototype]].

+ +

The %TypedArray% constructor on its own is not particularly useful.  Calling it or using it in a new expression will throw a TypeError, except when used during object creation in JS engines that support subclassing.  There are at present no such engines, so %TypedArray% is only useful to polyfill functions or properties onto all TypedArray constructors.

+ +

Property access

+ +

You can reference elements in the array using standard array index syntax (that is, using bracket notation). However, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, even when the indices are out of bound. Indexed properties will consult the {{jsxref("ArrayBuffer")}} and will never look at object properties. You can still use named properties, just like with all objects.

+ +
// Setting and getting using standard array syntax
+var int16 = new Int16Array(2);
+int16[0] = 42;
+console.log(int16[0]); // 42
+
+// Indexed properties on prototypes are not consulted (Fx 25)
+Int8Array.prototype[20] = "foo";
+(new Int8Array(32))[20]; // 0
+// even when out of bound
+Int8Array.prototype[20] = "foo";
+(new Int8Array(8))[20]; // undefined
+// or with negative integers
+Int8Array.prototype[-1] = "foo";
+(new Int8Array(8))[-1]; // undefined
+
+// Named properties are allowed, though (Fx 30)
+Int8Array.prototype.foo = "bar";
+(new Int8Array(32)).foo; // "bar"
+ +

TypedArray objects

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeSize in bytesDescriptionWeb IDL typeEquivalent C type
{{jsxref("Int8Array")}}18-bit two's complement signed integerbyteint8_t
{{jsxref("Uint8Array")}}18-bit unsigned integeroctetuint8_t
{{jsxref("Uint8ClampedArray")}}18-bit unsigned integer (clamped)octetuint8_t
{{jsxref("Int16Array")}}216-bit two's complement signed integershortint16_t
{{jsxref("Uint16Array")}}216-bit unsigned integerunsigned shortuint16_t
{{jsxref("Int32Array")}}432-bit two's complement signed integerlongint32_t
{{jsxref("Uint32Array")}}432-bit unsigned integerunsigned longuint32_t
{{jsxref("Float32Array")}}432-bit IEEE floating point numberunrestricted floatfloat
{{jsxref("Float64Array")}}864-bit IEEE floating point numberunrestricted doubledouble
+ +

Properties

+ +
+
{{jsxref("TypedArray.BYTES_PER_ELEMENT")}}
+
Returns a number value of the element size for the different typed array objects.
+
TypedArray.length
+
Length property whose value is 3.
+
{{jsxref("TypedArray.name")}}
+
Returns the string value of the constructor name. E.g "Int8Array".
+
{{jsxref("TypedArray.@@species", "get TypedArray[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("TypedArray.prototype")}}
+
Prototype for the TypedArray objects.
+
+ +

Methods

+ +
+
{{jsxref("TypedArray.from()")}}
+
Creates a new typed array from an array-like or iterable object. See also {{jsxref("Array.from()")}}.
+
{{jsxref("TypedArray.of()")}}
+
Creates a new typed array with a variable number of arguments. See also {{jsxref("Array.of()")}}.
+
+ +

TypedArray prototype

+ +

All TypedArrays inherit from {{jsxref("TypedArray.prototype")}}.

+ +

Properties

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','Properties')}}

+ +

Methods

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','Methods')}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}Defined as TypedArray and ArrayBufferView interface with typed array view types. Superseded by ECMAScript 6.
{{SpecName('ES6', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ES6')}}Initial definition in an ECMA standard. Specified behaviour for indexed and named properties. Specified that new is required.
{{SpecName('ESDraft', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(7.0)}}{{CompatGeckoDesktop("2")}}1011.65.1
Indexed properties not consulting prototype{{CompatVersionUnknown}} [1]{{CompatGeckoDesktop("25")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Named properties{{CompatVersionUnknown}}{{CompatGeckoDesktop("30")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
new is required{{CompatUnknown}}{{CompatGeckoDesktop("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support4.0{{CompatVersionUnknown}}{{ CompatGeckoMobile("2") }}1011.64.2{{CompatVersionUnknown}}
Indexed properties not consulting prototype{{CompatUnknown}}{{CompatVersionUnknown}} [1]{{ CompatGeckoMobile("25") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} [1]
Named properties{{CompatUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("30") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
new is required{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile("44") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] -1 and similar are not considered as indexed properties and therefore return the value of the prototype property.

+ +

Compatibility notes

+ +

Starting with ECMAScript 2015 (ES6), TypedArray constructors require to be constructed with a {{jsxref("Operators/new", "new")}} operator. Calling a TypedArray constructor as a function without new, will throw a {{jsxref("TypeError")}} from now on.

+ +
var dv = Int8Array([1, 2, 3]);
+// TypeError: calling a builtin Int8Array constructor
+// without new is forbidden
+ +
var dv = new Int8Array([1, 2, 3]);
+ +

See also

+ + diff --git a/files/id/web/javascript/reference/global_objects/typedarray/join/index.html b/files/id/web/javascript/reference/global_objects/typedarray/join/index.html new file mode 100644 index 0000000000..84f328ae1b --- /dev/null +++ b/files/id/web/javascript/reference/global_objects/typedarray/join/index.html @@ -0,0 +1,114 @@ +--- +title: TypedArray.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/join +tags: + - ECMAScript6 + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/join +--- +
{{JSRef}}
+ +

Method join() menggabungkan semua elemen dari array menjadi sebuah string. Alogaritma method ini memiliki kesamaan dengan {{jsxref("Array.prototype.join()")}}. TypedArray di sini merupakan salah datu typed array types.

+ +

Sintaks

+ +
typedarray.join([separator = ',']);
+ +

Parameter

+ +
+
separator
+
Opsional. Menentukan sebuah string untuk memisahkan setiap elemen. Separator perlu di konversi ke string jika dianggap penting. Jika dikosongkan, elemen array akan dipisahkan dengan tanda koma (",").
+
+ +

Contoh

+ +
var uint8 = new Uint8Array([1,2,3]);
+uint8.join();      // '1,2,3'
+uint8.join(' / '); // '1 / 2 / 3'
+uint8.join('');    // '123'
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-%typedarray%.prototype.join', 'TypedArray.prototype.join')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype.join', 'TypedArray.prototype.join')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop("37")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("37")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/index.html b/files/id/web/javascript/reference/index.html new file mode 100644 index 0000000000..261b76a5b5 --- /dev/null +++ b/files/id/web/javascript/reference/index.html @@ -0,0 +1,48 @@ +--- +title: Referensi JavaScript +slug: Web/JavaScript/Reference +tags: + - JavaScript +translation_of: Web/JavaScript/Reference +--- +
{{JsSidebar}}
+ +

Laman ini merupakan bagian dari sesi JavaScript pada MDN yang berfungsi sebagai acuan mengenai bahasa pemrograman JavaScript. Pelajari lebih lanjut perihal acuan ini.

+ +

Objek Global

+ +

Bagian ini mendokumentasikan semua object standar built-in JavaScript, beserta method dan propertinya.

+ +
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects', 'Standard_objects_by_category')}}
+ +

Pernyataan

+ +

Bagian ini mendekumentasikan semua pernyataan dan deklarasi  JavaScript.

+ +
{{page('/id/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
+ +

Ungkapan dan operator

+ +

Bagian ini mendokumentasikan semua ungkapan dan operator JavaScript .

+ +
{{page('/id/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
+ +

Fungsi

+ +

Bagian ini mendokumentasikan tentang Fungsi JavaScrip dan penggunaanya untuk pengembangan aplikasi anda.

+ + + +

Acuan tambahan

+ + diff --git a/files/id/web/javascript/reference/lexical_grammar/index.html b/files/id/web/javascript/reference/lexical_grammar/index.html new file mode 100644 index 0000000000..83e5696ccd --- /dev/null +++ b/files/id/web/javascript/reference/lexical_grammar/index.html @@ -0,0 +1,670 @@ +--- +title: Lexical grammar +slug: Web/JavaScript/Reference/Lexical_grammar +translation_of: Web/JavaScript/Reference/Lexical_grammar +--- +
{{JsSidebar("More")}}
+ +

Halaman ini menjelaskan tata bahasa leksikal JavaScript. Teks sumber skrip JavaScript dipindai dari kiri ke kanan dan diubah menjadi urutan elemen masukan yang merupakan token, karakter kontrol, terminator baris, komentar atau whitespace. ECMAScript juga mendefinisikan kata kunci dan literal tertentu dan memiliki aturan untuk penyisipan titik koma secara otomatis untuk mengakhiri pernyataan.

+ +

Karakter-karakter kontrol

+ +

Karakter kontrol tidak memiliki representasi visual namun digunakan untuk mengendalikan interpretasi teks.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Karakter-karakter kontrol format unicode
KodeNamaSingkatanDeskripsi
U+200CZero width non-joiner<ZWNJ>Ditempatkan di antara karakter untuk mencegah terhubung ke ligatur dalam bahasa tertentu (Wikipedia).
U+200DZero width joiner<ZWJ>Ditempatkan di antara karakter yang biasanya tidak terhubung agar karakter dapat dirender menggunakan bentuknya yang terhubung dalam bahasa tertentu. (Wikipedia).
U+FEFFByte order mark<BOM>Digunakan pada awal skrip untuk menandainya sebagai Unicode dan urutan byte teks (Wikipedia).
+ +

White space

+ +

Karakter whitespace meningkatkan keterbacaan teks sumber dan memisahkan token-token. Karakter ini biasanya tidak diperlukan untuk fungsionalitas kode. Alat minifikasi sering digunakan untuk membuang whitespace agar mengurangi jumlah data yang perlu ditransfer.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Karakter-karakter whitespace
KodeNamaSingkatanDeskripsi +

Rangkaian pelolosan/Escape

+
U+0009Tabulasi karakter<HT>Tabulasi horisontal\t
U+000BTabulasi baris<VT>Tabulasi vertikal\v
U+000CForm feed<FF>Karakter kontrol pemecah halaman (Wikipedia).\f
U+0020Space<SP>Spasi normal 
U+00A0No-break space<NBSP>Spasi normal, tetapi tidak ada petunjuk dimana baris terputus. 
OthersOther Unicode space characters<USP>Spasi di Unicode on Wikipedia 
+ +

Terminator baris

+ +

Selain karakter whitespace, karakter terminator baris digunakan untuk meningkatkan keterbacaan teks sumber. Namun, dalam beberapa kasus, terminator baris dapat mempengaruhi eksekusi kode JavaScript karena ada beberapa tempat di mana mereka dilarang. Terminator baris juga mempengaruhi proses penyisipan titik koma otomatis. Terminator baris dicocokkan dengan kelas \s dalam regular expressions.

+ +

Hanya kode Unicode berikut yang diperlakukan sebagai terminator baris di ECMAScript, karakter pemecah baris lainnya diperlakukan sebagai whitespace (misalnya, Next Line, NEL, U+0085 dianggap sebagai whitespace).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Karakter-karakter terminator baris
KodeNamaSingkatanDeskripsiRangkaian pelolosan/escape 
U+000ALine Feed<LF>Karakter baris baru di sistem UNIX.\n
U+000DCarriage Return<CR>Karakter baris baru di Commodore dan sistem Mac awal.\r
U+2028Line Separator<LS>Wikipedia 
U+2029Paragraph Separator<PS>Wikipedia 
+ +

Komentar

+ +

Komentar digunakan untuk menambahkan petunjuk, catatan, saran, atau peringatan ke kode JavaScript. Hal ini dapat mempermudah membaca dan memahami. Mereka juga dapat digunakan untuk menonaktifkan kode agar tidak dieksekusi; Ini juga dapat menjadi alat debugging yang berharga.

+ +

JavaScript memiliki dua cara untuk memberi komentar pada kodenya.

+ +

Cara pertama adalah komentar //; Ini membuat semua teks yang mengikutinya pada baris yang sama menjadi sebuah komentar. Sebagai contoh:

+ +
function komentar() {
+  // Ini adalah komentar JavaScript satu baris
+  console.log('Hello world!');
+}
+komentar();
+
+ +

Cara kedua adalah komentar gaya  /* */ , yang jauh lebih fleksibel.

+ +

Misalnya, Anda bisa menggunakannya dalam satu baris:

+ +
function komentar() {
+  /* Ini adalah komentar JavaScript satu baris */
+  console.log('Hello world!');
+}
+komentar();
+ +

Anda juga bisa membuat komentar beberapa baris, seperti ini:

+ +
function komentar() {
+  /* Komentar ini merentang dalam beberapa baris. Perhatikan
+     bahwa kita tidak perlu mengakhir komentar sebelum selesai. */
+  console.log('Hello world!');
+}
+komentar();
+ +

Anda juga bisa menggunakannya di tengah baris, jika Anda mau, meskipun ini bisa membuat kode Anda lebih sulit dibaca sehingga harus digunakan dengan hati-hati:

+ +
function komentar(x) {
+  console.log('Hello ' + x /* menysipkan nilai dari x */ + ' !');
+}
+comment('world');
+ +

Selain itu, Anda bisa menggunakannya untuk menonaktifkan kode agar tidak berjalan, dengan membungkus kode dalam komentar, seperti ini:

+ +
function comment() {
+  /* console.log('Hello world!'); */
+}
+comment();
+ +

Dalam hal ini, pemaggilan console.log() tidak pernah dikeluarkan, karena itu ada di dalam komentar. Sejumlah baris kode dapat dinonaktifkan dengan cara ini.

+ +

Kata kunci

+ +

Reserved keywords as of ECMAScript 2015

+ + + +

Kata kunci akan datang yang dicadangkan

+ +

Berikut ini disediakan sebagai kata kunci akan datang menurut spesifikasi ECMAScript. Mereka tidak memiliki fungsi khusus saat ini, namun mungkin pada beberapa waktu mendatang, sehingga tidak dapat digunakan sebagai pengidentifikasi.

+ +

Selalu dicadangkan:

+ + + +

Berikut ini hanya dicadangkan saat ditemukan dalam kode mode strict "ketat":

+ + + +

Berikut ini hanya dicadangkan saat ditemukan dalam kode modul:

+ + + +

Kata kunci standart lama yang masih dingunakan hingga sekarang

+ +

Berikut adalah dicadankan sebagai kata kunci akan datang pada spesifikasi ECMAScript usang (ECMAScript 1 s/d 3).

+ + + +

Selain itu literal-literal null, true, dan false tidak dapat digunakan sebagai pengidentifikasi didalam ECMAScript.

+ +

Penggunaan kata dicadangkan

+ +

Kata yang dicadangkan sebenarnya hanya berlaku untuk pengidentifikasi (vs. IdentifierNames ). Seperti yang dijelaskan di es5.github.com/#A.1, ini semua adalah IdentifierNames yang tidak mengecualikan ReservedWords .

+ +
a.import
+a['import']
+a = { import: 'test' }.
+
+ +

Di sisi lain, hal-hal berikut ini ilegal karena ini adalah pengidentifikasi, yaitu IdentifierName tanpa kata-kata yang dicadangkan. Pengidentifikasi digunakan untuk FunctionDeclaration dan FunctionExpression.

+ +
function import() {} // Illegal.
+ +

Literal

+ +

Literal null

+ +

Lihat juga null untuk informasi lebih lanjut.

+ +
null
+ +

Literal Boolean

+ +

Lihat juga Boolean untuk informasi lebih lanjut.

+ +
true
+false
+ +

Literal numerik

+ +

Decimal

+ +
1234567890
+42
+
+// Waspada saat mengunakan nol dimuka:
+0888 // 888 diuraikan sebagai desimal
+0777 // diuraikan sebagai oktal, 511 dalam desimal
+
+ +

Perhatikan bahwa literal desimal dapat dimulai dengan angka nol ( 0 ) diikuti oleh digit desimal lainnya, namun jika semua digit setelah angka 0 teratas lebih kecil dari 8, angka tersebut diartikan sebagai angka oktal. Ini tidak akan melempar JavaScript, lihat {{bug(957513)}}. Lihat juga halaman tentang parseInt().

+ +

Biner

+ +

Sintaksis bilangan biner menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "B" ( 0b atau 0B ). Karena sintaksis ini baru di ECMAScript 2015, lihat tabel kompatibilitas browser, di bawah ini. Jika digit setelah 0b tidak 0 atau 1, SyntaxError berikut dilempar: "Missing binary digits after 0b".

+ +
var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
+var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
+var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
+ +

Oktal

+ +

Sintaksis bilangan oktal menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "O" ( 0o atau 0O). Karena sintaks ini baru di ECMAScript 2015, lihat tabel kompatibilitas browser, di bawah ini. Jika digit setelah 0o berada di luar kisaran (01234567), SyntaxError berikut dilempar: "Missing octal digits after 0o".

+ +
var n = 0O755; // 493
+var m = 0o644; // 420
+
+// Juga dimungkinkan hanya menggunakan nol dimuka (lihat tentang desimal diatas)
+0755
+0644
+
+ +

Heksadesimal

+ +

Sintaksis bilangan heksadesimal menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "X" ( 0x atau 0X). Jika digit setelah 0x berada di luar rentang (0123456789ABCDEF), SyntaxError berikut dilempar: "Identifier starts immediately after numeric literal".

+ +
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
+0x123456789ABCDEF   // 81985529216486900
+0XA                 // 10
+
+ +

Literal objek

+ +

Lihat juga Objek and Penginisialisasi objek untuk informasi lebih lanjut.

+ +
var o = { a: 'foo', b: 'bar', c: 42 };
+
+// notasi singkat. baru di ES2015
+var a = 'foo', b = 'bar', c = 42;
+var o = {a, b, c};
+
+// bukannya
+var o = { a: a, b: b, c: c };
+
+ +

Literal array

+ +

Lihat juga Array untuk informasi lebih lanjut.

+ +
[1954, 1974, 1990, 2014]
+ +

Literal string

+ +
'foo'
+"bar"
+ +

Rangkaian pelolosan/escape heksadesimal

+ +
'\xA9' // "©"
+
+ +

Rangkaian pelolosan/escape Unicode

+ +

Rangkaian pelolosan Unicode memerlukan setidaknya empat karakter diawali \u.

+ +
'\u00A9' // "©"
+ +

Penerapan point kode Unicode

+ +

Baru di ECMAScript 2015. Dengan pelolosan kode Unicode, tiap karakter dapat diloloskan menggunakan bilangan hexadesimal jadi dimungkinkan untuk menggunkan kode Unicode sampai 0x10FFFF. Dengan pelolosan Unicode sederhana terkadang lebih dibutuhkan untuk menulis bagian pengganti secara terpisah untuk mencapai tujuan yang sama.

+ +

Lihat juga String.fromCodePoint() atau String.prototype.codePointAt().

+ +
'\u{2F804}'
+
+// ekuivalen dengan pelolosan Unicode sederhana
+'\uD87E\uDC04'
+ +

Literal regular expression

+ +

Lihat juga RegExp untuk informasi lebih lanjut.

+ +
/ab+c/g
+
+// Suatu literal "kosong" regular expression
+// diperlukan grup bukan penangkap
+// untuk menghindarkan ambiguitas denga komentar satu baris
+/(?:)/
+ +

Literal template

+ +

Lihat juga template strings untuk informasi lebih lanjut.

+ +
`string text`
+
+`string text baris 1
+ string text baris 2`
+
+`string text ${expression} string text`
+
+tag `string text ${expression} string text`
+ +

Penyisipan titik koma otomatis

+ +

Beberapa pernyataan JavaScript harus diakhiri dengan titik koma an oleh karena itu dipengaruhi oleh penyisipan otomatis semicolon (ASI):

+ + + +

Spesifikasi ECMAScript menyebutkan tiga aturan penyisipan titik koma.

+ +

1.  Titik koma disisipkan sebelumnya, bila terminator baris or "}" diteramukan yang tidak diizinkan oleh tata bahasa.

+ +
{ 1 2 } 3
+
+// di transformasikan ke ASI kedalam
+
+{ 1 2 ;} 3;
+ +

2.  Titik koma disisipkan di bagian akhir, saat akhir aliran input token terdeteksi dan parser tidak dapat mengurai aliran input tunggal aliran sebagai program yang lengkap.

+ +

Disini ++ tidak diperlakukan sebagai operator postfix yang menerapkan variabel b, karena terminator baris terjadi antara b dan ++.

+ +
a = b
+++c
+
+// di transformasikan ke ASI kedalam
+
+a = b;
+++c;
+
+ +

3. Titik koma disisipkan pada akhirnya, ketika sebuah pernyataan dengan produksi terbatas dalam tata bahasa diikuti oleh terminator baris. Pernyataan-pernyataan ini dengan aturan "tidak diperlukan terminator baris" adalah:

+ + + +
return
+a + b
+
+// di transformasikan ke ASI kedalam
+
+return;
+a + b;
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2("ES1")}}Definisi awal.
{{SpecName('ES5.1', '#sec-7', 'Lexical Conventions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}{{Spec2('ES6')}} +

Ditambahkan: Literal Bilangan Biner dan Octal, pelolosan kode Unicode, Templates

+
{{SpecName('ESDraft', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Literal numerik biner dan oktal (0b dan 0o){{CompatChrome(41)}}12{{CompatGeckoDesktop(25)}}{{CompatUnknown}}{{CompatOpera(28)}}{{CompatSafari(9)}}
Pelolosan kode Unicode (\u{}){{CompatChrome(44)}}12{{CompatGeckoDesktop(40)}}{{CompatNo}}{{CompatOpera(31)}}{{CompatSafari(9)}}
Notasi singkat untuk literal objek{{CompatChrome(43)}}12{{CompatGeckoDesktop(33)}}{{CompatNo}}{{CompatChrome(30)}}{{CompatSafari(9)}}
Literal template{{CompatChrome(41)}}12{{CompatGeckoDesktop(34)}}{{CompatNo}}{{CompatOpera(28)}}{{CompatSafari(9)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Literal numerik biner dan oktal (0b dan 0o){{CompatUnknown}}41{{CompatGeckomobile(33)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Pelolosan kode Unicode (\u{}){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckomobile(40)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Notasi singkat untuk literal objek{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(33)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Literal template{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(34)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Firefox-specific notes

+ + + +

See also

+ + diff --git a/files/id/web/javascript/reference/operators/conditional_operator/index.html b/files/id/web/javascript/reference/operators/conditional_operator/index.html new file mode 100644 index 0000000000..1a64158acb --- /dev/null +++ b/files/id/web/javascript/reference/operators/conditional_operator/index.html @@ -0,0 +1,167 @@ +--- +title: Operasional Kondisi (ternary) +slug: Web/JavaScript/Reference/Operators/Conditional_Operator +translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator +--- +
{{jsSidebar("Operators")}}
+ +

Operasianal kondisional (ternary) adalah satu-satunya operator yang hanya membutuhkan tiga operator. Operator ini sering digunakan sebagai jalan pintas untuk `if` statement.

+ +

Syntax

+ +
condition ? expr1 : expr2 
+ +

Parameters

+ +
+
condition (atau conditions)
+
Sebuah ekspresi akan menguji apakah menghasilkan true atau false.
+
+ +
+
expr1, expr2
+
Ekspresi yang akan dilakukan setelah kondisi terpenuhi.
+
+ +

Description

+ +

Jika condition menghasilkan true, maka operator ini akan menghasilkan/mengembalikan nilai dari expr1; dan jika sebaliknya, ini akan menghasilkan/mengembalikan nilai dari expr2. Sebagai contoh, untuk menampilkan pesan yang berbeda berdasarkan nilai dari variabel isMember, anda bisa menggunakan contoh kode berikut:

+ +
var isMember = true;
+'The fee is ' + (isMember ? '$2.00' : '$10.00'); //$2.00
+
+ +

Anda juga dapat mendefinisikan sebuah variabel secara langsung:

+ +
var elvisLives = Math.PI > 4 ? 'Yep' : 'Nope';
+ +

Anda juga bisa menggunakan operator ternary secara jamak (catatan: conditional operator adalah associative yang lebih baik):

+ +
var firstCheck = false, secondCheck = false, access = firstCheck ? 'Access denied' : secondCheck ? 'Access denied' : 'Access granted';
+console.log(access); // logs "Access granted"
+ +

Anda juga dapat menggunakan pengondisian jamak seperti pengondisian jamak pada statement IF pada umumnya:

+ +
var condition1 = true,
+    condition2 = false,
+    access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false");
+
+console.log(access); // logs "true false"
+
+ +

 

+ +

Note: The parentheses are not required, and do not affect the functionality. They are there to help visualize how the outcome is processed.

+ +

You can also use ternary evaluations in free space in order to do different operations:

+ +
var stop = false, age = 16;
+
+age > 18 ? location.assign('continue.html') : stop = true;
+
+ +

You can also do more than one single operation per case, separating them with a comma, and enclosing them in parenthesis:

+ +
var stop = false, age = 23;
+
+age > 18 ? (
+    alert('OK, you can go.'),
+    location.assign('continue.html')
+) : (
+    stop = true,
+    alert('Sorry, you are much too young!')
+);
+
+ +

You can also do more than one operation during the assignation of a value. In this case, the last comma-separated value of the parenthesis will be the value to be assigned.

+ +
var age = 16;
+
+var url = age > 18 ? (
+    alert('OK, you can go.'),
+    // alert returns "undefined", but it will be ignored because
+    // isn't the last comma-separated value of the parenthesis
+    'continue.html' // the value to be assigned if age > 18
+) : (
+    alert('You are much too young!'),
+    alert('Sorry :-('),
+    // etc. etc.
+    'stop.html' // the value to be assigned if !(age > 18)
+);
+
+location.assign(url); // "stop.html"
+ +

Returning Ternary Statements

+ +

The ternary operator lends itself well to function returns that would otherwise require an if/else statement.

+ +
var func1 = function( .. ) {
+  if (condition1) { return value1 }
+  else { return value2 }
+}
+
+var func2 = function( .. ) {
+  return condition1 ? value1 : value2
+}
+ +

A good way to spot that the ternary will be a suitable replacement for an if/else statement is when the return keyword is used multiple times and is the only expression inside of the if block.

+ +

By breaking the ternary onto multiple lines and making use of extra whitespace, the ternary operator can be used to very cleanly replace a lengthy series of if/else statements. This provides a syntactically light way of expressing the same logic:

+ +
var func1 = function( .. ) {
+  if (condition1) { return value1 }
+  else if (condition2) { return value2 }
+  else if (condition3) { return value3 }
+  else { return value4 }
+}
+
+var func2 = function( .. ) {
+  return condition1 ? value1
+       : condition2 ? value2
+       : condition3 ? value3
+       :              value4
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.conditional")}}

+ +

See also

+ + diff --git a/files/id/web/javascript/reference/operators/fungsi/index.html b/files/id/web/javascript/reference/operators/fungsi/index.html new file mode 100644 index 0000000000..5366891a5c --- /dev/null +++ b/files/id/web/javascript/reference/operators/fungsi/index.html @@ -0,0 +1,153 @@ +--- +title: ungkapan fungsi +slug: Web/JavaScript/Reference/Operators/fungsi +tags: + - Fungsi + - JavaScript + - Operator + - Ungkapan Utama +translation_of: Web/JavaScript/Reference/Operators/function +--- +
{{jsSidebar("Operators")}}
+ +
Kata kunci fungsi digunakan untuk mendefinisikan fungsi dalam sebuah ungkapan.
+ +
 
+ +

Sintaksis

+ +
function [nama]([param1[, param2[, ..., paramN]]]) {
+   pernyataan
+}
+ +

Parameters

+ +
+
nama
+
Bisa dihilangkan apabila fungsi merupaka fungsi anonim. Nama fungsi bersifat lokal, relatif terhadap tubuh fungsi.
+
paramN
+
Nama argumen yang akan diumpankan kepada fungsi.
+
pernyataan
+
Pernyataan yang menyusun tubuh fungsi.
+
+ +

Deskripsi

+ +

Sintaksis ungkapan fungsi nyaris sama apabila dibandingkan dengan sintaksis pernyataan fungsi(lihat pernyataan fungsi untuk lebih jelasnya). Perbedaan utama antara ungkapan fungsi dengan pernyataan fungsi ialah; ungkapan fungsi memperbolehkan nama fungsi untuk tidak digunakan/dihilangkan apabila ungkapan fungsi tersebut merupakan fungsi anonim. Ungkapan fungsi dapat digunakan sebagai IIFE (immediately Invoked Function Expression), sebuah fungsi yang otomatis dijalankan apabila didefinisikan. Untuk informasi lebih lanjut, lihat juga bab tentang fungsi.

+ +

Contoh

+ +

Dibawah ini merupakan contoh definisi sebuah fungsi tanpa nama yang kemudian ditugaskan kedalam variabel x:

+ +
var x = function(y) {
+   return y * y;
+};
+
+ +

Ungkapan fungsi bernama (Named function expression)

+ +

Apabila sebuah fungsi hendak dipanggil dari dalam tubuh fungsi itu sendiri, pergunakanlah ungkapan fungsi bernama. Nama fungsi bersifat lokal relatif terhadap tubuh fungsi. Manfaat penggunaan ungkapan fungsi bernama ialah menghindarkan penggunaan properti non-standar arguments.callee.

+ +
var math = {
+  'factorial': function factorial(n) {
+    if (n <= 1)
+      return 1;
+    return n * factorial(n - 1);
+  }
+};
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}}Definisi awal. Diterapkan pada JavaScript 1.5.
+ +

Kesesuaian Perambah (Browser)

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Mendasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Mendasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/operators/index.html b/files/id/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..ef3afeb763 --- /dev/null +++ b/files/id/web/javascript/reference/operators/index.html @@ -0,0 +1,269 @@ +--- +title: Expressions and operators +slug: Web/JavaScript/Reference/Operators +tags: + - JavaScript + - NeedsTranslation + - Operators + - TopicStub +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

This chapter documents all the JavaScript language operators, expressions and keywords.

+ +

Ekspresi and operator sesuai kategori

+ +

Untuk daftar isi sesuai Alfabet, silahkan lihat sisi sebelah kiri artikel ini.

+ +

Primary expressions

+ +

Basic keywords and general expressions in JavaScript.

+ +

Keyword-keyword dasar dan ekspersi-ekspresi umum di javascript

+ +
+
{{jsxref("Operators/this", "this")}}
+
The this keyword refers to the function's execution context.
+
{{jsxref("Operators/function", "function")}}
+
The function keyword defines a function expression.
+
{{jsxref("Global_Objects/Array", "[]")}}
+
Array literal syntax.
+
{{jsxref("Global_Objects/Object", "{}")}}
+
Object literal syntax.
+
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{experimental_inline()}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
+
Array comprehensions.
+
{{experimental_inline()}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator comprehensions.
+
{{jsxref("Operators/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Left-hand-side expressions

+ +

Left values are the destination of an assignment.

+ +
+
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
+
Member operators provide access to a property or method of an object
+ (object.property and object["property"]).
+
{{jsxref("Operators/new", "new")}}
+
The new operator creates an instance of a constructor.
+
{{experimental_inline()}} {{jsxref("Operators/super", "super")}}
+
The super keyword calls the parent constructor.
+
{{experimental_inline()}} {{jsxref("Operators/Spread_operator", "...obj")}}
+
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
+
+ +

Increment and decrement

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
+
Postfix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
+
Postfix decrement operator.
+
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
+
Prefix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
+
Prefix decrement operator.
+
+ +

Unary operators

+ +

A unary operation is operation with only one operand.

+ +
+
{{jsxref("Operators/delete", "delete")}}
+
The delete operator deletes a property from an object.
+
{{jsxref("Operators/void", "void")}}
+
The void operator discards an expression's return value.
+
{{jsxref("Operators/typeof", "typeof")}}
+
The typeof operator determines the type of a given object.
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
+
The unary plus operator converts its operand to Number type.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
+
The unary negation operator converts its operand to Number type and then negates it.
+
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
+
Bitwise NOT operator.
+
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
+
Logical NOT operator.
+
+ +

Arithmetic operators

+ +

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
+
Addition operator.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
+
Subtraction operator.
+
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
+
Division operator.
+
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
+
Multiplication operator.
+
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
+
Remainder operator.
+
+ +

Relational operators

+ +

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

+ +
+
{{jsxref("Operators/in", "in")}}
+
The in operator determines whether an object has a given property.
+
{{jsxref("Operators/instanceof", "instanceof")}}
+
The instanceof operator determines whether an object is an instance of another object.
+
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
+
Less than operator.
+
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
+
Greater than operator.
+
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
+
Less than or equal operator.
+
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
+
Greater than or equal operator.
+
+ +

Equality operators

+ +

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

+ +
+
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
+
Equality operator.
+
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
+
Inequality operator.
+
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
+
Identity operator.
+
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
+
Nonidentity operator.
+
+ +

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
+
Bitwise left shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
+
Bitwise right shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
+
Bitwise unsigned right shift operator.
+
+ +

Binary bitwise operators

+ +

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
+
Bitwise AND.
+
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
+
Bitwise OR.
+
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
+
Bitwise XOR.
+
+ +

Binary logical operators

+ +

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

+ +
+
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
+
Logical AND.
+
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
+
Logical OR.
+
+ +

Conditional (ternary) operator

+ +
+
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
+
+

The conditional operator returns one of two values based on the logical value of the condition.

+
+
+ +

Assignment operators

+ +

An assignment operator assigns a value to its left operand based on the value of its right operand.

+ +
+
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
+
Assignment operator.
+
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
+
Multiplication assignment.
+
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
+
Division assignment.
+
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
+
Remainder assignment.
+
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
+
Addition assignment.
+
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
+
Subtraction assignment
+
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
+
Left shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
+
Right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
+
Unsigned right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
+
Bitwise AND assignment.
+
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
+
Bitwise XOR assignment.
+
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
+
Bitwise OR assignment.
+
{{experimental_inline()}} {{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{experimental_inline()}} {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

+
+
+ +

Comma operator

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
+

The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.

+
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword, Array comprehensions, Generator comprehensions
+ +

See also

+ + diff --git a/files/id/web/javascript/reference/operators/yield/index.html b/files/id/web/javascript/reference/operators/yield/index.html new file mode 100644 index 0000000000..366f2aaa38 --- /dev/null +++ b/files/id/web/javascript/reference/operators/yield/index.html @@ -0,0 +1,109 @@ +--- +title: yield +slug: Web/JavaScript/Reference/Operators/yield +translation_of: Web/JavaScript/Reference/Operators/yield +--- +
{{jsSidebar("Operators")}}
+ +

Keyword yield digunakan untuk menghentikan sementara dan melanjutkan sebuah fungsi generator ({{jsxref("Statements/function*", "function*")}} atau legacy generator function).

+ +

Sintak

+ +
[rv] = yield [expression];
+ +
+
expression
+
Mendefeniskan nilai yang akan dikembalikan melalui iterator protocol. Apabila diabaikan, maka undefined akan dikembalikan.
+
rv
+
+

Mengembalikan nilai opsional yang diberikan pada generator method next() untuk melanjutkan eksekusinya.

+
+
+ +

Deskripsi

+ +

Keyword yield menghentikan secara sementara eksekusi dari fungsi generator dan nilai setelah keyword yield dikembalikan pada pemanggil generator tersebut. yield bisa juga disebut sebagai versi generator dari keywordreturn.

+ +

Keyword yield sebenarnya mengembalikan sebuah obyek IteratorResult dengan dua properti, value dan done. Propertivalue adalah hasi dari evaluasi ekspresi yield, dan done yang false, mengindikasikan bahwa fungsi generator tersebut belum selesai sepenuhnya.

+ +

Sekali berhenti pada ekspresi yield , eksekusi dari code generator tersebut akan terus dihentikan sampai generator method next() dipanggil. Setiap kali method generator next() dipanggil, generator melanjutkan eksekusi dan berjalan hingga mencapai salah satu dari kondisi berikut ini :

+ + + +

JIka sebuah nilai opsional diberikan pada generator method next(), nilai tersebut menjadi nilai yang dikembalikan oleh operasi yield dari generator pada saat itu.

+ +

Di antara kode generator, operatoryield -nya, dan kemampuan untuk menentukan sebua nilai awal baru dengan memberikannya pada {{jsxref("Generator.prototype.next()")}}, generator menawarkan power dan kontrol yang luar biasa.

+ +

Contoh

+ +

Kode berikut merupakan deklarasi dari sebuah contoh fungsi generator.

+ +
function* countAppleSales () {
+  var saleList = [3, 7, 5];
+  for (var i = 0; i < saleList.length; i++) {
+    yield saleList[i];
+  }
+}
+ +

Setelah sebuah fungsi generator didefenisikan, maka fungsi tersebut dapat digunakan untuk menghasilkan sebuah iterator seperti berikut.

+ +
var appleStore = countAppleSales(); // Generator { }
+console.log(appleStore.next()); // { value: 3, done: false }
+console.log(appleStore.next()); // { value: 7, done: false }
+console.log(appleStore.next()); // { value: 5, done: false }
+console.log(appleStore.next()); // { value: undefined, done: true }
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('ES2015', '#', 'Yield')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'Yield')}}{{Spec2('ESDraft')}}
+ +

Kompatabilitas Browser

+ + + +

{{Compat("javascript.operators.yield")}}

+ +

Catatan Firefox-specific

+ + + +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/statements/class/index.html b/files/id/web/javascript/reference/statements/class/index.html new file mode 100644 index 0000000000..6ca35e9c71 --- /dev/null +++ b/files/id/web/javascript/reference/statements/class/index.html @@ -0,0 +1,171 @@ +--- +title: class +slug: Web/JavaScript/Reference/Statements/class +tags: + - Classes + - Declaration + - ECMAScript6 + - Referensi +translation_of: Web/JavaScript/Reference/Statements/class +--- +
{{jsSidebar("Statements")}}
+ +

Deklarasi class digunakan untuk membuat class baru dengan nama menggunakan turunan berbasis prototype.

+ +
+

Anda juga bisa mendefinisikan kelas menggunakan{{jsxref("Operators/class", "class expression", "", 1)}}.

+
+ +

Sintaks

+ +
class name [extends] {
+  // class body
+}
+
+ +

Deskripsi

+ +

Seperti halnya dengan ekspresi class,  pembentuk (body) class dari deklarasi class di jalankan pada strict mode.

+ +

Deklarasi class bukanlah {{Glossary("Hoisting", "hoisted")}} (Tidak seperti function declarations).

+ +

Contoh

+ +

Dasar deklarasi class

+ +

Pada contoh, hal pertama yang kita lakukan adalah mendefinisikan class dengan nama Polygon, kemudian membentangkannya ( extend ) untuk membuat class bernama Square. Perlu diperhatikan bahwa super(), digunakan pada constructor, hanya dapat digunakan di konstruktor dan harus dipanggil setelah keyword 'this' dapat digunakan.

+ +
class Polygon {
+  constructor(height, width) {
+    this.name = 'Polygon';
+    this.height = height;
+    this.width = width;
+  }
+}
+
+class Square extends Polygon {
+  constructor(length) {
+    super(length, length);
+    this.name = 'Square';
+  }
+}
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
+ +

Kompabilitas Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Array subclassing{{CompatChrome(43.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Allowed in sloppy mode{{CompatChrome(49.0)}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FiturAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
Array subclassing{{CompatNo}}{{CompatChrome(43.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
Allowed in sloppy mode{{CompatNo}}{{CompatChrome(49.0)}}    {{CompatChrome(49.0)}}
+
+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/statements/do...while/index.html b/files/id/web/javascript/reference/statements/do...while/index.html new file mode 100644 index 0000000000..01c518ad84 --- /dev/null +++ b/files/id/web/javascript/reference/statements/do...while/index.html @@ -0,0 +1,101 @@ +--- +title: do...while +slug: Web/JavaScript/Reference/Statements/do...while +tags: + - JavaScript + - Referensi +translation_of: Web/JavaScript/Reference/Statements/do...while +--- +
{{jsSidebar("Statements")}}
+ +

Pernyataan do...while digunakan untuk membuat perulangan yang mengeksekusi penyataan tertentu hingga kondisi pemeriksaan penyataan tersebut bernilai false. Kondisi akan diperiksa setelah pernyataan dieksekusi/dijalankan dengan hasil penyataan tersebut yang dijalankan sekurangnya sekali.

+ +
{{EmbedInteractiveExample("pages/js/statement-dowhile.html")}}
+ + + +

Sintaks

+ +
do
+   penyataan
+while (kondisi);
+
+ +
+
penyataan
+
Sebuah penyataan yang dieksekusi setidaknya sekali dan akan kembali dieksekusi setiap kali kondisi pemeriksaan bernial true. Untuk mengeksekusi lebih dari satu penyataan di dalam perulangan, gunakan pernyataan {{jsxref("Statements/block", "block")}}  ({ ... }) untuk mengelompokkan penyataan.
+
+ +
+
kondisi
+
Sebuah ekspresi yang periksa setelah perulangan. Bila kondisi periksa bernilai true, maka pernyataan akan kembali dieksekusi. Bila kondisi periksa bernilai false, maka kendali akan melewati do...while dan meneruskan ke pernyataan selanjutnya.
+
+ +

Contoh

+ +

Penggunaan do...while

+ +

Pada contoh berikut, perulangan do...while diiterasikan setidaknya sekali dan kembali di iterasikan sampai nilai i tidak kurang dari 5.

+ +

Kode HTML

+ +
<div id="example"></div>
+ +

Kode JavaScript

+ +
var result = '';
+var i = 0;
+do {
+   i += 1;
+   result += i + ' ';
+} while (i < 5);
+document.getElementById('example').innerHTML = result;
+ +

Hasil

+ +

{{ EmbedLiveSample('Examples') }}

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.6.1', 'do-while statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ES6')}}Trailing ; is now optional.
{{SpecName('ESDraft', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas Peramban

+ + + +

{{Compat("javascript.statements.do_while")}}

+ +

Lihat pula

+ + diff --git a/files/id/web/javascript/reference/statements/empty/index.html b/files/id/web/javascript/reference/statements/empty/index.html new file mode 100644 index 0000000000..26b2bf8d20 --- /dev/null +++ b/files/id/web/javascript/reference/statements/empty/index.html @@ -0,0 +1,147 @@ +--- +title: empty +slug: Web/JavaScript/Reference/Statements/Empty +tags: + - JavaScript + - Statement +translation_of: Web/JavaScript/Reference/Statements/Empty +--- +
{{jsSidebar("Statements")}}
+ +

Pernyataan empty digunakan untuk menyediakan statement kosong, walaupun begitu sintaks JavaScript tetap menghitungnya sebagai sebuah Pernyataan.

+ +

Sintak

+ +
;
+
+ +

Deskripsi

+ +

Statemen atau penyataan kosong hanya berupa semicolon (;) menunjukkan bahawa tidak ada statement untuk dijalankan, meskipun jika sintak JavaScript membutuhkan salah satunya. Sifat kebalikan, dimana anda ingin menggunakan lebih dari satu statemen, namun javascript hanya memperbolehkan sebuah statemen kosong, anda bisa menggunakan block statement; yang merupakan gabungan dari beberapa statement menjadi satu.

+ +

Contoh

+ +

Statement kosong terkadang digunakan pada perulangan. Lihat pada contoh dengan body berisi sebuah statement kosong:

+ +
var arr = [1, 2, 3];
+
+// Assign all array values to 0
+for (i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ;
+
+console.log(arr)
+// [0, 0, 0]
+
+ +

Catatan: Ini merupakan ide yang bagus dengan menggunakan komentar pada penggunaan statement kosong, karena ini tidak benar - benar jelas seperti halnya penggunaan semicolon (;) pada umumnya. Contoh berikut bisa dikatakan merupakan penggunaan yang tidak disengaja:

+ +
if (condition);       // Perhatian, "if" tidak menjalankan apapun!
+   killTheUniverse()  // Jadi ini akan selalu di jalankan!!!
+
+ +

Contoh lain: Statemen if...else tanpa tanda kurung keriting ({}). Jika three bernilai true, tidak akan terjadi apapun, four tidak begitu penting, dan juga fungsi launchRocket() pada kasus else tidak akan dijalankan.

+ +
if (one)
+  doOne();
+else if (two)
+  doTwo();
+else if (three)
+  ; // nothing here
+else if (four)
+  doFour();
+else
+  launchRocket();
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ESDraft', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.3', 'Empty statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES1')}}Initial definition.
+ +

Kompabilitas Browser

+ +

{{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}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/statements/export/index.html b/files/id/web/javascript/reference/statements/export/index.html new file mode 100644 index 0000000000..1f6d26b71d --- /dev/null +++ b/files/id/web/javascript/reference/statements/export/index.html @@ -0,0 +1,171 @@ +--- +title: export +slug: Web/JavaScript/Reference/Statements/export +translation_of: Web/JavaScript/Reference/Statements/export +--- +
{{jsSidebar("Statements")}}
+ +

export statement digunakan untuk meng-ekspor fungsi, objects atau primitives dari file yang di berikan (atau module).

+ +
+

Catatan: Fitur ini tidak di implementasikan di browser secara bawaan untuk saat ini. ini hanya diimplementasikan di beberapa transpilers, seperti Traceur CompilerBabel atau Rollup.

+
+ +

Syntax

+ +
export { name1, name2, …, nameN };
+export { variable1 as name1, variable2 as name2, …, nameN };
+export let name1, name2, …, nameN; // also var
+export let name1 = …, name2 = …, …, nameN; // also var, const
+
+export default expression;
+export default function (…) { … } // also class, function*
+export default function name1(…) { … } // also class, function*
+export { name1 as default, … };
+
+export * from …;
+export { name1, name2, …, nameN } from …;
+export { import1 as name1, import2 as name2, …, nameN } from …;
+ +
+
nameN
+
+ +

Identitas yang akan diekspor ( sehingga dapat di impor via import di lain skrip).

+ +

Deskripsi

+ +

Ada dua jenis tipe yang berbeda-beda dari export, masing-masing sesuai dengan salah satu sintaks di atas:

+ + + +

Named exports berguna untuk mengekspor beberapa nilai. Selama import, satu akan menggunakan nama yang sama untuk mengacu pada nilai yang sesuai.

+ +

Mengenai default export, hanya ada satu default export per modul. default export bisa menjadi fungsi, class, objek atau yang lainya. Nilai ini dianggap sebagai  "Pokok" pengeluaran nilai karena akan menjadi sederhana untuk di import.

+ +

Contoh

+ +

Menggunakan named exports

+ +

dalam modul, kita bisa menggunakan kode berikut:

+ +
// module "my-module.js"
+export function cube(x) {
+  return x * x * x;
+}
+const foo = Math.PI + Math.SQRT2;
+export { foo };
+
+ +

Cara ini, di dalam script lain  (cf. import), kita bisa memiliki:

+ +
import { cube, foo } from 'my-module';
+console.log(cube(3)); // 27
+console.log(foo);    // 4.555806215962888
+ +

Menggunakan default export

+ +

Jika kita ingin mengekspor nilai tunggal atau memiliki nilai fallback untuk modul kita, kita bisa menggunakan default export:

+ +
// module "my-module.js"
+export default function cube(x) {
+  return x * x * x;
+}
+
+ +

Kemudian, di lain skrip, akan lebih mudah untuk mengimpor export default :

+ +
import cube from 'my-module';
+console.log(cube(3)); // 27
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-exports', 'Exports')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}} 
+ +

Kompatibilitas browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/statements/for...in/index.html b/files/id/web/javascript/reference/statements/for...in/index.html new file mode 100644 index 0000000000..0162c204ee --- /dev/null +++ b/files/id/web/javascript/reference/statements/for...in/index.html @@ -0,0 +1,201 @@ +--- +title: for...in +slug: Web/JavaScript/Reference/Statements/for...in +tags: + - JavaScript + - Statement +translation_of: Web/JavaScript/Reference/Statements/for...in +--- +
{{jsSidebar("Statements")}}
+ +

Pernyataan for...in mengulang setiap properti enumerable dari sebuah objek, dalam urutan sembarang. Untuk setiap properti yang berbeda, pernyataan dapat dieksekusi.

+ +

Sintak

+ +
for (variable in object) {...
+}
+ +
+
variable
+
Sebuah nama properti yang berbeda ditugaskan untuk variabel pada setiap iterasi.
+
object
+
Objek yang propertinya enumerable yang diiterasi.
+
+ +

Deskripsi

+ +

Perulangan for...in hanya mengiterasi pada properti enumerable. Objek yang dibuat dari built-in konstruktor seperti Array dan Object telah mewarisi properti non-enumerable dari Object.prototype dan String.prototype, seperti {{jsxref("String")}}'s {{jsxref("String.indexOf", "indexOf()")}} metode atau {{jsxref("Object")}}'s {{jsxref("Object.toString", "toString()")}} metode. Perulangan akan iterate atas semua properti enumerable dari objek itu sendiri dan mereka objek mewarisi dari prototipe konstruktor ini (properti lebih dekat ke objek di properti mata rantai prototipe menggantikan prototipe' properti).

+ +

Penghapusan, penambahan atau perubahan pada properti

+ +

Perulangan for...in mengiterasi properti suatu objek dalam urutan sembarang (lihat {{jsxref("Operators/delete", "delete")}} Operator untuk lebih lanjut tentang mengapa salah satu tidak dapat bergantung pada keteraturan tampak dari iterasi, setidaknya dalam pengaturan lintas-browser). Jika properti yang diubah dalam satu iterasi dan kemudian mengunjungi di lain waktu, nilainya dalam lingkaran adalah nilai pada waktu kemudian. Sebuah properti yang dihapus sebelum telah dikunjungi tidak akan dikunjungi nanti. Sifat ditambahkan ke objek dimana iterasi terjadi baik dapat dikunjungi atau dihilangkan dari iterasi. Secara umum yang terbaik adalah tidak untuk menambah, mengubah atau menghapus properti dari objek selama iterasi, selain properti saat ini sedang mengunjungi. Tidak ada jaminan apakah properti menambahkan akan dikunjungi, apakah properti dimodifikasi (selain yang saat ini) akan dikunjungi sebelum atau setelah dimodifikasi, atau apakah properti dihapus akan dikunjungi sebelum dihapus.

+ +

Iterasi Array dan for...in

+ +
+

Catatan: for...in tidak perlu digunakan untuk mengiterasi sebuah {{jsxref("Array")}} dimana urutan indeksnya sangat penting.

+
+ +

Index array hanyalah properti enumerable dengan nama integer dan tidak sama dengan properti Objek pada umumnya. Disini tidak akan menjamin jika for...in akan mengembalikan indek pada urutan tertentu.  Pernyataan for...in akan mengembalikan semua properti enumerable, termasuk didalamnya dengan nama non–integer dan serta turunannya.

+ +

Karena urutan iterasi merupakan implementation-dependent, pengiterasian pada array mungkin tidak membaca elemen pada urutan yang urut. Karena itu lebih baik menggunakan perulangan {{jsxref("Statements/for", "for")}} dengan menggunakan nomor indek (atau {{jsxref("Array.prototype.forEach()")}} atau {{jsxref("Statements/for...of", "for...of")}} loop) ketika mengiterasi array dimana urutan akses sangat penting.

+ +

Iterasi hanya pada properti sendiri

+ +

Jika anda hanya ingin mempertimbangkan properti yang melekat pada objek itu sendri, dan bukan prototypes-nya, gunakan {{jsxref("Object.getOwnPropertyNames", "getOwnPropertyNames()")}} atau lakukan {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}} cek ({{jsxref("Object.prototype.propertyIsEnumerable", "propertyIsEnumerable")}} juga dapat digunakan). Alternatifnya, jika anda tahu disana tidak ada campur tangan kode luar , anda dapat memperpanjang built-in prototypes dengan metode cek.

+ +

Contoh

+ +

Pada fungsi berikut menggunakan sebuah objek argumen. kemudian mengiterasi pada semua properti enumerable pada objek tersebut dan mengembalikan string dari nama properti dan nilainya.

+ +
var obj = {a:1, b:2, c:3};
+
+for (var prop in obj) {
+  console.log("obj." + prop + " = " + obj[prop]);
+}
+
+// Output:
+// "obj.a = 1"
+// "obj.b = 2"
+// "obj.c = 3"
+ +

Fungsi berikut mengiterasi menggunakan {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}}: properti turunannya tidak akan di tampilkan.

+ +
var triangle = {a:1, b:2, c:3};
+
+function ColoredTriangle() {
+  this.color = "red";
+}
+
+ColoredTriangle.prototype = triangle;
+
+var obj = new ColoredTriangle();
+
+for (var prop in obj) {
+  if( obj.hasOwnProperty( prop ) ) {
+    console.log("obj." + prop + " = " + obj[prop]);
+  }
+}
+
+// Output:
+// "obj.color = red"
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.6.3', 'for...in statement')}}{{Spec2('ES1')}}Initial definition.
+ +

Kompabilitas Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Kompabilitas: Ekspresi Initializer

+ +

Pada SpiderMonkey 40 {{geckoRelease(40)}} atau sebelumnya, bisa menggunakan ekspersi initializer (i=0) pada perulangan for...in :

+ +
var obj = {a:1, b:2, c:3};
+for(var i=0 in obj) {
+  console.log(obj[i]);
+}
+// 1
+// 2
+// 3
+
+ +

Perilaku non-standard ini sekarang diabaikan pada versi 40 dan selanjutnya akan disajikan dengan {{jsxref("SyntaxError")}} ("for-in loop head declarations may not have initializers") Peringatan pada konsole ({{bug(748550)}} dan {{bug(1164741)}}).

+ +

Pada mesin lain seperti v8 (Chrome), Chakra (IE/Edge), dan JSC (WebKit/Safari) juga telah menyelidiki untuk menghapus perilaku non standar tersebut.

+ +

Lihat Juga

+ + diff --git a/files/id/web/javascript/reference/statements/fungsi/index.html b/files/id/web/javascript/reference/statements/fungsi/index.html new file mode 100644 index 0000000000..8ac13d31af --- /dev/null +++ b/files/id/web/javascript/reference/statements/fungsi/index.html @@ -0,0 +1,232 @@ +--- +title: Deklarasi Fungsi +slug: Web/JavaScript/Reference/Statements/fungsi +tags: + - JavaScript + - Pernyataan + - Statement +translation_of: Web/JavaScript/Reference/Statements/function +--- +
{{jsSidebar("Statements")}}
+ +

Deklarasi fungsi mendefinisikan sebuah fungsi dengan parameter-parameter yang ditentukan.

+ +

Fungsi juga dapat didefinisikan menggukanan konstruktor {{jsxref("Function")}} dan {{jsxref("Operators/function", "function expression")}}.

+ +

Sintak

+ +
function name([param,[, param,[..., param]]]) {
+   [statements]
+}
+
+ +
+
name
+
Nama dari fungsi.
+
+ +
+
param
+
Nama dari argumen yang akan dilewatkan kepada fungsi. Jumlah maksimal dari argumen berbeda-beda di setiap mesin.
+
+ +
+
statements
+
Statemen-statemen yang membentuk tubuh dari sebuah fungsi.
+
+ +

Deskripsi

+ +

Sebuah fungsi yang diciptakan dengan deklarasi fungsi adalah sebuah objek Function dan memiliki semua properti, method-method dan tingkah laku dari objek Function. Lihat {{jsxref("Function")}} untuk informasi mendetail tentang fungsi-fungsi.

+ +

Sebuah fungsi juga dapat diciptakan menggunakan sebuah ekspresi (lihat  {{jsxref("Operators/function", "function expression")}}).

+ +

Secara default, fungsi mengembalikan nilai undefined. Untuk mengembalikan nilai lain, fungsi tersebut harus memiliki sebuah {{jsxref("Statements/return", "return")}} statement yang menentukan nilai untuk dikembalikan.

+ +

Fungsi yang dibuat secara kondisional

+ +

Fungsi dapat dideklarasikan secara kondisional, yaitu sebuah statement fungsi dapat disarangkan di dalam sebuah statement if. Kebanyakan aplikasi perambah selain Mozilla akan memperlakukan deklarasi kondisional seperti itu sebagai sebuah deklarasi non kondisional dan menciptakan fungsi tersebut meskipun kondisi bernilai benar atau salah, lihat artikel berikut untuk ikhtisar. Untuk alasan tersebut, deklarasi kondisional seharusnya tidak digunakan -- untuk pembuatakan kondisional gunakan ekspresi fungsi sebagai gantinya.

+ +

Pengangkatan deklarasi fungsi

+ +

Deklarasi fungsi di javaScript mengangkat definisi fungsi. Kamu dapat menggunakan fungsi sebelum kamu mendeklarasikan fungsi tersebut.

+ +
hoisted(); // logs "foo"
+
+function hoisted() {
+  console.log('foo');
+}
+
+ +

Dicatat bahwa {{jsxref("Operators/function", "function expressions")}} tidak terangkat:

+ +
notHoisted(); // TypeError: notHoisted is not a function
+
+var notHoisted = function() {
+   console.log('bar');
+};
+
+ +

Contoh

+ +

Menggunakan fungsi

+ +

Kode berikut mendeklarasikan sebuah fungsi yang mengembalikan jumlah total penjualan ketika diberikan angka dari unit-unit yang terjual dari produk a, b, dan c.

+ +
function calc_sales(units_a, units_b, units_c) {
+   return units_a * 79 + units_b * 129 + units_c * 699;
+}
+
+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-13', 'Function definition')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

Kompabilitas Perambah

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Allowed in sloppy mode{{CompatChrome(49.0)}}{{CompatUnknown}}    
Trailing comma in parameters{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Allowed in sloppy mode{{CompatNo}} +

{{CompatChrome(49.0)}}

+
{{CompatUnknown}}     +

{{CompatChrome(49.0)}}

+
Trailing comma in parameters{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Lihat juga

+ + diff --git a/files/id/web/javascript/reference/statements/index.html b/files/id/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..08840f4e1a --- /dev/null +++ b/files/id/web/javascript/reference/statements/index.html @@ -0,0 +1,139 @@ +--- +title: Statements +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - Referensi + - Statement +translation_of: Web/JavaScript/Reference/Statements +--- +
{{jsSidebar("Statements")}}
+ +

Aplikasi JavaScript terdiri dari statemen dengan sebuah sintaks tertentu. Sebuah statement dapat terdiri lebih dari satu baris. Setiap statement dapat berupa sebaris kode jika di pisahkan dengan semikolon ( ; ). Bukan merupakan keyword, tapi sekumpulan keyword.

+ +

Statemen dan deklarasi berdasarkan kategori

+ +

Untuk daftar berdasarkan alfabet lihat pada sidebar sebelah kiri.

+ +

Control flow

+ +
+
{{jsxref("Statements/block", "Block")}}
+
Sebuah block statemen digunakan untuk mengelompokkan zero ( 0 ) atau lebih statement. Block ini dibatasi menggunakan kurung kurawal.
+
{{jsxref("Statements/break", "break")}}
+
Membatasi  loop, switch, atau label statement dan transfer kontrol program pada statement berdasakan statemen akhir.
+
{{jsxref("Statements/continue", "continue")}}
+
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
+
{{jsxref("Statements/Empty", "Empty")}}
+
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
+
{{jsxref("Statements/if...else", "if...else")}}
+
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
+
{{jsxref("Statements/switch", "switch")}}
+
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
+
{{jsxref("Statements/throw", "throw")}}
+
Throws a user-defined exception.
+
{{jsxref("Statements/try...catch", "try...catch")}}
+
Marks a block of statements to try, and specifies a response, should an exception be thrown.
+
+ +

Deklarasi

+ +
+
{{jsxref("Statements/var", "var")}}
+
Mendeklarasikan variabel, biasanya menginisialisasi ke sebuah nilai.
+
{{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Fungsi dan class

+ +
+
{{jsxref("Statements/function", "function")}}
+
Declares a function with the specified parameters.
+
{{jsxref("Statements/function*", "function*")}}
+
Generators functions enable writing iterators more easily.
+
{{jsxref("Statements/return", "return")}}
+
Specifies the value to be returned by a function.
+
{{jsxref("Statements/class", "class")}}
+
Declares a class.
+
+ +

Iterations

+ +
+
{{jsxref("Statements/do...while", "do...while")}}
+
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
+
{{jsxref("Statements/for", "for")}}
+
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
+
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
+
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
+
{{jsxref("Statements/for...in", "for...in")}}
+
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
+
{{jsxref("Statements/for...of", "for...of")}}
+
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
+
{{jsxref("Statements/while", "while")}}
+
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
+
+ +

Others

+ +
+
{{jsxref("Statements/debugger", "debugger")}}
+
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
+
{{jsxref("Statements/export", "export")}}
+
Used to export functions to make them available for imports in external modules, another scripts.
+
{{jsxref("Statements/import", "import")}}
+
Used to import functions exported from an external module, another script.
+
{{jsxref("Statements/label", "label")}}
+
Provides a statement with an identifier that you can refer to using a break or continue statement.
+
+ +
+
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
+
Extends the scope chain for a statement.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
+ +

See also

+ + diff --git a/files/id/web/javascript/sekilas_teknologi_javascript/index.html b/files/id/web/javascript/sekilas_teknologi_javascript/index.html new file mode 100644 index 0000000000..adb6ec5a68 --- /dev/null +++ b/files/id/web/javascript/sekilas_teknologi_javascript/index.html @@ -0,0 +1,87 @@ +--- +title: Ikhtisar Teknologi JavaScript +slug: Web/JavaScript/sekilas_teknologi_JavaScript +translation_of: Web/JavaScript/JavaScript_technologies_overview +--- +
{{JsSidebar("Introductory")}}
+ +

Pengantar

+ +

Jika HTML untuk mengatur struktur dan konten dari halaman web dan CSS untuk menetapkan format dan tampilannya, maka JavaScript digunakan untuk menambah interaksi pada halaman web dan menciptakan aplikasi web yang kaya.

+ +

Namun, istilah "JavaScript" seperti yang dikenal pada konteks browser web berisi beberapa elemen yang sangat berbeda. Salah satunya adalah bahasa intinya (ECMAScript), yang lainnya adalah koleksi dari Web APIs, termasuk DOM (Document Object Model).

+ +

Bahasa inti (ECMAScript) JavaScript

+ +

Bahasa inti dari JavaScript distandarisasi oleh komite ECMA TC39 sebagai bahasa yang bernama ECMAScript.

+ +

Bahasa inti ini juga digunakan pada lingkungan non-browser, misalnya node.js.

+ +

Apa yang termasuk dalam lingkup ECMAScript?

+ +

Diantaranya, ECMAScript menetapkan:

+ + + +

Dukungan browser

+ +

Pada Oktober 2016, versi terbaru dari sebagian besar browser Web sudah menerapkan ECMAScript 5.1 dan ECMAScript 2015, namun versi yang lebih lama (yang masih digunakan) hanya menerapkan ECMAScript 5.

+ +

Masa depan

+ +

ECMAScript Edisi ke-6 mayor telah secara resmi disetujui dan diumumkan sebagai standar pada 17 Juni 1015 oleh ECMA General Assembly. Sejak saat itu Edisi ECMAScript diumumkan secara tahunan.

+ +

API Internasionalisasi

+ +

Spesifikasi API Internasionalisasi ECMAScript merupakan tambahan dari Spesifikasi Bahasa ECMAScript, yang juga distandarisasi oleh Ecma TC39. API internasionalisasi menyediakan kolasi (perbandingan string), format angka, format tanggal dan jam untuk aplikasi JavaScript, memungkinkan aplikasi memilih bahasa dan menyesuaikan fungsi sesuai kebutuhannya. Standar awal telah disetujui pada Desember 2012; status impementasinya dalam browser dicatat di dokumentasi Intl object. Saat ini spesifikasi Internasionalisasi juga disahkan secara tahunan dan browser secara konsisten meningkatkan implementasinya.

+ +

API DOM

+ +

WebIDL

+ +

WebIDL specification memberikan perekat antara teknologi DOM dan ECMAScript.

+ +

Inti dari DOM

+ +

Document Object Model (DOM) adalah bahasa konvensi independen lintas platform untuk mewakili dan berinteraksi dengan objects dalam dokumen HTML, XHTML dan XML. Objects didalam DOM tree dapat dialamatkan dan dimanipulasi dengan menggunakan methods pada objects. Core Document Object Model yang distandarisasi oleh {{glossary("W3C")}}, menetapkan antarmuka bahasa-agnostik untuk mengabstaraksi dokumen HTML dan XML sebagai objects, dan juga menetapkan mekanisme untuk memanipulasi abstraksi ini. Diantara yang ditetapkan oleh DOM, kita dapat menemukan:

+ + + +

Dari sudut pandang ECMAScript, objects yang didefinisikan di spesifikasi DOM disebut "host objects".

+ +

HTML DOM

+ +

Bahasa markup Web (HTML) yang ditetapkan dari sisi DOM. Seperti dalam konsep abstrak yang dibahas diatas pada Inti DOM, HTML juga didefinisikan sebagai sebuah elemen. The HTML DOM menyertakan properti className pada elemen HTML, or APIs seperti {{ domxref("document.body") }}.

+ +

Spesifikasi HTML juga menetapkan batasan pada dokumen; misalnya, ia memerlukan semua elemen anak dari sebuah ul untuk mewakili sebuah daftar tak urut, elemen li untuk mewakili daftar item. Secara umum, ia juga melarang penggunaan elemen dan atribut yang tidak didefinisikan dalam standar.

+ +

Ingin mengetahui Document object, Window object, dan elemen DOM lainnya? Baca DOM documentation.

+ +

API penting lainnya

+ + + +

Dukungan browser

+ +

Seperti kata pengembang web yang berpengalaman, DOM berantakan. Dukungan fitur-fitur DOM antar browser bervarasi, terutama disebabkan karena banyak fitur yang penting dari DOM sangat tidak jelas, spesifikasi (jika ada) dan browser web yang berbeda menambahkan fitur yang tidak kompatibel untuk overlapping use cases (misalnya Internet Explorer event model). Pada Juni 2011, W3C dan khususnya WHATWG menetapkan fitur-fitur lama secara rinci untuk meningkatkan interoperabilitas, dan browser pada akhirnya dapat meningkatkan implementasi mereka berdasarkan spesifikasi ini.

+ +

Sebuah teknik umum, meskipun mungkin bukan yang paling dapat diandalkan, pendekatan kompatibilitas lintas browser adalah dengan menggunakan pustaka JavaScript, yang menggunakan fitur DOM abstrak untuk menjaga API mereka tetap bekerja di browser yang berbeda. Beberapa framework yang paling banyak digunakan adalah jQuery, prototype, dan YUI.

diff --git a/files/id/web/mathml/element/index.html b/files/id/web/mathml/element/index.html new file mode 100644 index 0000000000..cb570e4974 --- /dev/null +++ b/files/id/web/mathml/element/index.html @@ -0,0 +1,234 @@ +--- +title: MathML element reference +slug: Web/MathML/Element +tags: + - MathML + - Referensi MathML +translation_of: Web/MathML/Element +--- +

{{MathMLRef}}

+ +

Ini adalah daftar alfabet dari elemen presentasi MathML.

+ +

Istilah Markup presentasi digunakan untuk menggambarkan struktur tata letak notasi matematika sedangkan konten markup memberikan makna matematika yang mendasari dan tidak seharusnya diberikan oleh parser MathML (lihat {{bug (276028)}}). Jika Anda ingin mempelajari lebih lanjut tentang markup konten yang harus Anda pertimbangkan Chapter 4 pada MathML 3 specification.

+ +

MathML presentation elements A  to Z

+ +
+

math

+ +
    +
  • {{MathMLElement("math")}} (Top-level element)
  • +
+ +

A

+ +
    +
  • {{MathMLElement("maction")}} (Binded actions to sub-expressions)
  • +
  • {{MathMLElement("maligngroup")}} (Alignment group)
  • +
  • {{MathMLElement("malignmark")}} (Alignment points)
  • +
+ +

E

+ +
    +
  • {{MathMLElement("menclose")}} (Enclosed contents)
  • +
  • {{MathMLElement("merror")}} (Enclosed syntax error messages)
  • +
+ +

F

+ +
    +
  • {{MathMLElement("mfenced")}} (Parentheses)
  • +
  • {{MathMLElement("mfrac")}} (Fraction)
  • +
+ +

G

+ +
    +
  • {{MathMLElement("mglyph")}} (Displaying non-standard symbols)
  • +
+ +

I

+ +
    +
  • {{MathMLElement("mi")}} (Identifier)
  • +
+ +

L

+ +
    +
  • {{MathMLElement("mlabeledtr")}} (Labeled row in a table or a matrix)
  • +
  • {{MathMLElement("mlongdiv")}} (Long division notation)
  • +
+ +

M

+ +
    +
  • {{MathMLElement("mmultiscripts")}} (Prescripts and tensor indices)
  • +
+ +

N

+ +
    +
  • {{MathMLElement("mn")}} (Number)
  • +
+ +

O

+ +
    +
  • {{MathMLElement("mo")}} (Operator)
  • +
  • {{MathMLElement("mover")}} (Overscript)
  • +
+ +

P

+ +
    +
  • {{MathMLElement("mpadded")}} (Space around content)
  • +
  • {{MathMLElement("mphantom")}} (Invisible content with reserved space)
  • +
+ +

R

+ +
    +
  • {{MathMLElement("mroot")}} (Radical with specified index)
  • +
  • {{MathMLElement("mrow")}} (Grouped sub-expressions)
  • +
+ +

S

+ +
    +
  • {{MathMLElement("ms")}} (String literal)
  • +
  • {{MathMLElement("mscarries")}} (Annotations such as carries)
  • +
  • {{MathMLElement("mscarry")}} (Single carry, child element of {{MathMLElement("mscarries")}})
  • +
  • {{MathMLElement("msgroup")}} (Grouped rows of {{MathMLElement("mstack")}} and {{MathMLElement("mlongdiv")}} elements)
  • +
  • {{MathMLElement("msline")}} (Horizontal lines inside {{MathMLElement("mstack")}} elements)
  • +
  • {{MathMLElement("mspace")}} (Space)
  • +
  • {{MathMLElement("msqrt")}} (Square root without an index)
  • +
  • {{MathMLElement("msrow")}} (Rows in {{MathMLElement("mstack")}} elements)
  • +
  • {{MathMLElement("mstack")}} (Stacked alignment)
  • +
  • {{MathMLElement("mstyle")}} (Style change)
  • +
  • {{MathMLElement("msub")}} (Subscript)
  • +
  • {{MathMLElement("msup")}} (Superscript)
  • +
  • {{MathMLElement("msubsup")}} (Subscript-superscript pair)
  • +
+ +

T

+ +
    +
  • {{MathMLElement("mtable")}} (Table or matrix)
  • +
  • {{MathMLElement("mtd")}} (Cell in a table or a matrix)
  • +
  • {{MathMLElement("mtext")}} (Text)
  • +
  • {{MathMLElement("mtr")}} (Row in a table or a matrix)
  • +
+ +

U

+ +
    +
  • {{MathMLElement("munder")}} (Underscript)
  • +
  • {{MathMLElement("munderover")}} (Underscript-overscript pair)
  • +
+ +

Other elements

+ +
    +
  • {{MathMLElement("semantics")}} (Container for semantic annotations)
  • +
  • <annotation> (Data annotations)
  • +
  • <annotation-xml> (XML annotations)
  • +
+
+ +

Elemen presentasi MathML berdasarkan kategori

+ +

 

+ +

Elemen tingkat atas

+ + + +

Elemen Token

+ + + +

Tata letak umum

+ + + +

Script dan batas elemen

+ + + +

Tabular Matematika

+ + + +

Matematika dasar

+ + + +

Elemen yang tidak terkategorikan

+ + + +

Anotasi semantik

+ + + +

Lihat juga

+ + diff --git a/files/id/web/mathml/index.html b/files/id/web/mathml/index.html new file mode 100644 index 0000000000..7c41b63f49 --- /dev/null +++ b/files/id/web/mathml/index.html @@ -0,0 +1,76 @@ +--- +title: MathML +slug: Web/MathML +tags: + - Landing + - MathML + - NeedsTranslation + - Reference + - TopicStub + - Web + - XML +translation_of: Web/MathML +--- +
{{MathMLRef}}
+ +

Mathematical Markup Language (MathML) is a dialect of XML for describing mathematical notation and capturing both its structure and content.

+ +

Here you'll find links to documentation, examples, and tools to help you work with this powerful technology. For a quick overview, see the slides for the innovation fairs at Mozilla Summit 2013.

+ +
+
+

MathML reference

+ +
+
MathML element reference
+
Details about each MathML element and compatibility information for desktop and mobile browsers.
+
MathML attribute reference
+
Information about MathML attributes that modify the appearance or behavior of elements.
+
MathML examples
+
MathML samples and examples to help you understand how it works.
+
Authoring MathML
+
Suggestions and tips for writing MathML, including suggested MathML editors and how to integrate their output into Web content.
+
+ +

View All...

+
+ +
+

Getting help from the community

+ + + +

Tools

+ + + + + + +
+
+ +

Browser compatibility

+ + + +

{{Compat("mathml.elements.math", 0)}}

diff --git a/files/id/web/reference/api/index.html b/files/id/web/reference/api/index.html new file mode 100644 index 0000000000..d8589d167f --- /dev/null +++ b/files/id/web/reference/api/index.html @@ -0,0 +1,65 @@ +--- +title: Referensi Web API +slug: Web/Reference/API +tags: + - API + - Landing + - Reference + - Web + - Web Desain +translation_of: Web/Reference/API +--- +

Web menyediakan banyak API untuk melaksanakan berbagai tugas. Seluruh API ini dapat diakses menggunakan kode Javascript, dan memungkinkan kita untuk melakukan perubahan-perubahan minor kepada {{domxref("window")}} atau {{domxref("element")}} maupun menghasilkan efek-efek video dan audio yang luar biasa menggunakan API seperti WebGL dan Web Audio.

+ +

Masing-masing antarmuka dari seluruh API yang ada didaftarkan pada index.

+ +

Ada juga daftar dari semua event yang tersedia pada referensi event.

+ +
+
+
+
Dokumen Object Model
+
DOM adalah API yang memungkinkan modifikasi pada dokumen. Memungkinkan manipulasi dari dokumen {{domxref("Node")}} dan {{domxref("Element")}}. HTML, XML, dan SVG mempunyai kelebihan itu untuk memanipulasi beberapa spesifik element.
+
Device API
+
Merupakan seperangkat APIs yang memungkinkan kita untuk mengakses ke seluruh fitur hardware yang tersedia ke halaman Web dan aplikasi. Misal. Ambient Light Sensor API, Battery Status API, Geolocation API, Pointer Lock API, Proximity API, Device Orientation API, Screen Orientation API, Vibration API.
+
Communication APIs
+
API ini memungkinkan halaman Web dan aplikasi berkomunikasi dengan halaman lain atau perangkat tertentu. Misal. Network Information API, Web Notifications, Simple Push API.
+
Data management APIs
+
Data pengguna dapat disimpan dan di kendalikan menggunakan perangkat API ini. Misal. FileHandle API, IndexedDB.
+
+ +

Tambahan dari API ini yang tersedia untuk setiap halaman Web dan aplikasi, sebuah set yang lebih powerfull yaitu Mozilla API tersedia untuk aplikasi khusus dan bersertifikat.

+ +
+
Privileged APIs
+
Aplikasi khusus merupakan aplikasi yang di install dengan hak khusus yang ditentukan pengguna. Privileged API meliputi: TCP Socket API, Contacts API, Device Storage API, Browser API, Camera API.
+
Certified APIs
+
Aplikasi bersertifikat merupakan aplikasi tingkat rendah yang melakukan operasi penting dalam sebuah sistem operasi seperti Firefox OS. Aplikasi Khusus tidak berinteraksi dengan aplikasi inimenggunakan Web Activities.  Certified APIs meliputi: Bluetooth API, Mobile Connection API, Network Stats API, Telephony, WebSMS, WiFi Information API, Power Management API, Settings API, Idle API, Permissions API, Time/Clock API.
+
+
+ +
+

Komunitas

+ +

Bergabung dengan komunitas API Web pada milis kami atau newsgroup:

+ + + +

Juga, pastikan bergabung pada diskusi secara langsung di channel #webapi di IRC.

+ + + +

Mungkin anda juga tertarik dengan topik berikut:

+ + +
+
+ +

 

diff --git a/files/id/web/reference/index.html b/files/id/web/reference/index.html new file mode 100644 index 0000000000..445d9adf8a --- /dev/null +++ b/files/id/web/reference/index.html @@ -0,0 +1,49 @@ +--- +title: Web technology reference +slug: Web/Reference +tags: + - Landing + - NeedsTranslation + - Reference + - TopicStub + - Web +translation_of: Web/Reference +--- +

{{draft()}}

+

The open Web is built using a number of technologies. Below you'll find links to our reference material for each of them.

+
+
+

Core Web technologies

+
+
+ Web API interface reference
+
+ Reference material for each of the interfaces that comprise the Web's APIs, including the DOM and all of the related APIs and interfaces you can use to build Web content and apps. This list covers all interfaces, arranged alphabetically.
+
+ Web APIs
+
+ A list of the individual APIs and technology suites that make up the overall Web API.
+
+ HTML
+
+ HyperText Markup Language is the language used to describe and define the content of a Web page.
+
+ CSS
+
+ Cascading Style Sheets are used to describe the appearance of Web content.
+
+ SVG
+
+ Scalable Vector Graphics let you describe images as sets of vectors and shapes in order to allow them to scale smoothly regardless of the size at which they're drawn.
+
+ MathML
+
+ The Mathematical Markup Language makes it possible to display complex mathematical equations and syntax.
+
+
+
+

Other technologies

+

To be completed soon...

+
+
+

 

diff --git a/files/id/web/security/index.html b/files/id/web/security/index.html new file mode 100644 index 0000000000..cc8b113b7a --- /dev/null +++ b/files/id/web/security/index.html @@ -0,0 +1,12 @@ +--- +title: Web security +slug: Web/Security +translation_of: Web/Security +--- +

+Memastikan bahwa situs web Anda atau aplikasi web terbuka aman sangat penting. Bahkan bug sederhana dalam kode Anda dapat menyebabkan kebocoran informasi pribadi, dan orang jahat di luar sana berusaha mencari cara untuk mencuri data. Artikel berorientasi keamanan web yang tercantum di sini menyediakan informasi yang dapat membantu Anda mengamankan situs Anda dan kode dari serangan dan pencurian data

+ + +

{{LandingPageListSubpages}}

+ +

{{QuickLinksWithSubpages}}

diff --git a/files/id/web/web_components/index.html b/files/id/web/web_components/index.html new file mode 100644 index 0000000000..326823bdbb --- /dev/null +++ b/files/id/web/web_components/index.html @@ -0,0 +1,230 @@ +--- +title: Web Components +slug: Web/Web_Components +tags: + - Artikel Web + - Gambaran + - HTML Imports + - JavaScript + - Landing + - Pengembangan Web + - Template + - Web Components + - component + - custom elements + - shadow dom + - slot +translation_of: Web/Web_Components +--- +
{{DefaultAPISidebar("Web Components")}}
+ +
+

Web Components adalah kumpulan fitur teknologi yang memungkinkan Anda membuat elemen khusus yang dapat digunakan kembali dengan fungsionalitasnya yang dikemas jauh dari sisa kode Anda dan menggunakannya di aplikasi web Anda.

+
+ +

Konsep dan penggunaan

+ +

Sebagai pengembang, kita semua tahu bahwa menggunakan kembali kode sebanyak mungkin merupakan ide yang bagus. Hal ini biasanya tidak mudah untuk struktur markup kustom memikirkan HTML kompleks (serta gaya dan skrip terkait) yang terkadang harus Anda tulis untuk memnuat kontrol UI khusus, dan bagaimana menggunakannya beberapa kali dapat mengubah halaman Anda menjadi berantankan jika Anda tidak berhati-hati.

+ +

Web Components bertujun untuk menyelesaikan masalah yang terdiri dari tiga teknologi utama, yang dapat digunakan bersama untuk membuat elemen kustom serbaguna dengan fungsionalitas terenkapsulasi yang dapat digunakan kembali di mana pun Anda suka tanpa takut benturan kode.

+ + + +

Pendekatan dasar untuk mengimplementasikan web component biasanya terlihat seperti ini:

+ +
    +
  1. Buat kelas di mana Anda menentukan fungsionalitas web component Anda, menggunakan sintaks kelas ECMAScript 2015 (lihat Kelas untuk informasi lebih lanjut).
  2. +
  3. Daftarkan elemen kustom baru Anda menggunakan metode {{domxref ("CustomElementRegistry.define ()")}}, meneruskan nama elemen yang akan ditentukan, kelas atau fungsi di mana fungsionalitasnya ditentukan, dan secara opsional, elemen apa yang diwarisi dari.
  4. +
  5. Jika perlu, lampirkan shadow DOM ke elemen khusus menggunakan metode {{domxref ("Element.attachShadow ()")}}. Tambahkan child element, event listener, dll., Ke shadow DOM menggunakan metode DOM biasa.
  6. +
  7. Jika perlu, tentukan template HTML menggunakan {{htmlelement ("template")}} dan {{htmlelement ("slot")}}. Sekali lagi gunakan metode DOM biasa untuk mengkloning template dan melampirkannya ke shadow DOM Anda.
  8. +
  9. Gunakan elemen kustom Anda di mana pun Anda suka di halaman Anda, seperti yang Anda lakukan pada elemen HTML biasa.
  10. +
+ +

Tutorial

+ +
+
Menggunakan custom element
+
Panduan yang menunjukkan cara menggunakan fitur elemen khusus untuk membuat komponen web sederhana, serta melihat callback siklus proses dan beberapa fitur lanjutan lainnya.
+
Menggunakan shadow DOM
+
Panduan yang mempelajari dasar-dasar shadow DOM, menunjukkan cara melampirkan shadow DOM ke elemen, menambahkan ke shadow DOM tree, menatanya, dan banyak lagi.
+
Menggunakan templates and slots
+
Panduan yang menunjukkan cara menentukan struktur HTML yang dapat digunakan kembali menggunakan elemen {{htmlelement ("template")}} dan {{htmlelement ("slot")}}, lalu menggunakan struktur tersebut di dalam komponen web Anda.
+
+ +

Referensi

+ +

Custom elements

+ +
+
{{domxref("CustomElementRegistry")}}
+
Berisi fungsionalitas yang terkait dengan elemen kustom, terutama metode {{domxref ("CustomElementRegistry.define()")}} yang digunakan untuk mendaftarkan elemen kustom baru sehingga dapat digunakan di dokumen Anda.
+
{{domxref("Window.customElements")}}
+
Mengembalikan referensi ke objek {{domxref("CustomElementRegistry.define()")}}.
+
Life cycle callbacks
+
Fungsi panggilan balik khusus yang ditentukan di dalam definisi kelas elemen khusus, yang memengaruhi perilakunya: +
    +
  • connectedCallback: Dipanggil saat elemen khusus pertama kali dihubungkan ke DOM dokumen.
  • +
  • disconnectedCallback: Dipanggil ketika elemen khusus terputus dari DOM dokumen.
  • +
  • adoptedCallback: Dipanggil ketika elemen kustom dipindahkan ke dokumen baru.
  • +
  • attributeChangedCallback: Dipanggil ketika salah satu atribut elemen khusus ditambahkan, dihapus, atau diubah.
  • +
+
+
+
    +
+
+
+ +
+
Ekstensi untuk membuat elemen bawaan khusus
+
+
    +
  • Atribut HTML global {{htmlattrxref ("is")}}: Memungkinkan Anda menentukan bahwa elemen HTML standar harus berperilaku seperti elemen bawaan khusus terdaftar.
  • +
  • Opsi "is" dari metode {{domxref ("Document.createElement()")}}: Memungkinkan Anda membuat instance elemen HTML standar yang berperilaku seperti elemen bawaan khusus terdaftar yang diberikan.
  • +
+
+
CSS pseudo-classes
+
Pseudo-classes yang berkaitan secara khusus dengan elemen khusus: +
    +
  • {{cssxref(":defined")}}: Mencocokkan elemen apa pun yang ditentukan, termasuk elemen bawaan dan elemen khusus yang ditentukan dengan CustomElementRegistry.define()).
  • +
  • {{cssxref(":host")}}: Memilih shadow host dari shadow DOM yang berisi CSS yang digunakan di dalamnya.
  • +
  • {{cssxref(":host()")}}: Memilih shadow host dari shadow DOM yang berisi CSS yang digunakan di dalamnya (sehingga Anda dapat memilih elemen khusus dari dalam shadow DOM-nya) tetapi hanya jika pemilih yang diberikan sebagai parameter fungsi cocok dengan shadow host.
  • +
  • {{cssxref(":host-context()")}}: Memilih shadow host dari shadow DOM yang berisi CSS yang digunakan di dalamnya (sehingga Anda dapat memilih elemen khusus dari dalam shadow DOM-nya) tetapi hanya jika pemilih yang diberikan sebagai parameter fungsi cocok dengan leluhur host bayangan di tempat itu itu berada di dalam hierarki DOM.
  • +
+
+
Pseudo-elements yang berkaitan secara khusus dengan elemen khusus: +
    +
  • {{cssxref("::part")}}: Merepresentasikan elemen apa pun dalam shadow tree yang memiliki atribut {{HTMLAttrxRef ("part")}} yang cocok.
  • +
+
+
+ +

Shadow DOM

+ +
+
{{domxref("ShadowRoot")}}
+
Merepresentasikan root node dari shadow DOM subtree.
+
{{domxref("DocumentOrShadowRoot")}}
+
Fitur penentu mixin yang tersedia di seluruh dokumen dan shadow roots.
+
Ekstensi {{domxref("Element")}}
+
Ekstensi ke antarmuka Element yang terkait dengan shadow DOM: +
    +
  • Metode {{domxref ("Element.attachShadow ()")}} melampirkan shadow DOM tree ke elemen yang ditentukan.
  • +
  • Properti {{domxref ("Element.shadowRoot")}} mengembalikan shadow root yang dilampirkan ke elemen yang ditentukan, atau null jika tidak ada shadow root yang terpasang.
  • +
+
+
Penambahan {{domxref ("Node")}} yang relevan
+
Penambahan antarmuka Node yang relevan dengan shadow DOM: +
    +
  • Metode {{domxref ("Node.getRootNode ()")}} mengembalikan root objek konteks, yang secara opsional menyertakan shadow root jika tersedia.
  • +
  • Properti {{domxref ("Node.isConnected")}} mengembalikan boolean yang menunjukkan apakah Node terhubung (langsung atau tidak langsung) ke objek konteks atau tidak, misalnya objek {{domxref ("Document")}} dalam kasus DOM normal, atau {{domxref ("ShadowRoot")}} untuk shadow DOM.
  • +
+
+
Ekstensi {{domxref("Event")}}
+
Ekstensi ke antarmuka Event yang terkait dengan shadow DOM: +
    +
  • {{domxref ("Event.composed")}}: Mengembalikan {{jsxref ("Boolean")}} yang menunjukkan apakah acara akan menyebar melintasi batas shadow DOM ke DOM standar (true), atau tidak (false).
  • +
  • {{domxref("Event.composedPath")}}: Mengembalikan event's path (objek tempat pemroses akan dipanggil). Ini tidak termasuk node dalam shadow tree jika shadow root dibuat dengan {{domxref ("ShadowRoot.mode")}} ditutup.
  • +
+
+
+ +

HTML templates

+ +
+
{{htmlelement("template")}}
+
Berisi fragmen HTML yang tidak dirender saat dokumen penampung awalnya dimuat, tetapi dapat ditampilkan saat runtime menggunakan JavaScript, terutama digunakan sebagai dasar struktur elemen khusus. Antarmuka DOM terkait adalah {{domxref ("HTMLTemplateElement")}}.
+
{{htmlelement("slot")}}
+
Placeholder di dalam web component yang dapat Anda isi dengan markup Anda sendiri, yang memungkinkan Anda membuat DOM tree terpisah dan menyajikannya bersama-sama. Antarmuka DOM terkait adalah {{domxref ("HTMLSlotElement")}}
+
Atribut HTML global slot
+
Menetapkan slot di shadow tree shadow DOM ke sebuah elemen.
+
{{domxref("Slotable")}}
+
Mixin yang diimplementasikan oleh node {{domxref ("Element")}} dan {{domxref ("Text")}}, mendefinisikan fitur yang memungkinkan mereka menjadi konten elemen {{htmlelement ("slot")}}. Mixin mendefinisikan satu atribut, {{domxref ("Slotable.assignedSlot")}}, yang mengembalikan referensi ke slot tempat node disisipkan.
+
+ +
+
Ekstensi {{domxref("Element")}}
+
Extensions ke antarmuka Element yang terkait dengan slot: +
    +
  • {{domxref("Element.slot")}}: Mengembalikan nama slot shadow DOM yang dilampirkan ke elemen.
  • +
+
+
CSS pseudo-elements
+
Pseudo-elements yang berkaitan secara khusus dengan slot: +
    +
  • {{cssxref("::slotted")}}: Mencocokkan konten apa pun yang dimasukkan ke dalam slot.
  • +
+
+
Event {{event("slotchange")}}
+
Diaktifkan pada instance {{domxref ("HTMLSlotElement")}} (elemen {{htmlelement ("slot")}}) saat node yang ada di slot itu berubah.
+
+ +

Contoh

+ +

Kami sedang membangun sejumlah contoh dalam repo GitHub contoh komponen web kami. Lebih banyak akan ditambahkan seiring berjalannya waktu.

+ +

Spesifikasi

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpesifikasiStatusKomentar
{{SpecName("HTML WHATWG","scripting.html#the-template-element","<template> element")}}{{Spec2("HTML WHATWG")}}Definisi dari {{HTMLElement("template")}}.
{{SpecName("HTML WHATWG","custom-elements.html#custom-elements","custom elements")}}{{Spec2("HTML WHATWG")}}Definisi dari HTML Custom Elements.
{{SpecName("DOM WHATWG","#shadow-trees","shadow trees")}}{{Spec2("DOM WHATWG")}}Definisi dari Shadow DOM.
{{SpecName("HTML Imports", "", "")}}{{Spec2("HTML Imports")}}Definisi Impor HTML awal.
{{SpecName("Shadow DOM", "", "")}}{{Spec2("Shadow DOM")}}Definisi Shadow DOM awal.
+ +

Kompabilitas browser

+ +

Umumnya:

+ + + +

Untuk dukungan browser mendetail dari fitur tertentu, Anda harus membaca halaman referensi yang tercantum di atas.

+ +

Lihat juga

+ + diff --git a/files/id/zones/index.html b/files/id/zones/index.html new file mode 100644 index 0000000000..1e9cf86546 --- /dev/null +++ b/files/id/zones/index.html @@ -0,0 +1,70 @@ +--- +title: Zones +slug: Zones +translation_of: Zones +--- +

MDN zones provide you one-stop access to information about specific topic areas or products. Here's a list of all the zones available to you.

+
+
+

Web and app development

+
+
+ App Center
+
+ Learn how to create open Web apps—rich experiences that run across multiple devices and form factors—using the same Web standards and open technologies you already know.
+
+ Developer tools
+
+ Learn how to use the Firefox developer tools to debug, test, and optimize your Web apps and sites.
+
+ Firefox Marketplace
+
+ An open, non-proprietary online marketplace for Web applications built using HTML, CSS, and JavaScript. Submit apps to the Firefox Marketplace or use the code to build your own marketplace.
+
+ Game development
+
+ Learn how to develop games for the Web, how to port existing games to Web technologies, and how to turn your games into Web apps.
+
+ Mozilla Developer Program
+
+ Learn more about the Mozilla Developer Program, where you can sign up for membership in the program, subscribe to our newsletter, and access our growing array of features for Web developers.
+
+
+
+

Products and projects

+
+
+ Emscripten
+
+ An LLVM to JavaScript compiler; this lets you compile, for example, C++ code into JavaScript code which can be run in any Web browser.
+
+ L20n
+
+ A JavaScript localization framework for unleashing your natural language's power with simple code.
+
+ The MDN project
+
+ The Mozilla Developer Network (this site) relies on its community of readers and contributors to grow and improve. You can learn here how to help use, contribute to, and build the code behind MDN!1
+
+ Persona
+
+ A new simple, privacy-sensitive single-sign in system developed by Mozilla which lets users log into your Web site using their email address, freeing you from password management.
+
+

Mozilla technologies

+
+
+ Add-ons
+
+ Learn how to build and install extensions, themes, and plug-ins for Mozilla-based software, including the popular Firefox Web browser.
+
+ Firefox
+
+ Learn all about Firefox, from how to build and revise it to how to build add-ons specifically for it.
+
+ Firefox OS
+
+ A new mobile operating system developed by Mozilla which lets users install and run open Web applications created using HTML, CSS, and JavaScript.
+
+
+
+

 

-- cgit v1.2.3-54-g00ecf