From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- files/uk/learn/common_questions/index.html | 133 +++ .../set_up_a_local_testing_server/index.html | 95 ++ .../cascade_and_inheritance/index.html | 337 ++++++++ files/uk/learn/css/building_blocks/index.html | 90 ++ .../index.html" | 70 ++ files/uk/learn/css/first_steps/index.html | 53 ++ .../index.html" | 129 +++ files/uk/learn/css/index.html | 68 ++ files/uk/learn/css/styling_text/index.html | 57 ++ .../index.html" | 394 +++++++++ .../css_basics/index.html | 273 ++++++ .../dealing_with_files/index.html | 101 +++ .../how_the_web_works/index.html | 94 ++ .../html_basics/index.html | 214 +++++ .../learn/getting_started_with_the_web/index.html | 64 ++ .../installing_basic_software/index.html | 63 ++ .../javascript_basics/index.html | 401 +++++++++ .../publishing_your_website/index.html | 111 +++ .../what_will_your_website_look_like/index.html | 118 +++ .../index.html" | 164 ++++ files/uk/learn/how_to_contribute/index.html | 83 ++ files/uk/learn/html/forms/index.html | 77 ++ .../uk/learn/html/forms/your_first_form/index.html | 298 +++++++ files/uk/learn/html/index.html | 54 ++ .../creating_hyperlinks/index.html | 322 +++++++ .../introduction_to_html/debugging_html/index.html | 186 ++++ .../getting_started/index.html | 522 +++++++++++ .../html_text_fundamentals/index.html | 953 +++++++++++++++++++++ .../uk/learn/html/introduction_to_html/index.html | 55 ++ .../scho_v_head_metadani_v_html/index.html | 276 ++++++ .../learn/html/multimedia_and_embedding/index.html | 55 ++ files/uk/learn/html/tables/index.html | 40 + files/uk/learn/index.html | 112 +++ .../javascript/client-side_web_apis/index.html | 43 + files/uk/learn/javascript/first_steps/index.html | 69 ++ .../first_steps/what_is_javascript/index.html | 422 +++++++++ files/uk/learn/javascript/index.html | 65 ++ .../uk/learn/javascript/objects/basics/index.html | 259 ++++++ files/uk/learn/javascript/objects/index.html | 46 + .../objects/object-oriented_js/index.html | 295 +++++++ .../index.html" | 51 ++ .../index.html" | 57 ++ files/uk/learn/server-side/django/index.html | 60 ++ .../server-side/django/introduction/index.html | 285 ++++++ .../uk/learn/server-side/express_nodejs/index.html | 77 ++ .../server-side/express_nodejs/routes/index.html | 644 ++++++++++++++ files/uk/learn/server-side/index.html | 52 ++ .../git_\321\202\320\260_github/index.html" | 86 ++ files/uk/learn/tools_and_testing/index.html | 61 ++ .../index.html" | 138 +++ .../znayomymos_zi_svelte/index.html" | 536 ++++++++++++ .../index.html" | 37 + .../index.html" | 41 + .../index.html" | 75 ++ .../index.html" | 315 +++++++ .../index.html" | 202 +++++ 56 files changed, 9978 insertions(+) create mode 100644 files/uk/learn/common_questions/index.html create mode 100644 files/uk/learn/common_questions/set_up_a_local_testing_server/index.html create mode 100644 files/uk/learn/css/building_blocks/cascade_and_inheritance/index.html create mode 100644 files/uk/learn/css/building_blocks/index.html create mode 100644 "files/uk/learn/css/css_\321\200\320\276\320\267\320\274\321\226\321\202\320\272\320\260/index.html" create mode 100644 files/uk/learn/css/first_steps/index.html create mode 100644 "files/uk/learn/css/first_steps/\321\211\320\276_\321\202\320\260\320\272\320\265_css/index.html" create mode 100644 files/uk/learn/css/index.html create mode 100644 files/uk/learn/css/styling_text/index.html create mode 100644 "files/uk/learn/css/styling_text/\321\201\321\202\320\270\320\273\321\226_\321\201\320\277\320\270\321\201\320\272\321\226\320\262/index.html" create mode 100644 files/uk/learn/getting_started_with_the_web/css_basics/index.html create mode 100644 files/uk/learn/getting_started_with_the_web/dealing_with_files/index.html create mode 100644 files/uk/learn/getting_started_with_the_web/how_the_web_works/index.html create mode 100644 files/uk/learn/getting_started_with_the_web/html_basics/index.html create mode 100644 files/uk/learn/getting_started_with_the_web/index.html create mode 100644 files/uk/learn/getting_started_with_the_web/installing_basic_software/index.html create mode 100644 files/uk/learn/getting_started_with_the_web/javascript_basics/index.html create mode 100644 files/uk/learn/getting_started_with_the_web/publishing_your_website/index.html create mode 100644 files/uk/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html create mode 100644 "files/uk/learn/getting_started_with_the_web/\321\226\320\275\321\202\320\265\321\200\320\275\320\265\321\202_\321\202\320\260_\320\262\320\265\320\261-\321\201\321\202\320\260\320\275\320\264\320\260\321\200\321\202\320\270/index.html" create mode 100644 files/uk/learn/how_to_contribute/index.html create mode 100644 files/uk/learn/html/forms/index.html create mode 100644 files/uk/learn/html/forms/your_first_form/index.html create mode 100644 files/uk/learn/html/index.html create mode 100644 files/uk/learn/html/introduction_to_html/creating_hyperlinks/index.html create mode 100644 files/uk/learn/html/introduction_to_html/debugging_html/index.html create mode 100644 files/uk/learn/html/introduction_to_html/getting_started/index.html create mode 100644 files/uk/learn/html/introduction_to_html/html_text_fundamentals/index.html create mode 100644 files/uk/learn/html/introduction_to_html/index.html create mode 100644 files/uk/learn/html/introduction_to_html/scho_v_head_metadani_v_html/index.html create mode 100644 files/uk/learn/html/multimedia_and_embedding/index.html create mode 100644 files/uk/learn/html/tables/index.html create mode 100644 files/uk/learn/index.html create mode 100644 files/uk/learn/javascript/client-side_web_apis/index.html create mode 100644 files/uk/learn/javascript/first_steps/index.html create mode 100644 files/uk/learn/javascript/first_steps/what_is_javascript/index.html create mode 100644 files/uk/learn/javascript/index.html create mode 100644 files/uk/learn/javascript/objects/basics/index.html create mode 100644 files/uk/learn/javascript/objects/index.html create mode 100644 files/uk/learn/javascript/objects/object-oriented_js/index.html create mode 100644 "files/uk/learn/javascript/\320\260\321\201\320\270\320\275\321\205\321\200\320\276\320\275\320\275\320\270\320\271/index.html" create mode 100644 "files/uk/learn/javascript/\320\261\321\203\320\264\321\226\320\262\320\265\320\273\321\214\320\275\321\226_\320\261\320\273\320\276\320\272\320\270/index.html" create mode 100644 files/uk/learn/server-side/django/index.html create mode 100644 files/uk/learn/server-side/django/introduction/index.html create mode 100644 files/uk/learn/server-side/express_nodejs/index.html create mode 100644 files/uk/learn/server-side/express_nodejs/routes/index.html create mode 100644 files/uk/learn/server-side/index.html create mode 100644 "files/uk/learn/tools_and_testing/git_\321\202\320\260_github/index.html" create mode 100644 files/uk/learn/tools_and_testing/index.html create mode 100644 "files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_javascript-\321\204\321\200\320\265\320\271\320\274\320\262\320\276\321\200\320\272\321\226\320\262_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/index.html" create mode 100644 "files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_javascript-\321\204\321\200\320\265\320\271\320\274\320\262\320\276\321\200\320\272\321\226\320\262_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/znayomymos_zi_svelte/index.html" create mode 100644 "files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_\321\226\320\275\321\201\321\202\321\200\321\203\320\274\320\265\320\275\321\202\321\226\320\262_\320\262\320\265\320\261-\321\200\320\276\320\267\321\200\320\276\320\261\320\272\320\270_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/index.html" create mode 100644 "files/uk/learn/tools_and_testing/\321\202\320\265\321\201\321\202\321\203\320\262\320\260\320\275\320\275\321\217_\320\272\321\200\320\276\321\201\320\261\321\200\320\260\321\203\320\267\320\265\321\200\320\275\320\276\321\201\321\202\321\226/index.html" create mode 100644 "files/uk/learn/\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" create mode 100644 "files/uk/learn/\320\275\320\260\320\262\321\207\320\260\320\275\320\275\321\217_\321\202\320\260_\320\276\321\202\321\200\320\270\320\274\320\260\320\275\320\275\321\217_\320\264\320\276\320\277\320\276\320\274\320\276\320\263\320\270/index.html" create mode 100644 "files/uk/learn/\321\204\321\200\320\276\320\275\321\202-\320\265\320\275\320\264_\320\262\320\265\320\261-\321\200\320\276\320\267\321\200\320\276\320\261\320\275\320\270\320\272/index.html" (limited to 'files/uk/learn') diff --git a/files/uk/learn/common_questions/index.html b/files/uk/learn/common_questions/index.html new file mode 100644 index 0000000000..cef04ddf9c --- /dev/null +++ b/files/uk/learn/common_questions/index.html @@ -0,0 +1,133 @@ +--- +title: Поширені питання +slug: Learn/Common_questions +tags: + - Інфраструктура + - Мережа + - Механізми мережі + - Навчання + - Написання сценаріїв +translation_of: Learn/Common_questions +--- +
{{LearnSidebar}}
+ +

Цей розділ надає відповіді на поширені питання, які проте не обов'язково є частиною основного матеріалу для вивчення (як-от статті по HTML чи CSS.) Ці статті надані для самостійного опрацювання.

+ +

Як працює мережа

+ +

Розділ розкриває механізм мережі - це питання, що відносяться до загальних знань про екосистему мережі та принципу її роботи.

+ +
+
+

Як працює Інтернет?

+
+
Інтернет - це основа мережі, технічна інфраструктура, завдяки якій вона можлива. В найпростішому вигляді - це велика мережа комп'ютерів, що спілкуються один з одним. В цій статті розглядається принцип його роботи на базовому рівні.
+
+

Яка різниця між веб-сторінкою, сайтом, веб-сервером та пошуковою системою?

+
+
У цій статті ви дізнаєтесь про різні веб-поняття: веб-сторінки, веб-сайти, веб-сервери та пошукові системи. Нові користувачі Інтернету часто плутають  або використовуються неправильно ці терміни. Давайте дізнаємося, що вони означають!
+
+

Що таке URL?

+
+
Поряд з {{Glossary("Hypertext","гіпертекстом")}} та {{Glossary("HTTP")}}, URL - одне з ключових понять мережі. Це механізм, який використовують {{Glossary("Browser","переглядачі")}} для отримання будь-яких доступних  в мережі ресурсів.
+
+

Що таке доменне ім'я?

+
+
Доменні імена є ключовою частиною інфраструктури Інтернету. Вони надають адресу для будь-якого веб-сервера, доступного в Інтернеті, у вигляді, що легко читається людиною
+
+

Що таке веб-сервер?

+
+
Термін "веб-сервер" може означати обладнання або програмне забезпечення, яке обслуговує веб-сайти клієнтів в Інтернеті, а також обидві частини, що працюють разом. У цій статті ми розглянемо, як працюють веб-сервери, та чому вони важливі.
+
+

Що таке гіперпосилання?

+
+
В цій статті ми розглянемо, що таке {{Glossary("Hyperlinks","гіперпосилання")}}, та чому вони мають значення. 
+
+ +

Інструменти та налаштування

+ +

Питання, що пов'язані з інструментами/програмами, які ви можете використати для створення сайтів.

+ +
+
+

Скільки коштує щось зробити в мережі?

+
+
Коли ви запускаєте сайт, це може вам нічого не коштувати або ваші витрати можуть бути захмарні. В статті ми вияснимо скільки що коштуватиме, та що ви матимете за плату чи даром.
+
+

Які програми потрібні для створення сайту?

+
+
Ця стаття про програмні компоненти, що необхідні вам для редагування, вивантаження чи перегляду сайту.
+
+

Які є текстові редактори?

+
+
В статті окреслено  деякі речі, про які потрібно замислитися перед вибором та встановленням текстового редактора для веб-розробки.
+
+

Що таке "Інструменти розробника" в браузері?

+
+
Кожен браузер має набір інструментів розробника для налагодження HTML, CSS та іншого веб-коду. Дізнайтесь, як використовувати їхні основні функції.
+
+

Як переконаєтись, що сайт працює належним чином?

+
+
Ви оприлюднили сайт в Інтернеті — чудово! Та чи впевнені ви, що він працює належним чином? Дізнайтеся про кілька основних способів усунення несправностей.
+
+

Як налаштувати локальний сервер для тестування?

+
+
+
+

Стаття про налаштовування, на вашому комп'ютері, простого локального сервера для  тестування та основи його використання.

+
+
+
+

Як вивантажити файли на веб-сервер?

+
+
Як оприлюднити сайт в Інтернеті, щоб люди мала доступ до нього з їхніх комп'ютерів? Зробимо це за допомогою одого з найпоширеніших способів — інструментів FTP
+
+

Як користуватись GitHub сторінками ?

+
+
Ця стаття містить загальний посібник по публікації вмісту за допомогою gh-сторінок GitHub.
+
+

Як розмістити свій сайт на Google App Engine?

+
+
Шукаєте місце для розміщення вашого веб-сайту? Це покроковий посібник по розміщенню вашого сайту на Google App Engine.
+
+

Які є інструменти для налагодження та підвищення ефективності сайту?

+
+
В наборі статей показано, як використовувати інструменти розробника в Firefox для налагодження та підвищення ефективності сайту. А саме — інструментів для перевірки використання пам'яті, дерева викликів JavaScript, кількості виділених версій DOM та інших.
+
+ +

Дизайн та доступність 

+ +

У розділі перелічені питання, пов'язані з естетикою, структурою сторінки, методами  досягнення доступності тощо.

+ +
+
+

Як почати розробку сайту?

+
+
Стаття про найважливіший перший крок кожного проекту: визначте, що ви хочете цим досягти.
+
+

Що містять поширені веб-макети?

+
+
При проектуванні сторінок сайту, добре мати уявлення про найпоширеніші макети. Ця стаття про декілька типових веб-макетів та їх окремі компоненти.
+
+

Що таке доступність?

+
+
Стаття містить основні поняття, що визначають доступність сайтів.
+
+

Як ми можемо спроектувати сайт для різноманітних користувачів?

+
+
Стаття містить основні методи, які допоможуть вам розробляти сайти для будь-яких користувачів — переваги швидкого доступу та подібні речі.
+
+

Які особливості HTML сприяють доступності?

+
+
В статті описуються специфічні особливості HTML, які можна використати, щоб зробити веб-сторінку більш доступною для людей з різними обмеженнями.
+
+ +

Питання з HTML, CSS та JavaScript

+ +

Про поширені вирішеня проблем в HTML/CSS/JavaScript читайте в наступних статтях:

+ + diff --git a/files/uk/learn/common_questions/set_up_a_local_testing_server/index.html b/files/uk/learn/common_questions/set_up_a_local_testing_server/index.html new file mode 100644 index 0000000000..5ebd96246f --- /dev/null +++ b/files/uk/learn/common_questions/set_up_a_local_testing_server/index.html @@ -0,0 +1,95 @@ +--- +title: Як налаштувати локальний тестовий сервер? +slug: Learn/Common_questions/set_up_a_local_testing_server +translation_of: Learn/Common_questions/set_up_a_local_testing_server +--- +
+

 Стаття про те, як налаштувати на вашому комп'ютері простий локальний тестовий сервер та основи його використання.

+
+ + + + + + + + + + + + +
Передумови:Вам потрібно спочатку дізнатись, як працює інтернет і що таке веб-сервер.
Мета:Ви дізнаєтеся, як налаштувати локальний тестовий сервер.
+ +

Локальні файли порівняно з віддаленими

+ +

Протягом більшої частини вивчення зони навчання ми пропонуємо вам просто відкрити свої приклади безпосередньо в браузері. Це можна зробити двічі клацнувши файл HTML, перетягнувши його в вікно браузера або вибравши «Файл»> «Відкрити ...» та знайти файл HTML. Є ще багато способів це зробити.

+ +

Якщо шлях веб-адреси починається з file://, а потім йде шлях до файлу на локальному жорсткому диску, використовується локальний файл. На відміну від цього, якщо ви переглядаєте один з наших прикладів, розміщених на GitHub (або приклад на якомусь іншому віддаленому сервері), веб-адреса почнеться з http:// або https://, щоб показати, що файл буде отримано через HTTP .

+ +

Проблема з тестуванням локальних файлів

+ +

Деякі приклади не працюватимуть, якщо ви відкриєте їх як локальні файли. Це може бути з різних причин, найбільш імовірно:

+ + + +

Запуск простого локального HTTP-сервера

+ +

Щоб подолати проблему з асинхронними запитами, та перевірити такі приклади, ми повинні запустити їх на локальному веб-сервері. Для наших цілей одним з найпростіших способів зробити це — використати модуль Python SimpleHTTPServer.

+ +

Як це зробити:

+ +
    +
  1. +

    Встановити Python. Якщо ви використовуєте Linux або Mac OS X, він вже має бути доступним у вашій системі. Якщо ви користувач Windows, ви можете отримати інсталятор з домашньої сторінки Python та дотримуватесь інструкцій, щоб встановити його:

    + +
      +
    • Перейдіть до python.org
    • +
    • Натисніть кнопку «Download» віберіть «Windows».
    • +
    • У списку виберіть виконавчий файл Windows x86 executable installer або Windows x86-64 executable installer та завантажте його. 
    • +
    • Після завантаження запустіть його.
    • +
    • На першій сторінці встановлення переконайтеся, що відмітили "Додати Python 3.xxx до PATH".
    • +
    • Натисніть кнопку «Встановити», а після завершення інсталяції — «Закрити».
    • +
    +
  2. +
  3. +

    Відкрийте командний рядок (Windows) або термінал (OS X/Linux). Щоб перевірити, чи встановлено Python, введіть таку команду:

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

    Ви маєте отриматити номер версії. Якщо це так, то перейдіть до каталогу, в якому ваш приклад, за допомогою команди cd.

    + +
    # include the directory name to enter it, for example
    +cd Desktop
    +# use two dots to jump up one directory level if you need to
    +cd ..
    +
  6. +
  7. +

    Щоб запустити сервер у цьому каталозі, введіть команду:

    + +
    # If Python version returned above is 3.X
    +python -m http.server
    +# If Python version returned above is 2.X
    +python -m SimpleHTTPServer
    +
  8. +
  9. +

    Зазвичай він буде запускати вміст каталогу на локальному веб-сервері по порту 8000. Ви можете перейти на цей сервер, зайшовши на адресу localhost: 8000 у своєму переглядачі. Ви побачите там вміст вказаного каталогу — натисніть файл HTML, який ви хочете запустити.

    +
  10. +
+ +
+

Примітка: Якщо у вас вже щось працює по порту 8000, ви можете вибрати інший, запустивши команду сервера з іншим номером порту, як-от python -m http.server 7800 (Python 3.x) або python -m SimpleHTTPServer 7800 (Python 2.x). Після цього ви можете отримати доступ до свого вмісту по localhost:7800.

+
+ +

Запуск мов серверної частини локально

+ +

Модуль Python SimpleHTTPServer (python 2.0) http.server (python 3.0) корисний, але він не знає як запустити код написаний на таких мовах як Python, PHP чи JavaScript. To handle that you'll need something more — exactly what you'll need depends on the server-side language you are trying to run. Here are a few examples:

+ + diff --git a/files/uk/learn/css/building_blocks/cascade_and_inheritance/index.html b/files/uk/learn/css/building_blocks/cascade_and_inheritance/index.html new file mode 100644 index 0000000000..5444f5713a --- /dev/null +++ b/files/uk/learn/css/building_blocks/cascade_and_inheritance/index.html @@ -0,0 +1,337 @@ +--- +title: Cascade and inheritance +slug: Learn/CSS/Building_blocks/Cascade_and_inheritance +translation_of: Learn/CSS/Building_blocks/Cascade_and_inheritance +--- +
{{LearnSidebar}}{{NextMenu("Learn/CSS/Building_blocks/Selectors", "Learn/CSS/Building_blocks")}}
+ +

Мета  цього уроку - розвинути розуміння найфундаментальніших концептів CSS — каскадності (cascade), специфічності (specificity), і наслідування (inheritance) — ці принципи контролюють те, як  CSS застосовується до елементів HTML і як вирішуються конфлікти між правилами CSS.

+ +

Опрацювання цього уроку може здатися не настільки актуальним на даному етапі і занадто академічним порівняно з іншими частинами курсу, однак розуміння цих концепцій збереже вам багато часу в майбутньому. Ми заохочуємо вас опрацювати цю частину курсу уважно і впевнитися, що ви розумієте ці концепти перед тим, як рухатися далі. 

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.)
Objective:To learn about the cascade and specificity, and how inheritance works in CSS.
+ +

Правила CSS, що конфліктують між собою

+ +

CSS означає Cascading Style Sheets (Каскадні Таблиці Стилів), і розуміння першого слова каскадний є надзвичайно важливим — спосіб поведінки каскадів це ключ до розуміння CSS.

+ +

Рано чи пізно, ви будете працювати над проектом і потрапите в ситуацію, коли правила CSS, які повинні були б застосуватися до якогось певного HTML елемента, не працюють.  Як правило, проблема полягатиме в тому, що ви створили два різних СSS правила, які можуть потенційно застосуватися до одного і того самого елемента. Каскад (cascade), так само як і тісно пов*язаний із ним концепт специфічності - це механізми, які контролюють те, яке саме із CSS правил застосується в випадку такого конфлікту. Правило, яке застосується до вашого елементу може бути далеко не тим, на котре ви очікували. Для того, щоб уникнути таких ситуацій, потрібно зрозуміти, як саме працюють ці механізми. 

+ +

Так само важливим є і концепт наслідування (inheritance), який полягає в тому, що деякі CSS властивості (CSS properties) по замовчуванню наслідують ознаки своїх батьківських елементів (parent elements), а деякі ні. Це так само може призвести до неочікуваних ситуацій.

+ +

Для початку, поглянемо на концепції із якими ми матимемо справу в загальному, а потім розберемо кожну із них по черзі, щоб побачити те, як вони співпрацюють між собою і іншими правилами CSS, які ви написали. Зрозуміти ці концепти може бути непросто спочатку, однак в процесі написання і практикування з CSS, вам буде все легше і легше  розуміти і те, як саме воно працює. 

+ +

Каскад (cascade)

+ +

Каскад — на найпростішому рівні, цей принцип полягає в тому, що порядок CSS правил має значення. В випадках, коли можна застосувати одне із двох різних правил із однаковою специфічністю, вибирається те правило, яке зазначене останнім. 

+ +

В нашому прикладі ми маємо два правила, що могли б бути застосовані до елемента  h1. Елемент h1 в кінцевому результаті виявиться синім — ці два правила мають ідентичний селектор, і, як результат, однакову специфічність, а тому той, який іде останнім по порядку, "перемагає".

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/cascade-simple.html", '100%', 400)}} 

+ +

Специфічність (specificity)

+ +

Принцип специфічності полягає в тому, як саме браузер вирішує те, яке із CSS правил застосувати тоді, коли різні правила відносяться до різних селеторів, але все одно можуть бути застосовані до одного і того самого елемента. В певному сенсі це міра того, наскільки специфічним буде вибір селектора.

+ + + +

Час для прикладу: ми знову бачимо 2 правила, що можуть бути застосовані до елемента  h1. В кінцквому результаті  h1 стає червоним — селектор по класу надає своєму правилу більшої специфічності,  а тому браузер застосує саме його, не зважаючи на те, що по порядку він йде другим.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/specificity-simple.html", '100%', 500)}} 

+ +

Ми пояснимо розрахунок специфічності далі у цій статті. 

+ +

Inheritance

+ +

Inheritance also needs to be understood in this context — some CSS property values set on parent elements are inherited by their child elements, and some aren't.

+ +

For example, if you set a color and font-family on an element, every element inside it will also be styled with that color and font, unless you've applied different color and font values directly to them.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/inheritance-simple.html", '100%', 550)}} 

+ +

Some properties do not inherit — for example if you set a {{cssxref("width")}} of 50% on an element, all of its descendants do not get a width of 50% of their parent's width. If this was the case, CSS would be very frustrating to use!

+ +
+

Note: On MDN CSS property reference pages you can find a technical information box, usually at the bottom of the specifications section, which lists a number of data points about that property, including whether it is inherited or not. See the color property Specifications section, for example.

+
+ +

Understanding how the concepts work together

+ +

These three concepts together control which CSS applies to what element; in the below sections we'll see how they work together. It can sometimes seem a little bit complicated, but you will start to remember them as you get more experienced with CSS, and you can always look up the details if you forget! Even experienced developers don't remember all the details.

+ +

Understanding inheritance

+ +

We'll start with inheritance. In the example below we have a {{cssxref("ul")}}, with two levels of unordered lists nested inside it. We have given the outer <ul> a border, padding, and a font color.

+ +

The color has applied to the direct children, but also the indirect children — the immediate child <li>s, and those inside the first nested list. We have then added a class of special to the second nested list and applied a different color to it. This then inherits down through its children.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/inheritance.html", '100%', 700)}} 

+ +

Things like widths (as mentioned above), margins, padding, and borders do not inherit. If a border were to be inherited by the children of our list, every single list and list item would gain a border — probably not an effect we would ever want!

+ +

Which properties are inherited by default and which aren't is largely down to common sense.

+ +

Controlling inheritance

+ +

CSS provides four special universal property values for controlling inheritance. Every CSS property accepts these values.

+ +
+
{{cssxref("inherit")}}
+
Sets the property value applied to a selected element to be the same as that of its parent element. Effectively, this "turns on inheritance".
+
{{cssxref("initial")}}
+
Sets the property value applied to a selected element to be the same as the value set for that element in the browser's default style sheet. If no value is set by the browser's default style sheet and the property is naturally inherited, then the property value is set to inherit instead.
+
{{cssxref("unset")}}
+
Resets the property to its natural value, which means that if the property is naturally inherited it acts like inherit, otherwise it acts like initial.
+
+ +
+

Note: There is also a newer value, {{cssxref("revert")}}, which has limited browser support.

+
+ +
+

Note: See {{SectionOnPage("/en-US/docs/Web/CSS/Cascade", "Origin of CSS declarations")}} for more information on each of these and how they work.

+
+ +

We can look at a list of links and explore how the universal values work. The live example below allows you to play with the CSS and see what happens when you make changes. Playing with code really is the best way to get to grips with HTML and CSS.

+ +

For example:

+ +
    +
  1. The second list item has the class my-class-1 applied. This sets the color of the a element nested inside to inherit. If you remove the rule how does it change the color of the link?
  2. +
  3. Do you understand why the third and fourth links are the color that they are? Check the description of the values above if not.
  4. +
  5. Which of the links will change color if you define a new color for the <a> element — for example a { color: red; }?
  6. +
+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/keywords.html", '100%', 700)}} 

+ +

Resetting all property values

+ +

The CSS shorthand property all can be used to apply one of these inheritance values to (almost) all properties at once. Its value can be any one of the inheritance values (inherit, initial, unset, or revert). It's a convenient way to undo changes made to styles so that you can get back to a known starting point before beginning new changes.

+ +

In the below example we have two blockquotes. The first has styling applied to the blockquote element itself, the second has a class applied to the blockquote which sets the value of all to unset.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/all.html", '100%', 700)}} 

+ +

Try setting the value of all to some of the other available values and observe what the difference is.

+ +

Розуміння каскадів

+ +

Ми тепер розуміємо, чому параграф, що знаходиться всередині структури HTML документа, має такий самий коляр як і той, що вказаний в CSS для елементу  <body>. З початкових уроків ми розуміємо також  from the introductory lessons we have an understanding of how to change the CSS applied to something at any point in the document — whether by assigning CSS to an element or creating a class. We will now take a proper look at how the cascade defines which CSS rules apply when more than one thing could style an element.

+ +

There are three factors to consider, listed here in decreasing order of importance. Earlier ones overrule later ones:

+ +
    +
  1. Importance
  2. +
  3. Specificity
  4. +
  5. Source order
  6. +
+ +

We will look at these from the bottom up, to see how browsers figure out exactly what CSS should be applied.

+ +

Source order

+ +

We have already seen how source order matters to the cascade. If you have more than one rule, which has exactly the same weight, then the one that comes last in the CSS will win. You can think of this as rules which are nearer the element itself overwriting early ones until the last one wins and gets to style the element.

+ +

Specificity

+ +

Once you understand the fact that source order matters, at some point you will run into a situation where you know that a rule comes later in the stylesheet, but an earlier, conflicting, rule is applied. This is because that earlier rule has a higher specificity — it is more specific, and therefore is being chosen by the browser as the one that should style the element.

+ +

As we saw earlier in this lesson, a class selector has more weight than an element selector, so the properties defined on the class will override those applied directly to the element.

+ +

Something to note here is that although we are thinking about selectors, and the rules that are applied to the thing they select, it isn't the entire rule which is overwritten, only the properties which are the same.

+ +

This behavior helps avoid repetition in your CSS. A common practice is to define generic styles for the basic elements, and then create classes for those which are different. For example, in the stylesheet below we have defined generic styles for level 2 headings, and then created some classes which change only some of the properties and values. The values defined initially are applied to all headings, then the more specific values are applied to the headings with the classes.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/mixing-rules.html", '100%', 700)}} 

+ +

Let's now have a look at how the browser will calculate specificity. We already know that an element selector has low specificity and can be overwritten by a class. Essentially a value in points is awarded to different types of selectors, and adding these up gives you the weight of that particular selector, which can then be assessed against other potential matches.

+ +

The amount of specificity a selector has is measured using four different values (or components), which can be thought of as thousands, hundreds, tens and ones — four single digits in four columns:

+ +
    +
  1. Thousands: Score one in this column if the declaration is inside a {{htmlattrxref("style")}} attribute, aka inline styles. Such declarations don't have selectors, so their specificity is always simply 1000.
  2. +
  3. Hundreds: Score one in this column for each ID selector contained inside the overall selector.
  4. +
  5. Tens: Score one in this column for each class selector, attribute selector, or pseudo-class contained inside the overall selector.
  6. +
  7. Ones: Score one in this column for each element selector or pseudo-element contained inside the overall selector.
  8. +
+ +
+

Note: The universal selector (*), combinators (+, >, ~, ' '), and negation pseudo-class (:not) have no effect on specificity.

+
+ +

The following table shows a few isolated examples to get you in the mood. Try going through these, and making sure you understand why they have the specificity that we have given them. We've not covered selectors in detail yet, but you can find details of each selector on the MDN  selectors reference.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SelectorThousandsHundredsTensOnesTotal specificity
h100010001
h1 + p::first-letter00030003
li > a[href*="en-US"] > .inline-warning00220022
#identifier01000100
No selector, with a rule inside an element's {{htmlattrxref("style")}} attribute10001000
+ +

Before we move on, let's look at an example in action.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/specificity-boxes.html", '100%', 700)}} 

+ +

So what's going on here? First of all, we are only interested in the first seven rules of this example, and as you'll notice, we have included their specificity values in a comment before each one.

+ + + +
    +
+ +
+

Note: This has only been an approximate example for ease of understanding. In actuality, each selector type has its own level of specificity that cannot be overwritten by selectors with a lower specificity level. For example, a million class selectors combined would not be able to overwrite the rules of one id selector.

+ +

A more accurate way to evaluate specificity would be to score the specificity levels individually starting from highest and moving on to lowest when necessary. Only when there is a tie between selector scores within a specificity level do you need to evaluate the next level down; otherwise, you can disregard the lower specificity level selectors since they can never overwrite the higher specificity levels.

+
+ +

!important

+ +

There is a special piece of CSS that you can use to overrule all of the above calculations, however you should be very careful with using it — !important. This is used to make a particular property and value the most specific thing, thus overriding the normal rules of the cascade.

+ +

Take a look at this example where we have two paragraphs, one of which has an ID.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/important.html", '100%', 700)}} 

+ +

Let's walk through this to see what's happening — try removing some of the properties to see what happens if you are finding it hard to understand:

+ +
    +
  1. You'll see that the third rule's {{cssxref("color")}} and {{cssxref("padding")}} values have been applied, but the {{cssxref("background-color")}} hasn't. Why? Really all three should surely apply, because rules later in the source order generally override earlier rules.
  2. +
  3. However, The rules above it win, because class selectors have higher specificity than element selectors.
  4. +
  5. Both elements have a {{htmlattrxref("class")}} of better, but the 2nd one has an {{htmlattrxref("id")}} of winning too. Since IDs have an even higher specificity than classes (you can only have one element with each unique ID on a page, but many elements with the same class — ID selectors are very specific in what they target), the red background color and the 1 pixel black border should both be applied to the 2nd element, with the first element getting the gray background color, and no border, as specified by the class.
  6. +
  7. The 2nd element does get the red background color, but no border. Why? Because of the !important declaration in the second rule — including this after border: none means that this declaration will win over the border value in the previous rule, even though the ID has higher specificity.
  8. +
+ +
+

Note: The only way to override this !important declaration would be to include another !important declaration on a declaration with the same specificity later in the source order, or one with a higher specificity.

+
+ +

It is useful to know that !important exists so that you know what it is when you come across it in other people's code. However, we strongly recommend that you never use it unless you absolutely have to. !important changes the way the cascade normally works, so it can make debugging CSS problems really hard to work out, especially in a large stylesheet.

+ +

One situation in which you may have to use it is when you are working on a CMS where you can't edit the core CSS modules, and you really want to override a style that can't be overridden in any other way. But really, don't use it if you can avoid it.

+ +

The effect of CSS location

+ +

Finally, it is also useful to note that the importance of a CSS declaration depends on what stylesheet it is specified in — it is possible for users to set custom stylesheets to override the developer's styles, for example the user might be visually impaired, and want to set the font size on all web pages they visit to be double the normal size to allow for easier reading.

+ +

To summarize

+ +

Conflicting declarations will be applied in the following order, with later ones overriding earlier ones:

+ +
    +
  1. Declarations in user agent style sheets (e.g. the browser's default styles, used when no other styling is set).
  2. +
  3. Normal declarations in user style sheets (custom styles set by a user).
  4. +
  5. Normal declarations in author style sheets (these are the styles set by us, the web developers).
  6. +
  7. Important declarations in author style sheets
  8. +
  9. Important declarations in user style sheets
  10. +
+ +

It makes sense for web developers' stylesheets to override user stylesheets, so the design can be kept as intended, but sometimes users have good reasons to override web developer styles, as mentioned above — this can be achieved by using !important in their rules.

+ +

Active learning: playing with the cascade

+ +

In this active learning, we'd like you to experiment with writing a single new rule that will override the color and background color that we've applied to the links by default. Can you use one of the special values we looked at in the {{anch("Controlling inheritance")}} section to write a declaration in a new rule that will reset the background color back to white, without using an actual color vff

+ +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, take a look at the solution here.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/task.html", '100%', 700)}}

+ +

What's next

+ +

If you understood most of this article, then well done — you've started getting familiar with the fundamental mechanics of CSS. Next up, we'll look at selectors in detail.

+ +

If you didn't fully understand the cascade, specificity, and inheritance, then don't worry! This is definitely the most complicated thing we've covered so far in the course, and is something that even professional web developers sometimes find tricky. We'd advise that you return to this article a few times as you continue through the course, and keep thinking about it.

+ +

Refer back here if you start to come across strange issues with styles not applying as expected. It could be a specificity issue.

+ +

{{NextMenu("Learn/CSS/Building_blocks/Selectors", "Learn/CSS/Building_blocks")}}

+ +

In this module

+ +
    +
  1. Cascade and inheritance
  2. +
  3. CSS selectors + +
  4. +
  5. The box model
  6. +
  7. Backgrounds and borders
  8. +
  9. Handling different text directions
  10. +
  11. Overflowing content
  12. +
  13. Values and units
  14. +
  15. Sizing items in CSS
  16. +
  17. Images, media, and form elements
  18. +
  19. Styling tables
  20. +
  21. Debugging CSS
  22. +
  23. Organizing your CSS
  24. +
diff --git a/files/uk/learn/css/building_blocks/index.html b/files/uk/learn/css/building_blocks/index.html new file mode 100644 index 0000000000..39839cd182 --- /dev/null +++ b/files/uk/learn/css/building_blocks/index.html @@ -0,0 +1,90 @@ +--- +title: Будівельні блоки CSS +slug: Learn/CSS/Building_blocks +tags: + - Beginner + - CSS + - Learn + - NeedsTranslation + - TopicStub + - building blocks +translation_of: Learn/CSS/Building_blocks +--- +
{{LearnSidebar}}
+ +

This module carries on where CSS first steps left off — now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. This module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more.

+ +

The aim here is to provide you with a toolkit for writing competent CSS and help you understand all the essential theory, before moving on to more specific disciplines like text styling and CSS layout.

+ +

Prerequisites

+ +

Before starting this module, you should have:

+ +
    +
  1. Basic familiarity with using computers, and using the Web passively (i.e. just looking at it, consuming the content.)
  2. +
  3. A basic work environment set up as detailed in Installing basic software, and an understanding of how to create and manage files, as detailed in Dealing with files.
  4. +
  5. Basic familiarity with HTML, as discussed in the Introduction to HTML module.
  6. +
  7. An understanding of the basics of CSS, as discussed in the CSS first steps module.
  8. +
+ +
+

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

+
+ +

Guides

+ +

This module contains the following articles, which cover the most essential parts of the CSS language. Along the way you'll come across plenty of exercises to allow you to test your understanding.

+ +
+
Cascade and inheritance
+
The aim of this lesson is to develop your understanding of some of the most fundamental concepts of CSS — the cascade, specificity, and inheritance — which control how CSS is applied to HTML and how conflicts are resolved.
+
CSS selectors
+
There are a wide variety of CSS selectors available, allowing for fine-grained precision when selecting elements to style. In this article and its sub-articles we'll run through the different types in great detail, seeing how they work. The sub-articles are as follows: + +
+
The box model
+
Everything in CSS has a box around it, and understanding these boxes is key to being able to create layouts with CSS, or to align items with other items. In this lesson we will take a proper look at the CSS Box Model, in order that you can move onto more complex layout tasks with an understanding of how it works and the terminology that relates to it.
+
Backgrounds and borders
+
In this lesson we will take a look at some of the creative things you can do with CSS backgrounds and borders. From adding gradients, background images, and rounded corners, backgrounds and borders are the answer to a lot of styling questions in CSS.
+
Handling different text directions
+
In recent years, CSS has evolved in order to better support different directionality of content, including right-to-left but also top-to-bottom content (such as Japanese) — these different directionalities are called writing modes. As you progress in your study and begin to work with layout, an understanding of writing modes will be very helpful to you, therefore we will introduce them in this article.
+
Overflowing content
+
In this lesson we will look at another important concept in CSS — overflow. Overflow is what happens when there is too much content to be contained comfortably inside a box. In this guide you will learn what it is and how to manage it.
+
CSS values and units
+
Every property used in CSS has a value or set of values that are allowed for that property. In this lesson we will take a look at some of the most common values and units in use.
+
Sizing items in CSS
+
In the various lessons so far you have come across a number of ways to size items on a web page using CSS. Understanding how big the different features in your design will be is important, and in this lesson we will summarize the various ways elements get a size via CSS and define a few terms around sizing that will help you in the future.
+
Images, media, and form elements
+
In this lesson we will take a look at how certain special elements are treated in CSS. Images, other media, and form elements behave a little differently in terms of your ability to style them with CSS than regular boxes. Understanding what is and isn't possible can save some frustration, and this lesson will highlight some of the main things that you need to know.
+
Styling tables
+
Styling an HTML table isn't the most glamorous job in the world, but sometimes we all have to do it. This article provides a guide to making HTML tables look good, with some specific table styling techniques highlighted.
+
Debugging CSS
+
Sometimes when writing CSS you will encounter an issue where your CSS doesn't seem to be doing what you expect. This article will give you guidance on how to go about debugging a CSS problem, and show you how the DevTools included in all modern browsers can help you find out what is going on.
+
Organizing your CSS
+
As you start to work on larger stylesheets and big projects you will discover that maintaining a huge CSS file can be challenging. In this article we will take a brief look at some best practices for writing your CSS to make it easily maintainable, and some of the solutions you will find in use by others to help improve maintainability.
+
+ +

Assessments

+ +

Want to test your CSS skills? The following assessments will test your understanding of the CSS covered in the guides above.

+ +
+
Fundamental CSS comprehension
+
This assessment tests your understanding of basic syntax, selectors, specificity, box model, and more.
+
Creating fancy letterheaded paper
+
If you want to make the right impression, writing a letter on nice letterheaded paper can be a really good start. In this assessment, we'll challenge you to create an online template to achieve such a look.
+
A cool looking box
+
Here you'll get some practice in using background and border styling to create an eye-catching box.
+
+ +

See also

+ +
+
Advanced styling effects
+
This article acts as a box of tricks, providing an introduction to some interesting advanced styling features such as box shadows, blend modes, and filters.
+
diff --git "a/files/uk/learn/css/css_\321\200\320\276\320\267\320\274\321\226\321\202\320\272\320\260/index.html" "b/files/uk/learn/css/css_\321\200\320\276\320\267\320\274\321\226\321\202\320\272\320\260/index.html" new file mode 100644 index 0000000000..14ce8f9c63 --- /dev/null +++ "b/files/uk/learn/css/css_\321\200\320\276\320\267\320\274\321\226\321\202\320\272\320\260/index.html" @@ -0,0 +1,70 @@ +--- +title: CSS розмітка +slug: Learn/CSS/CSS_розмітка +translation_of: Learn/CSS/CSS_layout +--- +
{{LearnSidebar}}
+ +

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 we can now dive deep into CSS layout, looking at different display settings, modern layout tools like flexbox, CSS grid, and positioning, and some of the legacy techniques you might still want to know about.

+ +
+

Looking to become a front-end web developer?

+ +

We have put together a course that includes all the essential information you need to work towards your goal.

+ +

Get started

+
+ +

Prerequisites

+ +

Before starting this module, you should already:

+ +
    +
  1. Have basic familiarity with HTML, as discussed in the Introduction to HTML module.
  2. +
  3. Be comfortable with CSS fundamentals, as discussed in Introduction to CSS.
  4. +
  5. Understand how to style boxes.
  6. +
+ +
+

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

+
+ +

Guides

+ +

These articles will provide instruction on the fundamental layout tools and techniques available in CSS. At the end of the lessons is an assessment to help you check your understanding of layout methods, by laying out a webpage.

+ +
+
Introduction to CSS layout
+
This article will recap some of the CSS layout features we've already touched upon in previous modules — such as different {{cssxref("display")}} values — and introduce some of the concepts we'll be covering throughout this module.
+
Normal flow
+
Elements on webpages lay themselves out according to normal flow - until we do something to change that. This article explains the basics of normal flow as a grounding for learning how to change it.
+
Flexbox
+
Flexbox is a one-dimensional layout method for laying out items in rows or columns. Items flex to fill additional space and shrink to fit into smaller spaces. This article explains all the fundamentals. After studying this guide you can test your flexbox skills to check your understanding before moving on.
+
Grids
+
CSS Grid Layout is a two-dimensional layout system for the web. It lets you lay content out in rows and columns, and has many features that make building complex layouts straightforward. This article will give you all you need to know to get started with page layout, then test your grid skills before moving on.
+
Floats
+
Originally for floating images inside blocks of text, the {{cssxref("float")}} property became one of the most commonly used tools for creating multiple column layouts on webpages. With the advent of Flexbox and Grid it has now returned to its original purpose, as this article explains.
+
Positioning
+
Positioning allows you to take elements out of the normal document layout flow, and make them behave differently, for example sitting on top of one another, or always remaining in the same place inside the browser viewport. This article explains the different {{cssxref("position")}} values, and how to use them.
+
Multiple-column layout
+
The multiple-column layout specification gives you a method of laying content out in columns, as you might see in a newspaper. This article explains how to use this feature.
+
Responsive design
+
As more diverse screen sizes have appeared on web-enabled devices, the concept of responsive web design (RWD) has appeared: a set of practices that allows web pages to alter their layout and appearance to suit different screen widths, resolutions, etc. It is an idea that changed the way we design for a multi-device web, and in this article we'll help you understand the main techniques you need to know to master it.
+
Beginner's guide to media queries
+
The CSS Media Query gives you a way to apply CSS only when the browser and device environment matches a rule that you specify, for example "viewport is wider than 480 pixels". Media queries are a key part of responsive web design, as they allow you to create different layouts depending on the size of the viewport, but they can also be used to detect other things about the environment your site is running on, for example whether the user is using a touchscreen rather than a mouse. In this lesson you will first learn about the syntax used in media queries, and then move on to use them in a worked example showing how a simple design might be made responsive.
+
Legacy layout methods
+
Grid systems are a very common feature used in CSS layouts, and before CSS Grid Layout they tended to be implemented using floats or other layout features. You imagine your layout as a set number of columns (e.g. 4, 6, or 12), and then fit your content columns inside these imaginary columns. In this article we'll explore how these older methods work, in order that you understand how they were used if you work on an older project.
+
Supporting older browsers
+
+

In this module we recommend using Flexbox and Grid as the main layout methods for your designs. However there will be visitors to your site who use older browsers, or browsers which do not support the methods you have used. This will always be the case on the web — as new features are developed, different browsers will prioritise different things. This article explains how to use modern web techniques without locking out users of older technology.

+
+
Assessment: Fundamental layout comprehension
+
An assessment to test your knowledge of different layout methods by laying out a webpage.
+
+ +

See also

+ +
+
Practical positioning examples
+
This article shows how to build some real world examples to illustrate what kinds of things you can do with positioning.
+
diff --git a/files/uk/learn/css/first_steps/index.html b/files/uk/learn/css/first_steps/index.html new file mode 100644 index 0000000000..30aa7f0214 --- /dev/null +++ b/files/uk/learn/css/first_steps/index.html @@ -0,0 +1,53 @@ +--- +title: Перші кроки у CSS +slug: Learn/CSS/First_steps +tags: + - CSS + - Модулі + - Навчання + - Перші кроки + - Посадка + - Початок +translation_of: Learn/CSS/First_steps +--- +
{{LearnSidebar}}
+ +

CSS (Cascading Style Sheets) використовується для стилювання та розміщення веб-сторінок - наприклад, для зміни шрифту, кольору, розміру та інтервалу вашого вмісту, розділення його на кілька стовпців або додавання анімації та інших декоративних функцій. Цей модуль забезпечує легкий початок вашого шляху до оволодіння CSS основами того, як він працює, як виглядає синтаксис і як ви можете почати використовувати його для додавання стилю до HTML.

+ +

Передумови

+ +

Перш ніж запустити цей модуль, ви повинні мати:

+ +
    +
  1. Основне ознайомлення з використанням комп'ютерів та пасивним використанням Інтернету (тобто перегляд його, споживання вмісту.)
  2. +
  3. Основне робоче середовище, створене, як детально описано в Встановлення базового програмного забезпечення, і розуміння того, як створювати файли та керувати ними, як детально описано у розділі «Робота з файлами».
    + Основне ознайомлення з HTML, як обговорювалося в модулі Вступ до HTML .
  4. +
+ +
+

Примітка. Якщо ви працюєте на комп'ютері / планшеті / іншому пристрої, де у вас немає можливості створювати власні файли, ви можете спробувати (більшість) прикладів коду в онлайн-програмі кодування, наприклад JSBin або Thimble.

+
+ +

Посібники

+ +

Цей модуль містить наступні статті, які допоможуть вам ознайомитись з усією базовою теорією CSS та нададуть вам можливість перевірити деякі навички.

+ +
+
Що таке CSS?
+
{{Glossary("CSS")}} (Каскадні таблиці стилів) дозволяє створювати чудові веб-сторінки, але як це працює під кришкою? Ця стаття пояснює, що таке CSS, на прикладі простого синтаксису, а також висвітлює деякі ключові терміни про мову.
+
Початок роботи з CSS
+
У цій статті ми візьмемо простий HTML-документ і застосуємо до нього CSS, вивчивши деякі практичні речі щодо мови.
+
Яка структура CSS
+
Тепер, коли ви маєте уявлення про те, що таке CSS та основи його використання, саме час трохи заглибитись у структуру самої мови. Ми вже зустріли багато обговорених тут концепцій; ви можете повернутися до цього, щоб скласти резюме, якщо ви знайдете якісь пізніші поняття заплутані.
+
Як працює CSS
+
Ми вивчили основи CSS, для чого він потрібен та як писати прості таблиці стилів. У цьому уроці ми розглянемо, як браузер приймає CSS та HTML і перетворює їх у веб-сторінку.
+
Використовуючи свої нові знання
+
З того, що ви вивчили на останніх кількох уроках, ви повинні виявити, що ви можете форматувати прості текстові документи за допомогою CSS, щоб додати до них свій власний стиль. Ця стаття дає вам шанс це зробити.
+
+ +

Дивіться також

+ +
+
Проміжна веб-грамотність 1: Вступ до CSS
+
Чудовий курс від Mozilla foundation, який вивчає та перевіряє багато навичок, про які говорилося в модулі «Вступ до CSS». Дізнайтеся про стилізацію HTML-елементів на веб-сторінці, селекторах CSS, атрибутах та значеннях.
+
diff --git "a/files/uk/learn/css/first_steps/\321\211\320\276_\321\202\320\260\320\272\320\265_css/index.html" "b/files/uk/learn/css/first_steps/\321\211\320\276_\321\202\320\260\320\272\320\265_css/index.html" new file mode 100644 index 0000000000..a1ee6d30ea --- /dev/null +++ "b/files/uk/learn/css/first_steps/\321\211\320\276_\321\202\320\260\320\272\320\265_css/index.html" @@ -0,0 +1,129 @@ +--- +title: Що таке CSS? +slug: Learn/CSS/First_steps/Що_таке_CSS +tags: + - CSS + - Вступ до CSS + - Модулі + - Навчання + - Синтаксис + - Специфікація + - новачок +translation_of: Learn/CSS/First_steps/What_is_CSS +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/CSS/First_steps/Getting_started", "Learn/CSS/First_steps")}}
+ +

{{Glossary("CSS")}} (Каскадні таблиці стилів) дозволяє створювати чудові веб-сторінки, але як це працює під кришкою? Ця стаття пояснює, що таке CSS, на прикладі простого синтаксису, а також висвітлює деякі ключові терміни про мову.

+ + + + + + + + + + + + +
Передумови:Основна комп'ютерна грамотність, встановлено базове програмне забезпечення, основні знання про робота з файлами, та HTML базовий (вивчыть Вступ до HTML)
+

Мета:

+ + +
To learn what CSS is.
+ +

У вступі до модуля HTML ми розглянули, що таке HTML, і як він використовується для розмітки документів. Ці документи можна прочитати у веб-браузері. Заголовки виглядатимуть більше, ніж звичайний текст, абзаци перериваються на новий рядок і мають пробіл між ними. Посилання кольорові та підкреслені, щоб відрізняти їх від решти тексту. Що ви бачите, це стилі браузера за замовчуванням - дуже основні стилі, які браузер застосовує до HTML, щоб переконатися, що він буде в основному читабельним, навіть якщо автор сторінки не вказав явного стилю.

+ +

The default styles used by a browser

+ +

Однак Інтернет був би нудним місцем, якби всі веб-сайти виглядали так. За допомогою CSS ви можете точно контролювати, як виглядають елементи HTML у браузері, представляючи свою розмітку, використовуючи будь-який дизайн, який вам подобається.

+ +

Для чого CSS?

+ +

Як ми вже згадували раніше, CSS - це мова, яка визначає, як документи подаються користувачам - як вони оформляються, викладаються тощо.A document is usually a text file structured using a markup language — {{Glossary("HTML")}} is the most common markup language, but you may also come across other markup languages such as {{Glossary("SVG")}} or {{Glossary("XML")}}.

+ +

Подання документа користувачеві означає перетворення його в форму, яку можна використовувати вашій аудиторії. {{Глосарій ("браузер", "Браузери")}}, як {{Глосарій ("Mozilla Firefox", "Firefox")}}, {{Глосарій ("Google Chrome", "Chrome")}} або { {Глосарій ("Microsoft Edge", "Edge")}} призначений для візуального представлення документів, наприклад, на екрані комп'ютера, проекторі чи принтері.

+ +
+

Примітка: Іноді браузер називається {{Glossary ("Агент користувача", "Агент користувача")}}, що в основному означає комп'ютерну програму, яка представляє людину всередині комп'ютерної системи. Браузери - це основний тип агента користувача, про який ми думаємо, коли говоримо про CSS, однак, це не єдиний. Доступні й інші користувацькі агенти - такі, які перетворюють документи HTML та CSS у PDF-файли для друку.

+
+ +

CSS можна використовувати для дуже базового стилю тексту документа - наприклад, для зміни кольору та розміру заголовків та посилань. Його можна використовувати для створення макета - наприклад, перетворення одного стовпця тексту в макет з основною областю вмісту та бічною панеллю для пов'язаної інформації. Його навіть можна використовувати для таких ефектів, як анімація. Перегляньте посилання в цьому пункті для конкретних прикладів.

+ +

Синтаксис CSS

+ +

CSS є мовою на основі правил - ви визначаєте правила, що визначають групи стилів, які слід застосовувати до певних елементів або груп елементів на вашій веб-сторінці. Наприклад, "Я хочу, щоб основний заголовок на моїй сторінці відображався як великий червоний текст".

+ +

У наведеному нижче коді показано дуже просте правило CSS, яке дозволило б досягти описаного вище стилю:

+ +
h1 {
+    color: red;
+    font-size: 5em;
+}
+ +

Правило відкривається за допомогою {{Глосарій ("CSS Selector", "Selector")}}. Це вибирає HTML-елемент, який ми будемо стилювати. У цьому випадку ми створюємо заголовки рівня першого рівня ({{htmlelement ("h1")}}).

+ +

Потім у нас є набір фігурних брекетів { }. Всередині буде одна чи кілька декларацій, які мають форму властивостей і значень пар. Кожна пара визначає властивість елемента (-ів), який ми вибираємо, а потім значення, яке ми хотіли б надати властивості.

+ +

Перед двокрапкою ми маємо властивість, а після двокрапки - значення. CSS {{Глосарій ("властивість / CSS", "властивості")}} мають різні допустимі значення, залежно від того, яке властивість задано. У нашому прикладі ми маємо властивість кольору, яка може приймати різні значення кольорів. У нас також є  font-size влыстивість. Ця властивість може приймати різні розмір одиниць.

+ +

Таблиця стилів CSS міститиме багато таких правил, написаних один за одним.

+ +
h1 {
+    color: red;
+    font-size: 5em;
+}
+
+p {
+    color: black;
+}
+ +

Ви побачите, що швидко засвоюєте деякі значення, тоді як інші вам потрібно буде шукати. Окремі сторінки властивостей на MDN дають вам швидкий спосіб пошуку властивостей та їх значень, коли ви забудете, або хочете знати, що ще можна використовувати як значення.

+ +
+

Примітка: Ви можете знайти посилання на всі сторінки властивостей CSS (разом з іншими функціями CSS), перелічені в розділі MDN CSS reference. Крім того, вам слід звикнути до пошуку "mdn css-feature-name" у своїй улюбленій пошуковій системі, коли вам потрібно дізнатися більше інформації про функцію CSS. Наприклад, спробуйте шукати "mdn color" і "mdn font-size"!

+
+ +

CSS Модулі

+ +

Оскільки існує так багато речей, які можна стилювати за допомогою CSS, мова розбивається на модулі. Ви побачите посилання на ці модулі під час вивчення MDN та багато сторінок документації, організованих навколо певного модуля. Наприклад, ви можете ознайомитися з посиланням на MDN на модуль "Фони та межі", щоб дізнатися, яке його призначення, а також які різні властивості та інші особливості він містить. Ви також знайдете посилання на специфікацію CSS, яка визначає технологію (див. Нижче).

+ +

На цьому етапі вам не потрібно занадто хвилюватися про структурування CSS, однак це може полегшити пошук інформації, якщо, наприклад, ви знаєте, що певне властивість, можливо, знайдеться серед інших подібних речей і є тому, ймовірно, в тій же специфікації.

+ +

Для конкретного прикладу повернемося до модуля «Фони та межі» - ви можете подумати, що це має логічний сенс для background-color та border-color властивості, що визначаються в цьому модулі. І ти будеш прав.

+ +

CSS специфікація

+ +

Усі технології веб-стандартів (HTML, CSS, JavaScript тощо) визначені в гігантських документах, що називаються специфікаціями (або просто "специфікаціями"), які публікуються організаціями зі стандартів (наприклад, {{глосарій ("W3C")}}, {{глосарій ("WHATWG")}}, {{глосарій ("ECMA")}} або {{глосарій ("Хронос")}}) і точно визначте, як повинні поводитися ці технології.

+ +

CSS не відрізняється - він розроблений групою в межах W3C під назвою CSS Робоча група. Ця група складається з представників постачальників браузерів та інших компаній, які мають інтерес до CSS. Є й інші люди, відомі як запрошені експерти, які виступають незалежними голосами; вони не пов'язані з організацією-членом.

+ +

Робоча група CSS розробляє або уточнює нові функції CSS. Іноді тому, що конкретний браузер зацікавлений у певних можливостях, інший раз через те, що веб-дизайнери та розробники просять про функцію, а іноді тому, що сама Робоча група визначила вимогу. CSS постійно розвивається, доступні нові функції. Однак, головне в CSS - це те, що всі дуже наполегливо працюють, щоб ніколи не змінювати речі таким чином, щоб зламати старі веб-сайти. Веб-сайт, побудований у 2000 році, використовуючи доступний тоді обмежений CSS, і сьогодні повинен використовуватись у веб-переглядачі!

+ +

Як новачок у CSS, ймовірно, ви знайдете специфікації CSS непосильними - вони призначені для інженерів використовувати для впровадження підтримки функцій в агентах користувачів, а не для веб-розробників, які читають, щоб зрозуміти CSS. Багато досвідчених розробників швидше звертаються до документації MDN або інших навчальних посібників. Однак варто знати, що вони існують, розуміючи взаємозв'язок між CSS, який ви використовуєте, підтримкою браузера (див. Нижче) та специфікаціями.

+ +

Підтримка браузера

+ +

Після того, як CSS буде визначено, він може бути корисним для нас лише при розробці веб-сторінок, якщо один або кілька браузерів реалізували його. Це означає, що код написаний, щоб перетворити інструкцію з нашого CSS-файлу на щось, що може бути виведене на екран. Ми розглянемо цей процес докладніше на уроці Як працює CSS. Всі браузери незвично одночасно реалізовувати функцію, тому зазвичай існує розрив, де можна використовувати частину CSS в деяких браузерах, а не в інших. З цієї причини корисність перевірити стан реалізації. На кожній сторінці властивостей на MDN ви можете побачити статус об’єкта, який вас цікавить, тож ви можете сказати, чи зможете ви ним користуватися на веб-сайті.

+ +

Далі йде таблиця даних compat для властивості CSS font-family .

+ +

{{Compat("css.properties.font-family")}}

+ +

Що далі

+ +

Тепер, коли ви зрозуміли, що таке CSS, перейдемо до Початок роботи з CSS де ви можете почати самостійно писати деякі CSS.

+ +

{{NextMenu("Learn/CSS/First_steps/Getting_started", "Learn/CSS/First_steps")}}

+ +

In this module

+ +
    +
  1. Що таке CSS?
  2. +
  3. Початок роботи з CSS
  4. +
  5. Як структурується CSS
  6. +
  7. Як працює CSS
  8. +
  9. Використовуйте свої нові знання
  10. +
diff --git a/files/uk/learn/css/index.html b/files/uk/learn/css/index.html new file mode 100644 index 0000000000..c4fd0dedfc --- /dev/null +++ b/files/uk/learn/css/index.html @@ -0,0 +1,68 @@ +--- +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 — або {{glossary("CSS")}} — це перша технологія, яку слід почати вивчати після {{glossary("HTML")}}. Хоча HTML використовується для визначення структури та семантики вашого вмісту, CSS використовується для його стилізації та викладки. Наприклад, ви можете використовувати CSS, щоб змінити шрифт, колір, розмір та інтервал вашого вмісту, розділити його на кілька стовпців або додати анімацію та інші декоративні функції.

+ +

Шляхи навчання

+ +

Ви повинні вивчити основи HTML, перш ніж спробувати будь-який CSS. Рекомендуємо спочатку опрацювати наш Вступ до модуля HTML. У цьому модулі ви дізнаєтесь про:

+ + + +

Після того, як ви зрозумієте основи HTML, рекомендуємо вам вивчити HTML і CSS одночасно, рухаючись вперед і назад між двома темами. Це тому, що HTML набагато цікавіше і набагато цікавіше вчитися, коли ви застосовуєте CSS, і ви не можете навчитися CSS, не знаючи HTML.

+ +

Перш ніж розпочати цю тему, ви також повинні ознайомитись з використанням комп’ютерів та пасивним використанням Інтернету (тобто, просто переглянувши його, споживаючи вміст). Ви повинні мати базове робоче середовище, налаштоване як детально
+ в Встановлення базового програмного забезпечення та зрозуміти, як створити та керувати файлами, як це детально описано в Робота з файлами — обидва вони є нашими частинами Початок роботи з Інтернетом повний модуль для початківців.

+ +

Рекомендується опрацювати Початок роботи з Інтернетом перш ніж перейти до цієї теми. Однак це не зовсім необхідне, оскільки значна частина того, що розглядається в статті про основи CSS, також висвітлено в нашому модулі Вступ до CSS, хоча і набагато детальніше.

+ +

Модулі

+ +

Ця тема містить наступні модулі в запропонованому порядку для роботи над ними. Ви обов'язково повинні почати з першого.

+ +
+
Вступ до CSS
+
Цей модуль розпочинає роботу з основами роботи CSS, включаючи використання селекторів та властивостей; написання правил CSS; застосування CSS до HTML; визначення довжини, кольору та інших одиниць у CSS; контроль каскаду та успадкування; розуміння основ моделі коробки; та налагодження CSS.
+
Стилізація тексту
+
Тут ми розглядаємо основи стилізації тексту, включаючи встановлення шрифту, жирності та курсиву; інтервал між рядками та літерами; і скидання тіней та інших функцій тексту. Ми округляємо модуль, дивлячись на застосування спеціальних шрифтів до вашої сторінки та стилістичні списки та посилання.
+
Стильні коробки
+
Далі ми розглянемо вікна стилізації, один із основних кроків щодо створення веб-сторінки. У цьому модулі ми резюмуємо модель коробки, потім переглядаємо керування макетами коробки, встановлюючи накладки, межі та поля, встановлюючи власні кольори фону, зображення та фантазійні функції, такі як тіні для крапель та фільтри на коробках.
+
CSS макет
+
На даний момент ми вже розглядали основи CSS, як стилювати текст та як стилізувати та маніпулювати полями, у яких розміщений ваш вміст. Тепер прийшов час розглянути, як розташувати вікна в потрібному місці по відношенню до вікна перегляду та один до одного. Ми забезпечили необхідні передумови, тому тепер ми можемо зануритися в глиб CSS-макета, переглядаючи різні налаштування дисплея, сучасні інструменти компонування, такі як flexbox, CSS-сітка та позиціонування, а також деякі застарілі методи, про які ви все ще можете знати.
+
Чуйний дизайн (TBD)
+
Завдяки такій кількості різних типів пристроїв, які сьогодні можуть переглядати Інтернет, чуйний веб-дизайн (RWD) стала основним навиком веб-розробки. Цей модуль буде охоплювати основні принципи та інструменти роботи RWD; поясніть, як застосувати різні CSS до документа залежно від функцій пристрою, таких як ширина екрана, орієнтація та роздільна здатність; та вивчити технології, доступні для обслуговування різних відео та зображень залежно від таких функцій.
+
+ +

Вирішення поширених проблем CSS

+ +

Використовуйте CSS для вирішення загальних проблем надає посилання на розділи вмісту, що пояснюють, як використовувати CSS для вирішення дуже поширених проблем під час створення веб-сторінки.

+ +

Ви спочатку застосовуватимете кольори до елементів HTML та їх фонів; зміни розміру, форми та положення елементів; і додавати та визначати межі елементів. Але не так багато, що ти не зможеш зробити, коли добре зрозумієш навіть основи CSS. Одна з найкращих речей щодо вивчення CSS - це те, що, як тільки ви знаєте основи, зазвичай у вас є гарне відчуття того, що можна, а чого не можна зробити, навіть якщо ви ще не знаєте, як це зробити!

+ +

Дивіться також

+ +
+
CSS в MDN
+
Основна точка входу для CSS-документації на MDN, де ви знайдете детальну довідкову документацію щодо всіх функцій мови CSS. Хочете знати всі цінності, які може спричинити властивість? Це гарне місце.
+
diff --git a/files/uk/learn/css/styling_text/index.html b/files/uk/learn/css/styling_text/index.html new file mode 100644 index 0000000000..46c343f406 --- /dev/null +++ b/files/uk/learn/css/styling_text/index.html @@ -0,0 +1,57 @@ +--- +title: Стилізація тексту +slug: Learn/CSS/Styling_text +tags: + - Beginner + - CSS + - CodingScripting + - Fonts + - Landing + - Links + - Module + - NeedsTranslation + - Text + - TopicStub + - font + - letter + - line + - lists + - shadow + - web fonts +translation_of: Learn/CSS/Styling_text +--- +
{{LearnSidebar}}
+ +

With the basics of the CSS language covered, the next CSS topic for you to concentrate on is styling text — one of the most common things you'll do with CSS. Here we look at text styling fundamentals, including setting font, boldness, italics, line and letter spacing, 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.

+ +

Prerequisites

+ +

Before starting this module, you should already have basic familiarity with HTML, as discussed in the Introduction to HTML module, and be comfortable with CSS fundamentals, as discussed in Introduction to CSS.

+ +
+

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

+
+ +

Guides

+ +

This module contains the following articles, which will teach you all of the essentials behind styling HTML text content.

+ +
+
Fundamental text and font styling
+
In this article we go through all the basics of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.
+
Styling lists
+
Lists behave like any other text for the most part, but there are some CSS properties specific to lists that you need to know about, and some best practices to consider. This article explains all.
+
Styling links
+
When styling links, it is important to understand how to make use of pseudo-classes to style link states effectively, and how to style links for use in common varied interface features such as navigation menus and tabs. We'll look at all these topics in this article.
+
Web fonts
+
Here we will explore web fonts in detail — these allow you to download custom fonts along with your web page, to allow for more varied, custom text styling.
+
+ +

Assessments

+ +

The following assessments will test your understanding of the text styling techniques covered in the guides above.

+ +
+
Typesetting a community school homepage
+
In this assessment we'll test your understanding of styling text by getting you to style the text for a community school's homepage.
+
diff --git "a/files/uk/learn/css/styling_text/\321\201\321\202\320\270\320\273\321\226_\321\201\320\277\320\270\321\201\320\272\321\226\320\262/index.html" "b/files/uk/learn/css/styling_text/\321\201\321\202\320\270\320\273\321\226_\321\201\320\277\320\270\321\201\320\272\321\226\320\262/index.html" new file mode 100644 index 0000000000..da8f62ab84 --- /dev/null +++ "b/files/uk/learn/css/styling_text/\321\201\321\202\320\270\320\273\321\226_\321\201\320\277\320\270\321\201\320\272\321\226\320\262/index.html" @@ -0,0 +1,394 @@ +--- +title: Стилі списків +slug: Learn/CSS/Styling_text/Стилі_списків +tags: + - CSS + - Початківець + - Спискі + - Стаття + - Стилі + - Текст +translation_of: Learn/CSS/Styling_text/Styling_lists +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/CSS/Styling_text/Fundamentals", "Learn/CSS/Styling_text/Styling_links", "Learn/CSS/Styling_text")}}
+ +

Здебільшого Списки ведуть себе як будь-який інший текст, але є деякі властивості CSS, специфічні для списків, які вам потрібно знати, а також деякі найкращі способи розгляду. Ця стаття пояснює все.

+ + + + + + + + + + + + +
Передумови:Основна комп'ютерна грамотність, основи HTML (вивчення Вступу до HTML), основи CSS (вивчення Вступу до CSS), Основи тексту та шрифтів CSS.
Мета:Познайомитися з найкращими практиками та властивостями, пов'язаними зі списками стилів.
+ +

Простий приклад списку

+ +

Почнемо з того, давайте подивимося на приклад простого списку. У цій статті ми розглянемо списки неупорядкованих, упорядкованих та опису - у всіх є стилістичні функції, схожі на деякі,  що є характерними для їхнього типу списку. Неперевершений приклад доступний на Github ( також перевірте цей код)

+ +

Приклад HTML для нашого списку виглядає так:

+ +
<h2>Shopping (unordered) list</h2>
+
+<p>Paragraph for reference, paragraph for reference, paragraph for reference,
+paragraph for reference, paragraph for reference, paragraph for reference.</p>
+
+<ul>
+  <li>Humous</li>
+  <li>Pitta</li>
+  <li>Green salad</li>
+  <li>Halloumi</li>
+</ul>
+
+<h2>Recipe (ordered) list</h2>
+
+<p>Paragraph for reference, paragraph for reference, paragraph for reference,
+paragraph for reference, paragraph for reference, paragraph for reference.</p>
+
+<ol>
+  <li>Toast pitta, leave to cool, then slice down the edge.</li>
+  <li>Fry the halloumi in a shallow, non-stick pan, until browned on both sides.</li>
+  <li>Wash and chop the salad.</li>
+  <li>Fill pitta with salad, humous, and fried halloumi.</li>
+</ol>
+
+<h2>Ingredient description list</h2>
+
+<p>Paragraph for reference, paragraph for reference, paragraph for reference,
+paragraph for reference, paragraph for reference, paragraph for reference.</p>
+
+<dl>
+  <dt>Humous</dt>
+  <dd>A thick dip/sauce generally made from chick peas blended with tahini, lemon juice, salt, garlic, and other ingredients.</dd>
+  <dt>Pitta</dt>
+  <dd>A soft, slightly leavened flatbread.</dd>
+  <dt>Halloumi</dt>
+  <dd>A semi-hard, unripened, brined cheese with a higher-than-usual melting point, usually made from goat/sheep milk.</dd>
+  <dt>Green salad</dt>
+  <dd>That green healthy stuff that many of us just use to garnish kebabs.</dd>
+</dl>
+ +

Якщо ви зараз перейдете до живого прикладу та вивчіть елементи списку, що використовують інструменти розробника браузера, ви помітите пара стилів по замовчуванням:

+ + + +

Обробка списку інтервалів

+ +

При складанні списків стилів потрібно настроїти свої стилі, щоб вони мали однакові вертикальні відстані як їх оточуючі елементи (такі як абзаци та зображення, іноді їх називають вертикальним ритмом) і однакові між собою горизонтальні відстані (ви можете побачити  закінчений стиль приклад  в Github, і знайти вихідний код також.)

+ +

CSS, який використовується для стилізації тексту та інтервалу, виглядає наступним чином:

+ +
/* General styles */
+
+html {
+  font-family: Helvetica, Arial, sans-serif;
+  font-size: 10px;
+}
+
+h2 {
+  font-size: 2rem;
+}
+
+ul,ol,dl,p {
+  font-size: 1.5rem;
+}
+
+li, p {
+  line-height: 1.5;
+}
+
+/* Description list styles */
+
+
+dd, dt {
+  line-height: 1.5;
+}
+
+dt {
+  font-weight: bold;
+}
+
+dd {
+  margin-bottom: 1.5rem;
+}
+ + + +

List-specific styles

+ +

Now we've looked at general spacing techniques for lists, let's explore some list-specific properties. There are three properties you should know about to start with, which can be set on {{htmlelement("ul")}} or {{htmlelement("ol")}} elements:

+ + + +

Bullet styles

+ +

As mentioned above, the {{cssxref("list-style-type")}} property allows you to set what type of bullet to use for the bullet points. In our example, we've set the ordered list to use uppercase roman numerals, with:

+ +
ol {
+  list-style-type: upper-roman;
+}
+ +

Це дає нам такий вигляд:

+ +

an ordered list with the bullet points set to appear outside the list item text.

+ +

You can find a lot more options by checking out the {{cssxref("list-style-type")}} reference page.

+ +

Bullet position

+ +

The {{cssxref("list-style-position")}} property sets whether the bullets appear inside the list items, or outside them before the start of each item. The default value is outside, which causes the bullets to sit outside the list items, as seen above.

+ +

If you set the value to inside, the bullets will sit inside the lines:

+ +
ol {
+  list-style-type: upper-roman;
+  list-style-position: inside;
+}
+ +

an ordered list with the bullet points set to appear inside the list item text.

+ +

Using a custom bullet image

+ +

The {{cssxref("list-style-image")}} property allows you to use a custom image for your bullet. The syntax is pretty simple:

+ +
ul {
+  list-style-image: url(star.svg);
+}
+ +

However, this property is a bit limited in terms of controlling the position, size, etc. of the bullets. You are better off using the {{cssxref("background")}} family of properties, which you'll learn a lot more about in the Styling boxes module. For now, here's a taster!

+ +

In our finished example, we have styled the unordered list like so (on top of what you've already seen above):

+ +
ul {
+  padding-left: 2rem;
+  list-style-type: none;
+}
+
+ul li {
+  padding-left: 2rem;
+  background-image: url(star.svg);
+  background-position: 0 0;
+  background-size: 1.6rem 1.6rem;
+  background-repeat: no-repeat;
+}
+ +

Here we've done the following:

+ + + +

This gives us the following result:

+ +

an unordered list with the bullet points set as little star images

+ +

list-style shorthand

+ +

The three properties mentioned above can all be set using a single shorthand property, {{cssxref("list-style")}}. For example, the following CSS:

+ +
ul {
+  list-style-type: square;
+  list-style-image: url(example.png);
+  list-style-position: inside;
+}
+ +

Could be replaced by this:

+ +
ul {
+  list-style: square url(example.png) inside;
+}
+ +

The values can be listed in any order, and you can use one, two or all three (the default values used for the properties that are not included are disc, none, and outside). If both a type and an image are specified, the type is used as a fallback if the image can't be loaded for some reason.

+ +

Controlling list counting

+ +

Sometimes you might want to count differently on an ordered list — e.g. starting from a number other than 1, or counting backwards, or counting in steps of more than 1. HTML and CSS have some tools to help you here.

+ +

start

+ +

The {{htmlattrxref("start","ol")}} attribute allows you to start the list counting from a number other than 1. The following example:

+ +
<ol start="4">
+  <li>Toast pitta, leave to cool, then slice down the edge.</li>
+  <li>Fry the halloumi in a shallow, non-stick pan, until browned on both sides.</li>
+  <li>Wash and chop the salad.</li>
+  <li>Fill pitta with salad, humous, and fried halloumi.</li>
+</ol>
+ +

Gives you this output:

+ +

{{ EmbedLiveSample('start', '100%', 150) }}

+ +

reversed

+ +

The {{htmlattrxref("reversed","ol")}} attribute will start the list counting down instead of up. The following example:

+ +
<ol start="4" reversed>
+  <li>Toast pitta, leave to cool, then slice down the edge.</li>
+  <li>Fry the halloumi in a shallow, non-stick pan, until browned on both sides.</li>
+  <li>Wash and chop the salad.</li>
+  <li>Fill pitta with salad, humous, and fried halloumi.</li>
+</ol>
+ +

Gives you this output:

+ +

{{ EmbedLiveSample('reversed', '100%', 150) }}

+ +

value

+ +

The {{htmlattrxref("value","ol")}} attribute allows you to set your list items to specific numerical values. The following example:

+ +
<ol>
+  <li value="2">Toast pitta, leave to cool, then slice down the edge.</li>
+  <li value="4">Fry the halloumi in a shallow, non-stick pan, until browned on both sides.</li>
+  <li value="6">Wash and chop the salad.</li>
+  <li value="8">Fill pitta with salad, humous, and fried halloumi.</li>
+</ol>
+ +

Gives you this output:

+ +

{{ EmbedLiveSample('value', '100%', 150) }}

+ +
+

Note: Even if you are using a non-number {{cssxref("list-style-type")}}, you still need to use the equivalent numerical values in the value attribute.

+
+ +

Active learning: Styling a nested list

+ +

In this active learning session, we want you to take what you've learned above and have a go at styling a nested list. We've provided you with the HTML, and we want you to:

+ +
    +
  1. Give the unordered list square bullets.
  2. +
  3. Give the unordered list items and the ordered list items a line height of 1.5 of their font-size.
  4. +
  5. Give the ordered list lower alphabetical bullets.
  6. +
  7. Feel free to play with the list example as much as you like, experimenting with bullet types, spacing, or whatever else you can find.
  8. +
+ +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see a potential answer.

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 800) }}

+ +

See also

+ +

CSS counters provide advanced tools for customizing list counting and styling, but they are quite complex. We recommend looking into these if you want to stretch yourself. See:

+ + + +

Summary

+ +

Lists are relatively easy to get the hang of styling once you know a few associated basic principles and specific properties. In the next article we'll get on to link styling techniques.

+ +

{{PreviousMenuNext("Learn/CSS/Styling_text/Fundamentals", "Learn/CSS/Styling_text/Styling_links", "Learn/CSS/Styling_text")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/uk/learn/getting_started_with_the_web/css_basics/index.html b/files/uk/learn/getting_started_with_the_web/css_basics/index.html new file mode 100644 index 0000000000..61069ad322 --- /dev/null +++ b/files/uk/learn/getting_started_with_the_web/css_basics/index.html @@ -0,0 +1,273 @@ +--- +title: Основи CSS +slug: Learn/Getting_started_with_the_web/CSS_basics +tags: + - CSS + - Веб + - Навчання + - Початківцям + - Стилізація +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")}}
+ +
+

Cascading Stylesheets (CSS, каскадні таблиці стилів) — це код, що використовується для стилізації сайту. В Основах CSS надається інформація про стилізацію для початківців. Ми відповімо на такі питання: яким чином зробити текст чорним або червоним? Як розмістити контент саме у тому місці, де ми хочемо його бачити на сторінці? Як задавати фонові кольори та зображення?

+
+ +

Що таке CSS насправді?

+ +

Як і HTML, CSS не є справжньою мовою програмування. Це лише мова таблиць стилів, яка дозволяє задавати стилі обраним елементам у HTML документах. Наприклад, для того, щоб вибрати усі параграфи на HTML сторінці та зробити колір їхнього тексту червоним, потрібно написати такий CSS:

+ +
p {
+  color: red;
+}
+ +

Давайте спробуємо: вставте ці три рядки CSS у новий файл у вашому редакторі коду, та збережіть файл як style.css у вашій теці styles.

+ +

Окрім того, нам необхідно приєднати CSS до вашого HTML документу, інакше стилі CSS не вплинуть на те, як браузер відобразить HTML документ. (Якщо ви щойно приєдналися до нашого проекту, прочитайте Роботу з файлами та Основи HTML щоб дізнатися, що необхідно зробити на початку.) Відкрийте ваш файл index.html та вставте наступний рядок кудись у head, між тегами <head> і </head>:

+ +
    +
  1. +
    <link href="styles/style.css" rel="stylesheet" type="text/css">
    +
  2. +
  3. Збережіть index.html та відкрийте його у вашому браузері. Ви побачите щось на зразок наведеного зображення:
  4. +
+ +

A mozilla logo and some paragraphs. The paragraph text has been styled red by our css.Якщо текст ваших параграфів став червоним, вітаємо! Ви щойно написали ваш перший CSS!

+ +

Анатомія правила CSS

+ +

Подивимось на попередній CSS більш детально:

+ +

+ +

Вся структура називається "rule set" — "набір правил" (частіше, скорочено, "правило"). Його частини також мають свої назви:

+ +
+
Selector — Селектор
+
Назва елементу HTML на початку правила. Селектор вибирає елемент чи елементи, які будуть стилізовані (у нашому випадку, елементи p). Для стилізації інших елементів просто змініть селектор.
+
Declaration — Визначення (декларація)
+
Одне правило на зразок color: red; вказує, яку властивість елементу ви бажаєте стилізувати.
+
Properties — Властивості
+
Шляхи, якими ви можете стилізувати даний HTML елемент. (У цьому випадку, color — це властивість елементів p). У CSS ви обираєте властивості, які хочете змінити у вашому правилі.
+
Property value — Значення властивості
+
Праворуч від властивості, після двокрапки, ми вказуємо значення властивості, обираючи з багатьох можливих значень для наданої властивості (є багато інших значень властивості color окрім red).
+
+ +

Зверніть увагу на інші важливі частини синтаксису:

+ + + +

Отже, для того, щоб змінити декілька значень властивостей одночасно, їх достатньо записати, розділяючи крапкою з комою, наприклад:

+ +
p {
+  color: red;
+  width: 500px;
+  border: 1px solid black;
+}
+ +

Вибір багатьох елементів одночасно

+ +

Ви також можете вибрати декілька типів елементів та застосувати один набір правил для них усіх. Додайте декілька селекторів, розділяючи їх комою, наприклад:

+ +
p,li,h1 {
+  color: red;
+}
+ +

Різні типи селекторів

+ +

Є велика кількість різних типів селекторів. Вище ми розглянули лише селектори елементів, які вибирають всі елементи заданого типу у наданих HTML документах. Але ми можемо застосовувати більш специфічні селектори. Подивіться на найбільш розповсюджені типи селекторів:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Назва селекторуЩо він вибираєПриклад
Селектор елементу (іноді називають селектором тегу)Всі HTML елементи даного типуp
+ Вибирає <p>
Селектор по IDЕлемент на сторінці, який має заданий ID (на HTML сторінці не може бути декілька елементів з однаковими ID).#my-id
+ Вибирає <p id="my-id"> чи <a id="my-id">
Селектор по класуЕлементи на сторінці, які мають задані класи (на сторінці можуть бути елементи з однаковими класами)..my-class
+ Вибирає <p class="my-class"> та <a class="my-class">
Селектор по атрибутуЕлементи на сторінці із вказаним атрибутомimg[src]
+ Вибирає <img src="myimage.png"> але не <img>
Селектори псевдокласівВказані елементи, але тільки тоді, коли вони знаходяться у вказаному стані, наприклад, коли на них наводять курсор миші.a:hover
+ Вибирає <a>, але тільки коли курсор миші вказує на посилання.
+ +

Інші селектори ви можете побачити на сторінці Selectors guide.

+ +

Шрифти та текст

+ +

Дослідивши деякі основи CSS, давайте додамо більше правил та інформації в файл style.css, щоб зробити наш приклад більш привабливим. Для початку покращимо вигляд наших шрифтів та тексту.

+ +
    +
  1. В першу чергу, знайдіть збережений вами вивід з сайту Google Fonts, який ви зберегли раніше. Додайте елемент <link ... > у head файлу index.html (будь-куди між тегами <head> та </head>). Елемент буде виглядати приблизно так: + +
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    +
  2. +
  3. Видаліть правило, яке зараз знаходиться у вашому файлі style.css. Це був гарний приклад, але червоний текст виглядає не дуже гарно.
  4. +
  5. Додайте наступні строки до вашого файлу стилей, замінивши placeholder на рядок font-family, який ви отримали з сайту Google Fonts. (font-family означає шрифти, які ви застосуєте для вашого тексту). Це правило встановить глобальний базовий шрифт і його розмір для всієї сторінки (так як <html> — це батьківський елемент всієї сторінки, всі елементи у ньому успадкують однаковий font-size та font-family): +
    html {
    +  font-size: 10px; /* px означає 'пікселі': базовий розмір шрифта встановлюється рівним 10 пікселів заввишки  */
    +  font-family: placeholder: замініть цей плейсхолдер на строку із сайту Google fonts
    +}
    + +
    +

    Примітка: Я додав коментар із поясненням, що означає "px". Все у CSS документі, що знаходиться  між /* та */ — це коментар CSS, який ігнорується браузером. Коментарі застосовують для приміток та пояснень, що допоможуть вам в роботі.

    +
    +
  6. +
  7. Встановимо розміри шрифта для елементів, що містять у собі текст всередині HTML body ({{htmlelement("h1")}}, {{htmlelement("li")}}, та {{htmlelement("p")}}). Також відцентруємо текст нашого заголовку та встановимо висоту строки і проміжок між літерами нашого контенту, щоб зробити його зручнішим для читання. +
    h1 {
    +  font-size: 60px;
    +  text-align: center;
    +}
    +
    +p, li {
    +  font-size: 16px;
    +  line-height: 2;
    +  letter-spacing: 1px;
    +}
    +
  8. +
+ +

Ви можете змінювати числа як завгодно, щоб ваш дизайн виглядав так, як ви хочете. Загалом він буде виглядати так:

+ +

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

+ +

Блоки, блоки, і ще раз про блоки

+ +

Одна річ, яку ви помітите при написанні CSS, полягає в тому, що багато використовуються блоки - встановлення їх розміру, кольору, позиції тощо. Більшість HTML-елементів на вашій сторінці можуть розглядатися як блоки, які розташовані один на одному.

+ +

a big stack of boxes or crates sat on top of one another

+ +

Не дивно, що макет CSS заснований переважно на блочній моделі (box model). Кожен із блоків, що займає простір на вашій сторінці, має такі властивості:

+ + + +

three boxes sat inside one another. From outside to in they are labelled margin, border and padding

+ +

В цьому розділі ми також використовуємо:

+ + + +

Отже, давайте почнемо та додамо ще кілька CSS на нашу сторінку! Додайте ці нові правила до нижньої частини сторінки, і не бійтеся експериментувати зі зміною значень, щоб побачити, як це працює.

+ +

Зміна кольору сторінки

+ +
html {
+  background-color: #00539F;
+}
+ +

Це правило встановлює фоновий колір для всієї сторінки . Змініть код кольору на будь-який інший, що ви обрали при плануванні свого сайту.

+ +

Задання стилів для body

+ +
body {
+  width: 600px;
+  margin: 0 auto;
+  background-color: #FF9500;
+  padding: 0 20px 20px 20px;
+  border: 5px solid black;
+}
+ +

Тепер стилі для елемента body. Тут багато параметрів, тому давайте розглянемо по-одному:

+ + + +

Позиціонування та стиль заголовка головної сторінки

+ +
h1 {
+  margin: 0;
+  padding: 20px 0;
+  color: #00539F;
+  text-shadow: 3px 3px 1px black;
+}
+ +

Ви, мабуть, помітили, що у верхній частині body є чималенький розрив. Це відбувається тому, що браузери застосовують деякий стиль за умовчанням до елемента {{htmlelement("h1")}} (серед інших), навіть якщо ви не застосували жодного CSS! Це може здаватись поганою ідеєю, але ми хочемо, щоб навіть незавершена веб-сторінка мала базову читабельність. Щоб позбутися розриву, ми перекриваємо стандартний стиль за замовчуванням, встановлюючи margin: 0;.

+ +

Далі ми встановили верхній та нижній відступи (padding) заголовку до 20 пікселів і зробили заголовок текстом того ж кольору, що і колір фону (background) всієї сторінки html.

+ +

Одна досить цікава властивість, яку ми використовували тут, це - text-shadow, яка застосовує текстову тінь до текстового вмісту елемента. Її чотири значення означають наступне:

+ + + +

Знову ж таки, спробуйте експериментувати з різними значеннями, щоб побачити, що ви можете придумати.

+ +

Центрування зображення

+ +
img {
+  display: block;
+  margin: 0 auto;
+}
+ +

Нарешті, ми будемо центрувати зображення, щоб воно виглядало краще. Ми могли б використати margin: 0 auto як і раніше для body, але ми також можемо зробити дещо інше. Елемент body є блочним рівнем, тобто він займає місце на сторінці, і до нього можуть бути додані поля та інші значення відступів. Зображення, з іншого боку, є вбудованими елементами (inline), тобто вони не можуть мати відступів. Таким чином, щоб застосувати поля до зображення, ми повинні надати поведінку блочного рівня зображенню за допомогою display: block;.

+ +
+

Примітка: Не хвилюйтесь, якщо ще не зрозуміли display: block; і відміну між блочним рівнем / вбудованим (inline) елементом. Далі ви будете вивчати CSS більш глибоко. Ви можете дізнатись більше про різні доступні значення відображення на нашому сайті display reference page.

+
+ +

Висновок

+ +

Якщо ви дотримувалися всіх інструкцій у цій статті, ви повинні отримати сторінку, яка виглядає приблизно так (ви можете також переглянути нашу версію тут):

+ +

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.

+ +

Якщо ви застрягли, ви можете завжди  порівняти свою роботу з нашим закінченим прикладом коду на Github.

+ +

Тут ми, дійсно, лише зачепили поверхневі знання із CSS. Щоб дізнатись більше, перейдіть до Вивчення теми CSS.

+ +

{{PreviousMenuNext("Learn/Getting_started_with_the_web/HTML_basics", "Learn/Getting_started_with_the_web/JavaScript_basics", "Learn/Getting_started_with_the_web")}}

diff --git a/files/uk/learn/getting_started_with_the_web/dealing_with_files/index.html b/files/uk/learn/getting_started_with_the_web/dealing_with_files/index.html new file mode 100644 index 0000000000..1cd1fa24d6 --- /dev/null +++ b/files/uk/learn/getting_started_with_the_web/dealing_with_files/index.html @@ -0,0 +1,101 @@ +--- +title: Робота з файлами +slug: Learn/Getting_started_with_the_web/Dealing_with_files +tags: + - HTML + - Веб-сайт + - Початківцям + - Теорія + - Файли +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")}}
+ +
+

Веб-сайт складається з багатьох файлів: текстового наповнення, коду, стилів, медіаконтенту тощо. Коли ви будуєте веб-сайт, ви маєте поєднати ці файли у єдину змістову структуру на своєму локальному комп'ютері, переконатися, що всі файли можуть "спілкуватися" один з одним і правильно відображати весь контент, до того, як ви завантажите їх на сервер. У статті Робота з файлами ми розглядаємо кілька питань, які допоможуть правильно налаштувати структуру файлів для вашого сайту. 

+
+ +

Де саме має зберігатися сайт на вашому комп'ютері?

+ +

Коли ви працюєте над своїм сайтом локально на комп'ютері, вам слід зберігати всі файли сайту в одній папці, структура якої має повністю відповідати структурі папки живого сайту, яка зберігається на сервері. Ваша локальна папка може зберігатися де завгодно, але найкраще тримати її там, де ви зможете її легко знайти, наприклад, на робочому столі чи в корені диска. 

+ +
    +
  1. Виберіть місце для зберігання ваший веб-сайтів. Створіть нову папку і назвіть її web-projects (або схожим чином). У цій папці житимуть всі ваші веб-проекти. 
  2. +
  3. Всередині папки, створіть ще одну папку для вашого першого веб-сайту. Назвіть її test-site (або більш вигадливо).
  4. +
+ +

Примітка про великі й малі літери і пробіли

+ +

Читаючи цю статтю, ви помітите, що ми просимо вас називати папки і файли малими літерами і без пробілів. Це тому що:

+ +
    +
  1. Багато комп'ютерів, особливо веб-серверів, є чутливими до регістрів літер. Наприклад, якщо ви покладете зображення MyImage.jpg у ваш веб-проект  test-site, а потім у якомусь файлі спробуєте вставити це зображення, вказавши шлях як test-site/myimage.jpg, це може не спрацювати.
  2. +
  3. Браузери, веб-сервери і мови програмування не завжди правильно опрацьовують пробіли. Наприклад, якщо ви використовуєте пробіли в назві файлу, деякі системи можуть вважати, що це дві окремі назви файлів. Деякі сервери замінять пробіли в назві файлів символом "%20" (код символу пробіл в URI), поламаючи при цьому ваші посилання. Краще розділяти слова дефісом, ніж нижнім підкресленням: my-file.html замість my_file.html.
  4. +
+ +

Коротко кажучи, вам слід використовувати дефіс у назвах файлів. Google розуміє дефіс як спосіб розділення слів, але на нижнє підкреслення це не поширюється. З цих міркувань, найкраще звикати до написання назв папок і файлів малими літерами без пробілів, розділяючи слова дефісом, принаймні допоки у вас немає достатніх знань. Так ви матимете менше проблем згодом. 

+ +

Яку структуру вибрати для вашого сайту?

+ +

Давайте поглянемо, яку структуру повинен мати ваш сайт. Найбільш поширені компоненти, які мають практично всі проекти, які ми створюємо, — це HTML-файл з назвою index, а також кілька папок: із зображеннями, стилями і скриптами. Давайте створимо їх зараз:

+ +
    +
  1. index.html: цей файл буде містити практично весь контент вашої головної сторінки — текст і зображення, які користувачі бачать, коли відвідують ваш сайт. У своєму текстовому редакторі створіть файл з назвою index.html і збережіть його в папці test-site.
  2. +
  3. Папка images: у цій папці будуть зібрані всі зображення, які ви будете використовувати на сайті. Створіть папку з назвою images всередині папки test-site.
  4. +
  5. Папка styles: у цій папці зберігатимуться всі CSS-файли зі стилями, якими ви будете змінювати зовнішній вигляд вашого контенту (наприклад, шрифт тексту чи колір бекграунду). Створіть папку styles всередині папки test-site.
  6. +
  7. Папка scripts: у цій папці будуть зберігатися всі файли з JavaScript-кодом, яким ви додасте інтерактивності вашому сайту (наприклад, щоб кнопки при кліку відображали якісь дані). Створіть папку scripts всередині папки test-site.
  8. +
+ +
+

Примітка: на комп'ютерах Windows ви не завжди можете бачити повну назву файлу із розширенням, оскільки Windows за замовчанням приховує розширення файлів. Ви можете змінити налаштування так: у File Explorer вибрати вкладку View і поставити "галочку" в пункті File name extensions. Більш детальну інформацію про те, як змінити налаштування на вашій версії Windows, можна легко знайти в інтернеті.

+
+ +

Шляхи файлів

+ +

Щоб змусити файли "спілкуватися" між собою, ви маєте вказати їм шлях один до одного — по суті, маршрут, за яким один файл буде знати, де лежить інший файл. Щоб показати, як це працює, ми додамо трохи HTML у наш файл index.html, щоб вкласти на сторінку зображення, яке ви вибрали в статті "What will your website look like?".

+ +
    +
  1. Скопіюйте вибране раніше зображення в папку images.
  2. +
  3. Відкрийте файл index.html і вставте туди цей код, точно так, як він поданий тут. Поки що не переймайтеся, що він означає, — пізніше ми розглянемо його в деталях. +
    <!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. Рядок <img src="" alt="My test image"> є кодом HTML, який вставить зображення на нашу сторінку. Ми маємо сказати цьому коду, де саме шукати картинку, тобто вказати шлях файлу. Наше зображення зберігається в папці images, яка, в свою чергу, зберігається на тому ж рівні (в тій самій директорії), що і файл index.html. Щоб файл index.html зміг дістатися до нашого зображення, нам потрібно спочатку вказати назву папки із зображеннями, а потім ім'я конкретного зображення, отак: images/ім'я-вашого-файлу. Наприклад, якщо наше зображення називається firefox-icon.png, то наш шлях виглядатиме так: images/firefox-icon.png.
  6. +
  7. Вставте цей шлях у ваш код HTML між лапками коду src="".
  8. +
  9. Збережіть файл HTML, потім відкрийте його в браузері (подвійний клік на файлі). Ви маєте побачити вашу нову веб-сторінку із зображенням! 
  10. +
+ +

A screenshot of our basic website showing just the firefox logo - a flaming fox wrapping the world

+ +

Загальні правила шляху файлу:

+ + + +

Поки що це все, що вам потрібно знати.

+ +
+

Примітка: файлова система Windows у своїх шляхах зазвичай використовує обернену скісну риску замість звичайної, наприклад, C:\windows. На ваш код HTML це не впливає— навіть якщо ви пишете сайт на Windows, вам все одно слід використовувати звичайну скісну риску. 

+
+ +

Що ще потрібно зробити?

+ +

Поки що це все. Структура вашої папки має виглядати приблизно так: 

+ +

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")}}

diff --git a/files/uk/learn/getting_started_with_the_web/how_the_web_works/index.html b/files/uk/learn/getting_started_with_the_web/how_the_web_works/index.html new file mode 100644 index 0000000000..d736cf3913 --- /dev/null +++ b/files/uk/learn/getting_started_with_the_web/how_the_web_works/index.html @@ -0,0 +1,94 @@ +--- +title: Як працює мережа +slug: Learn/Getting_started_with_the_web/How_the_Web_works +tags: + - IP-адреса + - Клієнт + - Початківцям + - Сервер + - протокол +translation_of: Learn/Getting_started_with_the_web/How_the_Web_works +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/Getting_started_with_the_web/Publishing_your_website", "Learn/Getting_started_with_the_web")}}
+ +
+

Стаття Як працює мережа спрощено пояснює, що саме відбувається, коли ви переглядаєте веб-сторінку у браузері на комп'ютері чи телефоні. 

+
+ +

Ця теорія не є обов'язковою на початку веб-розробки, але чим далі ви просуватиметеся, тим більш очевидними будуть переваги розуміння того, що саме відбувається за лаштунками. 

+ +

Клієнти та сервери

+ +

Комп'ютери, приєднані до мережі, називаються клієнтами та серверами. Цей малюнок спрощено показує, як відбувається їхня взаємодія: 

+ +

+ + + +

Інші гравці на полі

+ +

Клієнт та сервер, про які йшлося вище, не єдині учасники процесу. Існує багато інших складових, про які ми зараз розкажемо. 

+ +

Для початку, уявимо мережу як дорогу. На одному кінці дороги — ваш будинок. Це наш клієнт. На протилежному кінці дороги — крамниця, у якій ви хочете щось придбати. Це наш сервер. 

+ +

+ +

На додачу до сервера і клієнта, ми також маємо: 

+ + + +

То що, власне, відбувається?

+ +

Коли ви вписуєте адресу в браузер, то:

+ +
    +
  1. Браузер іде на DNS-сервер і знаходить там справжню адресу серверу, на якому зберігається потрібний вам сайт (ви знаходите адресу магазину).
  2. +
  3. Браузер надсилає HTTP-запит до сервера з проханням вислати копію сайту на клієнт (ви йдете в магазин і замовляєте товар). Цей запит і всі інші дані, які пересилаються між клієнтом і сервером, передаються в мережі за допомогою TCP/IP.
  4. +
  5. Якщо сервер вирішує задовольнити запит, він відсилає клієнту повідомлення "200 OK", що означає "Звісно, ви можете подивитися цей веб-сайт! Ось він", і потім починає відсилати файли веб-сайту в браузер по шматочках, погрупованих в маленькі набори, які називаються пакетами даних (магазин видає вам ваш товар і ви несете його додому).
  6. +
  7. Браузер збирає докупи всі шматочки і показує їх вам у вигляді готової веб-сторінки (ваш товар вже вдома!).
  8. +
+ +

Пояснення DNS

+ +

Усі адреси ваших улюблених сайтів насправді є зовсім не такими, якими виглядають. Вони є спеціальними наборами цифр, як, наприклад, оцей: 63.245.215.20.

+ +

Це {{Glossary("IP Address", "IP-адреса")}} сайту, вона представляє унікальне місце зберігання сайту в мережі. Її непросто запам'ятати, чи не так? Саме тому бути винайдені сервери доменних імен (Domain Name Servers), або DNS-сервери. Це спеціальні сервери, які зіставляють веб-адресу, яку ви вводите в браузер (наприклад, "mozilla.org") зі справжньою (IP) адресою сайту.

+ +

Веб-сайти можна знайти напряму через їхні IP-адреси. Спробуйте зайти на сайт Mozilla website, увівши 63.245.215.20 в адресний рядок браузера.

+ +

A domain name is just another form of an IP address

+ +

Пояснення пакетів

+ +

Вище ми вживали термін "пакет", щоб описати формат, у якому дані пересилаються з сервера на клієнт. Що це означає? Дані пересилаються по мережі у вигляді серій пакетів, кожен з яких містить маленьких шматок інформації. Це робиться для того, щоб багато різних користувачів могли завантажувати одну й ту саму сторінку одночасно. Якщо б веб-сайти надсилалися одним великим шматком, тільки один користувач міг би завантажувати її в певний час, що значно ускладнило б користування мережею. 

+ +

Також дивися

+ + + +

Автор фото

+ +

Street photo: Street composing, by Kevin D.

+ +

{{PreviousMenu("Learn/Getting_started_with_the_web/Publishing_your_website", "Learn/Getting_started_with_the_web")}}

diff --git a/files/uk/learn/getting_started_with_the_web/html_basics/index.html b/files/uk/learn/getting_started_with_the_web/html_basics/index.html new file mode 100644 index 0000000000..71e66f6f1e --- /dev/null +++ b/files/uk/learn/getting_started_with_the_web/html_basics/index.html @@ -0,0 +1,214 @@ +--- +title: Основи HTML +slug: Learn/Getting_started_with_the_web/HTML_basics +tags: + - HTML + - Початківець +translation_of: Learn/Getting_started_with_the_web/HTML_basics +--- +
{{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 (мова гіпертекстової розмітки) — це код, який використовується для структурування і відображення веб-сторінки та її контенту. Наприклад, контент може бути розбитий на параграфи (абзаци), містити список, зображення чи таблицю. Ця стаття має дати базове розуміння мови HTML та її призначення. 

+
+ +

Що таке HTML?

+ +

HTML — це не мова програмування, це мова розмітки, яка каже вашому браузеру, як відображати вміст веб-сторінки, яку ви переглядаєте. Вона може бути простою чи складною, залежно від бажання веб-дизайнера, який її створює. HTML складається з серії ({{Glossary("element", "елементів")}}), які використовуються для вміщення, або "загортання" в них різних частин контенту, щоб вони відображалися чи діяли в певний спосіб. Ці елементи за допомогою початкових і кінцевих ({{Glossary("tag", "тегів")}}) можуть зробити слово чи зображення посиланням на будь-яку іншу сторінку, можуть відображати текст курсивом, збільшити чи зменшити шрифт тощо. Для прикладу, візьмемо такий контент: 

+ +
Мій кіт дуже сумний.
+ +

Якщо ми хочемо, щоб цей рядок був сам по собі, ми можемо вказати, що це параграф (абзац), додавши до нього відповідні теги:

+ +
<p>Мій кіт дуже сумний.</p>
+ +

Анатомія елементу HTML

+ +

Погляньмо на елемент "параграф" детальніше. 

+ +

+ +

Основні частини елементу такі:

+ +
    +
  1. Початковий тег: містить назву елементу (в даному випадку, p), загорнену в кутові дужки. Цей тег позначає початок елементу, або місце, де елемент починає діяти. У даному випадку — це місце, де починається параграф. 
  2. +
  3. Кінцевий тег: такий самий тег, як і початковий, тільки тепер він містить скісну риску перед назвою елементу. Цей тег позначає місце закінчення елементу — у даному випадку, місце, де закінчується параграф. Одна з найпоширеніших помилок початківців — це забути поставити кінцевий тег, що може призвести до несподіваних результатів. 
  4. +
  5. Вміст: вміст елементу, у даному випадку — просто текст. 
  6. +
  7. Елемент: початковий тег плюс кінцевий тег плюс вміст між ними — дорівнює елемент.
  8. +
+ +

Елементи також можуть мати атрибути, які виглядають так: 

+ +

+ +

Атрибути містять додаткову інформацію про елемент, яка не відображається в самому контенті. У прикладі вище class це ім'я атрибута, а editor-note — це значення атрибута. Атрибут class дозволяє дати елементу певний ідентифікатор, який пізніше можна використати для того, щоб доступитися до цього елемента і змінити його стиль. 

+ +

Атрибут завжди повинен мати:

+ +
    +
  1. Пробіл між ім'ям атрибута і назвою елементу (або попереднім атрибутом, якщо такий є).
  2. +
  3. Ім'я атрибута, за яким іде знак дорівнює.
  4. +
  5. Значення атрибута, загорнене в прямі лапки.
  6. +
+ +

Вкладені елементи

+ +

Ви можете додати елемент всередину іншого елементу. Це називається вкладенням. Якщо ми хочемо наголосити, що наш кіт дуже сумний, ми можемо загорнути слово "дуже" в елемент {{htmlelement("strong")}}, який означає, що слово особливо сильно наголошене:

+ +
<p>Мій кіт <strong>дуже</strong> сумний.</p>
+ +

Важливо пам'ятати правильне вкладення елементів: у прикладі вище ми спершу відкрили елемент {{htmlelement("p")}}, а потім елемент <strong>, що означає, що першим ми маємо закрити внутрішній елемент {{htmlelement("strong")}}, а потім зовнішній {{htmlelement("p")}}. Приклад нижче неправильний:

+ +
<p>Мій кіт <strong>дуже сумний.</p></strong>
+ +

Елемент має закриватися або всередині, або ззовні іншого елемента. Якщо кінцевий тег зовнішнього елемента іде перед кінцевим тегом внутрішнього елемента, ваш браузер спробує здогадатися, що ви хотіли цим всім сказати, і результати цього можуть бути неочікуваними. Тому не робіть так!

+ +

Порожні елементи

+ +

Деякі елементи не містять жодного вмісту. Вони називаються порожніми елементами. Для прикладу візьмемо елемент {{htmlelement("img")}}:

+ +
<img src="images/firefox-icon.png" alt="Моє тестове зображення">
+ +

Цей елемент має два атрибути, при цьому не має кінцевого тегу і жодного внутрішнього вмісту. Елементу image не потрібно загортати контент, його мета — вставити зображення на певне місце на веб-сторінці.

+ +

Анатомія HTML-документу

+ +

Все зазначене вище є основами HTML-елементів, але окремо взяті елементи самі по собі мало на що здатні. Тепер ми поглянемо на те, як окремі елементи формують цілу веб-сторінку. Візьмемо для прикладу код з файлу index.html (який використовується в статті Робота з файлами):

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>Моя тестова сторінка</title>
+  </head>
+  <body>
+    <img src="images/firefox-icon.png" alt="Моє тестове зображення">
+  </body>
+</html>
+ +

Тут ми маємо:

+ + + +

Зображення

+ +

Повернемося до елементу {{htmlelement("img")}}:

+ +
<img src="images/firefox-icon.png" alt="Моє тестове зображення">
+ +

Як ми вже з'ясували раніше, цей елемент вставляє зображення на сторінку в тому місці, де воно має з'явитися.  Це відбувається за допомогою атрибута src (source — джерело), який містить шлях до зображення.

+ +

Також ми додали атрибут alt (alternative). У цьому атрибуті потрібно вказувати альтернативний текст-опис зображення для тих випадків, коли користувачі не зможуть побачити картинку, наприклад, через те, що:

+ +
    +
  1. Мають порушення зору. Користувачі з порушенням зору часто використовують скрін-рідери, які читають описи зображень.
  2. +
  3. Щось пішло не так при завантаженні зображення. Спробуйте навмисно змінити шлях до зображення в атрибуті src, щоб він став неправильним. Якщо ви тепер перезавантажите сторінку, ви побачите, що на місці зображення буде текст:
  4. +
+ +

+ +

Основним при створенні атрибута alt має бути описовість тексту. Цей атрибут має дати користувачу достатньо інформації, щоб скласти уявлення про те, що є на зображенні. У нашому випадку, текст "Моє тестове зображення" нікуди не годиться. Набагато кращий варіант для логотипу Firefox був би "Логотип Firefox: палаюча лисиця навколо Земної кулі."

+ +

Спробуйте придумати кращий альтернативний текст для свого зображення. 

+ +
+

Примітка: дізнайтеся більше про доступність на сторінці MDN's Accessibility.

+
+ +

Розмітка тексту

+ +

У цьому розділі ми розглянемо базові HTML-елементи, які використовуються для розмітки тексту.

+ +

Заголовки

+ +

Елементи "Heading" дозволяють вам вказати, що певні частини контенту вашої сторінки є заголовками або підзаголовками. Так само, як у книжці є назва книги, назви розділів і підзаголовки, у HTML-документі це також є. HTML має заголовки шістьох рівнів, {{htmlelement("h1")}}–{{htmlelement("h6")}}, хоча зазвичай використовуються перші 3-4.

+ +
<h1>Мій головний заголовок</h1>
+<h2>Мій важливий заголовок</h2>
+<h3>Мій підзаголовок</h3>
+<h4>Мій менш важливий підзаголовок</h4>
+ +

Спробуйте додати підзаголовки до вашої HTML-сторінки перед елементом {{htmlelement("img")}}.

+ +

Параграфи

+ +

Як пояснювалося вище, елемент {{htmlelement("p")}} містить частину тексту, яка становить один абзац. Параграфи використовуються дуже часто, особливо при розмітці звичайного текстового контенту:

+ +
<p>Це один параграф.</p>
+ +

Додайте зразок тексту (він має бути готовий зі статті Як виглядатиме ваш сайт?) в один чи два параграфи і розмістіть їх прямо під елементом {{htmlelement("img")}}.

+ +

Списки

+ +

Чимало контенту на веб-сторінках є списками, і в HTML є спеціальні елементи для них. Розмітка списків завжди має принаймні два елементи. Найпоширеніші типи списків - це нумерований і ненумерований списки:

+ +
    +
  1. Ненумерований список — це перелік, у якому порядок пунктів не суттєвий, наприклад, список покупок. Такий список загортається в елемент {{htmlelement("ul")}}.
  2. +
  3. Нумерований список — це перелік, у якому порядок пунктів має значення, наприклад, рецепт приготування. Такий список загортається в елемент {{htmlelement("ol")}}.
  4. +
+ +

Кожен пункт всередині списку загортається в свій окремий елемент {{htmlelement("li")}} (list item).

+ +

Наприклад, якщо ми хочемо перетворити такий параграф у список: 

+ +
<p>Mozilla — це глобальна спільнота технологів, мислителів і творців, які працюють разом...</p>
+ +

Ми можемо так змінити розмітку:

+ +
<p>Mozilla — це глобальна спільнота</p>
+
+<ul>
+  <li>технологів</li>
+  <li>мислителів</li>
+  <li>творців</li>
+</ul>
+
+<p>які працюють разом... </p>
+ +

Спробуйте додати нумерований чи ненумерований список до вашої сторінки.

+ +

Посилання

+ +

Посилання дуже важливі — це те, що робить мережу мережею! Щоб додати посилання, потрібно використовувати елемент {{htmlelement("a")}} ("a" скорочено від "anchor" — якір). Щоб перетворити параграф на посилання, робіть так:

+ +
    +
  1. Виберіть текст. Ми вибрали "Mozilla Manifesto".
  2. +
  3. Загорніть цей текст в елемент {{htmlelement("a")}}, отак: +
    <a>Mozilla Manifesto</a>
    +
  4. +
  5. Додайте до елементу {{htmlelement("a")}} атрибут href, отак: +
    <a href="">Mozilla Manifesto</a>
    +
  6. +
  7. Додайте значення цьому атрибута — адресу посилання: +
    <a href="https://www.mozilla.org/en-US/about/manifesto/">Mozilla Manifesto</a>
    +
  8. +
+ +

Не пропускайте частину https:// чи http:// на початку адреси, так званий протокол, інакше результати можуть бути неочікуваними. Після того, як елемент доданий, клікніть на посилання і переконайтеся, що вас відправило туди, куди ви хотіли.

+ +
+

href може видаватися дивним ім'ям для атрибута, який складно запам'ятати. Він означає hypertext reference — гіпертекстове посилання.

+
+ +

Тепер додайте посилання до своєї сторінки.

+ +

Висновок

+ +

Якщо ви слідували інструкціям у цій статті, у вас мала вийти сторінка, яка виглядає приблизно так (також можна переглянути тут):
+
+ A web page screenshot showing a firefox logo, a heading saying mozilla is cool, and two paragraphs of filler text

+ +

Якщо ви застрягли, ви завжди можете порівняти свій код із завершеним прикладом коду на GitHub.

+ +

У цій статті ми розглянули тільки базові поняття HTML. Щоб дізнатися більше, зайдіть на сторінку HTML Learning topic.

+ +

{{PreviousMenuNext("Learn/Getting_started_with_the_web/Dealing_with_files", "Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web")}}

diff --git a/files/uk/learn/getting_started_with_the_web/index.html b/files/uk/learn/getting_started_with_the_web/index.html new file mode 100644 index 0000000000..af137773c8 --- /dev/null +++ b/files/uk/learn/getting_started_with_the_web/index.html @@ -0,0 +1,64 @@ +--- +title: Початок роботи з Інтернетом +slug: Learn/Getting_started_with_the_web +tags: + - CSS + - HTML + - 'l10n: пріоритет' + - Покажчик + - Посібник + - Початківцям + - Розробка + - Теорія +translation_of: Learn/Getting_started_with_the_web +--- +
{{LearnSidebar}}
+ +
+

«Початок роботи з Інтернетом» — це серія стислих статей, що знайомить з практичними питаннями веб-розробки. Ви налаштуєте інструменти, необхідні для створення простої веб-сторінки та публікації власного коду.

+
+ +

Історія вашого першого сайту

+ +

Розробка професійного сайту - це кропітка робота. Радимо не поспішати, якщо ви початківець у веб-програмуванні. Ви не отримаєте відразу новий Facebook, але легко побудуєте свій перший сайт.

+ +

Опрацьовуючи статті послідовно, ви розташуєте створену веб-сторінку в інтернеті. Почнемо!

+ +

Встановлення необхідних програм

+ +

Є чимало інструментів для побудови сайтів. Початківець може розгубитись, при виборі редакторів коду, фреймворків  та засобів для тестів. Встановлення необхідних програм поступово допоможе встановити все, що потрібно для простої веб-розробки.

+ +

Який вигляд матиме ваш сайт?

+ +

Перед тим, як почати писати код для сайту, треба мати план. Яку інформацію відобразити? Які кольори та шрифти використати? Який вигляд матиме ваш сайт? Пропонуємо вам простий спосіб планування змісту та зовнішнього вигляду вашого сайту.

+ +

Робота з файлами

+ +

Сайт складається з багатьох файлів: текстів, коду, таблиць стилів, медіа-контенту тощо. Коли створюється сайт, потрібно об'єднати ці файли в логічну структуру та впевнитися, що вони доступні одне одному. Робота з файлами пояснює, як створити логічну структуру файлів для сайту й уникнути типових проблем.

+ +

Основи HTML

+ +

Hypertext Markup Language (HTML, мова розмітки гіпертексту) — це код, що структурує зміст веб-сторінок та надання йому значення і мети. Наприклад, чи є контент набором параграфів, чи списком із маркерами? Чи є на сторінці зображення, таблиці з даними? В Основах HTML достатньо інформації для знайомства з HTML.

+ +

Основи CSS

+ +

Cascading Stylesheets (CSS, каскадні таблиці стилів) — це код для стилізації сайту. Наприклад, який колір тексту, де розміщенно контент на екрані? Які фонові зображення та кольори взято для оздоблення сайту? З Основ CSS ви дізнаєтесь про стилізацію для початківців.

+ +

Основи JavaScript

+ +

JavaScript — це мова програмування, яку використовують для можливості взаємодії з веб-сайтами. А саме: ігри, дії, що відбудутся після натиску на кнопоку або введення даних до форми, створення динамічних стилей, анімацій тощо. Основи JavaScript описують можливості цієї захоплючої мови програмування та як почати нею користовуватись.

+ +

Публікація вашого сайту

+ +

Після написання коду та організації файлів вашого сайту, необхідно розмістити його в інтернеті, щоб люди могли побачити результати вашої праці. Публікація вашого коду допоможе як найлегше розмістити ваш код в інтернеті.

+ +

Як працює Інтернет 

+ +

Коли ви заходите на улюблений сайт, виконується безліч фонових завдань, можливо непомітних для вас. Як працює Інтернет описує процеси, які відбуваються, коли ви переглядаєте веб-сторінку на компьютері.

+ +

Дивіться також

+ + diff --git a/files/uk/learn/getting_started_with_the_web/installing_basic_software/index.html b/files/uk/learn/getting_started_with_the_web/installing_basic_software/index.html new file mode 100644 index 0000000000..22e6bfadf6 --- /dev/null +++ b/files/uk/learn/getting_started_with_the_web/installing_basic_software/index.html @@ -0,0 +1,63 @@ +--- +title: Встановлення необхідних програм +slug: Learn/Getting_started_with_the_web/Installing_basic_software +tags: + - Браузер + - Початківцям + - текстовий редактор + - інструменти +translation_of: Learn/Getting_started_with_the_web/Installing_basic_software +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/Getting_started_with_the_web/What_will_your_website_look_like", "Learn/Getting_started_with_the_web")}}
+ +
+

В статті "Встановлення необхідних програм" ми з'ясуємо, які інструменти потрібні для веб-розробки та як їх правильно встановити.

+
+ +

Які інструменти використовують професіонали?

+ + + +

Які інструменти мені потрібні зараз?

+ +

Список виглядає страшно, але на щастя ви можете починати веб-розробку без знань більшості з них. У статті розглянемо базовий мінімум — текстовий редактор і кілька сучасних браузерів. 

+ +

Встановлення текстового редактора

+ +

Напевно, у вас вже є простий текстовий редактор на комп'ютері. Windows зазвичай має Notepad, а macOS — TextEdit. Linux пропонує різні варіанти, зокрема Ubuntu має gedit.

+ +

Для веб-розробки доступні кращі редактори, ніж Notepad чи TextEdit. Пропонуємо Brackets —безкоштовний редактор з підказками та попереднім переглядом. 

+ +

Встановлення сучасного браузера

+ +

Встановимо кілька браузерів, щоб тестувати наш код. Оберіть операційну систему, клацніть відповідне посилання та завантажте улюблені браузери:

+ + + +

Перед тим, як продовжити, встановіть принаймні два з цих браузерів і запустіть їх.

+ +
+

Internet Explorer не сумісний з деякими сучасними функціями вебу та, вірогідно, не зможе запустити ваш проект. Зазвичай вам не потрібно турбуватися про те, щоб зробити свої веб-проекти сумісними з ним, оскільки дуже мало людей все ще користуються ним - тож, не надто переймайтеся про це, поки ви навчаєтесь. Іноді ви можете зіткнутися з проектом, який потребує його підтримки.

+
+ +

Встановлення локального веб-сервера

+ +

Деякі приклади потрібно буде тестувати на локальному веб-сервері. Ви можете дізнатися, як його встановити, у статті Як ти налаштуєш локальний тестовий сервер?

+ +

{{NextMenu("Learn/Getting_started_with_the_web/What_will_your_website_look_like", "Learn/Getting_started_with_the_web")}}

diff --git a/files/uk/learn/getting_started_with_the_web/javascript_basics/index.html b/files/uk/learn/getting_started_with_the_web/javascript_basics/index.html new file mode 100644 index 0000000000..50ffb7a580 --- /dev/null +++ b/files/uk/learn/getting_started_with_the_web/javascript_basics/index.html @@ -0,0 +1,401 @@ +--- +title: Основи JavaScript +slug: Learn/Getting_started_with_the_web/JavaScript_basics +tags: + - Інтернет + - Мова + - Основи + - Українська + - вивчення +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 — це мова програмування, яка приносить інтерактивність до вашого веб-сайту (наприклад: ігри, реакція на натиски кнопок, введеня даних через форми, динамічна зміна стилів, анімація). Ця стаття допоможе розпочати вивчення цієї захоплюючої мови і дасть вам уяву про її можливості.

+
+ +

Що ж являє собою JavaScript насправді?

+ +

{{Glossary("JavaScript")}} ("JS" скорочено) це повноцінна {{Glossary("Динамічна мова програмування", "динамічна мова програмування")}}, яка, у застосуванні до {{Glossary("HTML")}} документу, може надати динамічну інтерактивність на веб-сайтах. Вона була винайдена Бренданом Eйхом, співзасновником проекту Mozilla, the Mozilla Foundation, та Mozilla Corporation.

+ +

JavaScript має надзвичайно багато застосувань. Ви можете розпочати з малого: створити "каруселі", галереї зображень, динамічні макети сторінок, відповіді на натиски кнопок, тощо. Із досвідом, ви зможете створювати ігри, 2D та 3D графіку, складні застосунки з використанням баз даних та багато іншого!

+ +

JavaScript доволі компактна та гнучка мова. Розробники забезпечили велике розмаїття інструментів, що доповнюють основу мови JavaScript, які відкривають величезну кількість додаткового функціоналу з мінімальними зусиллями. Серед них:

+ + + +

Тому що ця стаття повинна бути легким введенням до JavaScript, на цьому етапі ми не будемо займати вашу увагу детальними розмовами про різницю основної мови JavaScript та різними інструментами, що наведені вище. Ви можете вивчити це у деталях пізніше, у нашій JavaScript learning area, та решті MDN.

+ +

Нижче ми представимо вам деякі аспекти основної мови, а також ви ознайомитесь з деякими можливостями API браузера. Розважайтесь!

+ +

Приклад "hello world"

+ +

Попередній розділ звучить неймовірно, і це дійсно так — JavaScript є одним із найперспекнивніших Веб-технологій, і коли ви проникнитесь та почнете використовувати його, ваші веб-сайти перейдуть у нові виміри продуктивності та креативності.

+ +

Тим не менш,  відчувати себе комфортно з  JavaScript складніше ніж з HTML та CSS. Вам потрібно починати з малого та продовжувати працювати малими послідовними кроками. Для початку, ми розглянемо як додати деякі прості JS-елементи на вашу сторінку,  створюючи "hello world!" зразок (стандартний приклад з програмування).

+ +
+

Важливо: Якщо ви не проходили пепередні частини курсу, завантажте цей зразок коду(архів) і використовуйте його як точку початку.

+
+ +
    +
  1. Перш за все, перейдіть до вашого тестового сайту та створіть нову папку з іменем "scripts"(без лапок). Тоді, всередині нової папки для скриптів, що ви щойно створили, створіть новий файл з назвою main.js. Збережіть його в папці scripts .
  2. +
  3. Далі, у вашому файлі index.html введіть наступний елемент в новому рядку просто перед закриваючим тегом </body> : +
    <script src="scripts/main.js"></script>
    +
  4. +
  5. Загалом,  це те ж саме, що і {{htmlelement("link")}} елемент для CSS — він додає JavaScript до сторінки, тож це може впливати на HTML (також на CSS, та будь що інше на сторінці).
  6. +
  7. Тепер додайте цей код до файлу main.js : +
    var myHeading = document.querySelector('h1');
    +myHeading.textContent = 'Hello world!';
    +
  8. +
  9. Наприкінці,  переконайтесь, що файли HTML та JavaScript збережені та приєднані до  index.html в браузері. Ви маєте побачити щось на кшталт цього:
  10. +
+ +
+

Зауважте: Причиною, чому ми ставимо {{htmlelement("script")}} елемент ближче до низу HTML файлу, є те, що HTML завантажується браузером в порядку того, як він прописаний в файлі. Якщо JavaScript завантажено першим, а очікується, що він має впливати на HTML під ним, він може не працювати, якщо JavaScript завантажується раніше, ніж HTML, над яким він має здійснювати якісь маніпуляції. Тож, писати підключення JavaScript наприкінці коду HTML це, зачасту, найкраща стратегія.

+
+ +

Що сталось?

+ +

Текст вашого заголовка було замінено на "Hello world!", використовуючи JavaScript.  Ви зробили це за допомогою першої функції яку використали, яка має назву {{domxref("Document.querySelector", "querySelector()")}} щоб отримати посилання на ваш заголовок та зберегти його у змінній myHeading. Дуже схоже до того, що ми робили, використовуючи CSS селектори. Коли є потреба щось зробити з елементом, ви маєте спочатку його вибрати.

+ +

Після цього, ви присвоюєте значення змінної myHeading властивості {{domxref("Node.textContent", "textContent")}} (яка містить контекст заголовка), а саме "Hello world!".

+ +
+

Зауважте: Обидві можливості, що ви використовували перед цим, є частиною Document Object Model (DOM) API, що дозволяє вам маніпулювати документами.

+
+ +

Прискорений курс основ

+ +

Розгляньмо кілька основних можливостей мови JavaScript, щоб дати вам краще розуміння того, як це все працює. Варто зазначити, що ці речі притаманні всім мовам програмування, тож якщо ви засвоїте цей базис, ви на шляху до того, щоб могти програмувати будь-що!

+ +
+

Важливо:  У цій статті, намагайтесь перевіряти приклади коду на своєму ПК у JavaScript консолі. Детальніша інформація про JS-консоль та інші засоби розробника у браузері.

+
+ +

Змінні

+ +

{{Glossary("Змінна", "Змінні")}} - контейнери, у яких ви можете зберігати значення. Ви можете розпочати з оголошення змінної за допомогою ключового слова var , після якого вказавши ім'я, яким ви хочете назвати змінну:

+ +
var myVariable;
+ +
+

Зауважте: Крапка з комою(англ. semicolon) в кінці рядка вказує на кінець виразу; ставити крапку з комою обов'язково, коли вам потрібно розділити вирази в одному рядку. Однак, деякі люди вважають гарною практикою ставити в кінці кожного виразу. Є інші правила, коли ви маєте чи не маєте ставити крапку з комою - дивіться Your Guide to Semicolons in JavaScript, щоб дізнатись більше.

+
+ +
+

Зауважте: Ви можете називати змінні майже будь-як, проте є певні обмеження (читайте статтю про правила іменування змінних.) Якщо вагаєтесь, можна перевірити ім'я вашої змінної, щоб дізнатись, чи є воно коректним.

+
+ +
+

Зауважте: JavaScript це мова чутлива до регістру — myVariable , це не те саме, що myvariable чи MYvariable. Якщо ви маєте проблеми з кодом, можливо, варто перевірити регістр.

+
+ +

Після оголошення змінної, ви можете просвоїти їй значення:

+ +
myVariable = 'Bob';
+ +

Ви можете виконувати обидві операції в одному рядку:

+ +
var myVariable = 'Bob';
+ +

Ви можете звертатись до змінної, просто вказавши її ім'я:

+ +
myVariable;
+ +

Після надання змінній значення, ви можете пізніше змінити його:

+ +
var myVariable = 'Bob';
+myVariable = 'Steve';
+ +

Зауважте, що змінні можуть містити значення різних типів:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ТипПоясненняПриклад
{{Glossary("String")}}Послідовність символів, відома як рядок. Щоб визначити, що значенням є рядок, ви мусите занести його в лапки.var myVariable = 'Bob';
{{Glossary("Number")}}Число. Без лапок.var myVariable = 10;
{{Glossary("Boolean")}}Значення True/False. Слова true та false є спеціальними словами в JS, та не потребують лапок.var myVariable = true;
{{Glossary("Array")}}Масив. Дозволяє зберігати багато значень за одним посиланням.var myVariable = [1,'Bob','Steve',10];
+ Виклик значень елементів здійснюється так:
+ myVariable[0], myVariable[1], і т. д.
{{Glossary("Object")}}Загалом, будь-що. Все у JS є об'єктом і може міститись у змінній. Пам'ятайте це.var myVariable = document.querySelector('h1');
+ Всі попередні приклади теж.
+ +

То навіщо нам потрібні змінні? Щож, змінні потрібні для всіх цікавих у програмуванні речей. Якби змінні не могли змінюватись, то ви не могли б робити ніяких динамічних речей, як то персоналізовані вітальні повідомлення чи зміна відображуваних в галереї зображень.

+ +

Коментарі

+ +

Ви можете залишати коментарі у JavaScript коді, так само як у CSS:

+ +
/*
+Все, що всередині, є коментарем.
+*/
+ +

Якщо коментар однорядковий, то простіше виділити його двома слешами:

+ +
// Це коментар. Малозмістовний, та все ж.
+
+ +

Оператори

+ +

{{Glossary("Оператор")}} , це математичний символ, що видає результат,  оснований на двох значення(чи змінних). В таблиці нижче ви можете побачити деякі з напростіших операторів з деякими прикладами, які можете перевірити у JavaScript консолі.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ОператорПоясненняСимволПриклад
Додавання/конкатинаціяВживається для додавання двох чисел чи злиття двох рядків разом.+6 + 9;
+ "Hello " + "world!";
Віднімання, множення, діленняТе ж, що і в простій математиці.-, *, / +

9 - 3;
+ 8 * 2;  //Множення у JS позначається зірочкою
+ 9 / 3;

+
ПрисвоєнняВи вже це бачили; присвоєння змінній значення.=var myVariable = 'Bob';
ПорівнянняПеревіряє чи дві змінні рівні та повертає true/false (Boolean) .===var myVariable = 3;
+ myVariable === 4;//false
Заперечення (обернений до порівняння)Повертає логічний вираз, протилежний значенню операнда; true стає false і т.п. Повертає true, якщо значення не рівні.!, !== +

Початковий вираз true, але повертається false , оскільки це заперечене порівняння :

+ +

var myVariable = 3;
+ !(myVariable === 3);

+ +

Ми перевіряємо "чи myVariable НЕ рівне 3". Повертає false, оскільки myVariable РІВНЕ 3.

+ +

var myVariable = 3;
+ myVariable !== 3;

+
+ +

Існує ще багато операторів, які ви можете використовувати, та цих поки достатньо. Відвідайте Expressions and operators, щоб побачити повний список.

+ +
+

Зауважте: Змішування типів даних може привести до дивних результатів при виконанні обрахунків, тож будьте обережні. Наприклад, введіть "35" + "25" в своїй консолі. Чому ви отримали не той результат, на який ви очікували? Тому, що лапки перетворили числа в рядки, тож виконалось не додавання, а злиття рядків. Якщо ввести 35 + 25 , то результат буде таким, який ви, можливо, очікували у попередньому випадку.

+
+ +

Умови

+ +

Умовами називають структури коду, що дозволяють вам перевіряти, повертає вираз true, чи ні, виконуючи певні частини коду, залежно від результату. Поширеною формою умовної конструкції є if ... else.  Наприклад:

+ +
var iceCream = 'chocolate';
+if (iceCream === 'chocolate') {
+  alert('Yay, I love chocolate ice cream!');
+} else {
+  alert('Awwww, but chocolate is my favorite...');
+}
+ +

Вираз всередині if ( ... ), це порівняння — використовує оператор порівняння щоб співставити значення змінної iceCream з рядком 'chocolate',щоб визначити, чи рівні вони. Якщо true, то запускається перший блок коду. Якщо порівняння не повертає true, то перший блок пропускається, а  другий блок, після виразу else, запускається замість нього.

+ +

Функції

+ +

{{Glossary("Функція", "Функції")}}, це шлях до збереження функціоналу, який ви плануєте використовувати знову. В такому разі, коли вам потрібна певна процедура, ви можете просто викликати відповідну функцію. Ви вже бачили деякі використання функцій, наприклад:

+ +
    +
  1. +
    var myVariable = document.querySelector('h1');
    +
  2. +
  3. +
    alert('hello!');
    +
  4. +
+ +

Ці функції, document.querySelector та alert, є вбудованими у браузер, тож ви можете викликати їх коли вам заманеться.

+ +

Якщо ви бачите щось, що виглядає, як ім'я змінної, проте має дужки до — () — та після, це функція. Функції зазвичай приймають {{Glossary("Арґумент", "аргументи")}} — дані, що необхідні їм для роботи. Їх записують між дужками, розділяючи комами, якщо є більше одного.

+ +

Наприклад, функція alert() створює випадаюче вікно в вікні браузера, але ми маємо задати аргументом рядок, щоб повідомити функції, що саме потрібно написати у випадаючому вікні.

+ +

Звісно ж, ви можете описувати власні функції — у цьому прикладі ми напишемо просту функцію, що приймає два числа аргументами та множить їх:

+ +
function multiply(num1,num2) {
+  var result = num1 * num2;
+  return result;
+}
+ +

Спробуйте запустити функцію в консолі та протестувати з різними аргументами. Наприклад:

+ +
multiply(4,7);
+multiply(20,20);
+multiply(0.5,3);
+ +
+

Зауважте: Вираз return вказує браузеру, що потрібно повернути змінну result наприкінці роботи функції, щоб вона була доступна до використання. Це необхідно, тому що змінні, що визначені всередині функції, видимі лише в цій же функції. Це називається {{Glossary("Scope", "зоною видимості")}} змінної. (more on variable scoping.)

+
+ +

Події

+ +

Справжня інтерактивність на сайті вимагає подій. Це структури коду, що стежать за тим, що стається у браузері та запускають певні блоки коду у відповідь. Найпоширеніша подія, це click, що виконується браузером, коли ви клікаєте на щось своєю мишкою. Щоб побачити це, пропишіть наступний код у консолі а потім клацніть на цій сторінці:

+ +
document.querySelector('html').onclick = function() {
+    alert('Ouch! Stop poking me!');
+}
+ +

Є багато шляхів прив'язати подію до елемента. Тут ми обираємо {{htmlelement("HTML")}} елемент, виставляючи для події onclick на виконання безіменну функцію, яку ми хочемо запустити при натисканні.

+ +

Зауважте, що це:

+ +
document.querySelector('html').onclick = function() {};
+ +

еквівалентне цьому:

+ +
var myHTML = document.querySelector('html');
+myHTML.onclick = function() {};
+ +

Просто коротше.

+ +

Прокачаємо наш зразок сайту

+ +

Тепер, коли ми розглянули кілька принципів JavaScript, давайте додамо трохи нових крутих фішок до нашого сайту, щоб подивитись, що ми можемо з ним робити.

+ +

Додамо зміну картинок

+ +

У цій частині, ми додамо ще зображень засобами DOM API, викорстовуючи JavaScript, щоб переключатись між ними, коли хтось клікне на зображення.

+ +
    +
  1. Перш за все, знайдіть ще одне зображення, яке б ви хотіли бачити на своєму сайті. Переконайтесь, що воно має такий же розмір, як і попереднє, або максимально близько до нього за розміром.
  2. +
  3. Збережіть його у папку images .
  4. +
  5. Перейменуйте його на 'firefox2.png' (без лапок, звичайно).
  6. +
  7. Перейдіть до файлу main.js, та введіть цей шматок коду JavaScript. (Якщо ваш  зразок "hello world" досі там, видаліть його.) +
    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');
    +    }
    +}
    +
  8. +
  9. Збережіть всі файли та відкрийте index.html у браузері. Тепер, коли ви клікатимете на зображення, воно буде замінюватись іншим.
  10. +
+ +

Ви зберігаєте посилання на ваше зображення у змінній myImage. Далі, ви прив'язуєте подію onclick для цієї змінної до функції, що не має імені(анонімної). Зараз, щоразу, коли ви клікнете на цей елемент:

+ +
    +
  1. Ви поновлюєте значення атрубуту зображення src .
  2. +
  3. Використовуєте умову для перевірки, чи значення src рівне шляху до першого зображення: +
      +
    1. Якщо так, ви змінюєте значення src на шлях до другого зображення, змушуючи вже друге зображення завантажитись до елемента {{htmlelement("image")}}.
    2. +
    3. Якщо ні (значить зміни вже відбувались), значення src замінюється назад до оригінального зображення, в первинний стан.
    4. +
    +
  4. +
+ +

Персоналізоване привітання

+ +

Далі ми допишемо шматок коду, що змінить заголовок сторінки на особисте привітання, коли користувач вперше відвідує сторінку. Це повідомлення залишиться, якщо користувач покине сайт та повернеться знову - ми збережемо його засобами Web Storage API. Ми також додамо можливість змінити користувача і, відповідно, привітання, як тільки буде потрібно.

+ +
    +
  1. До index.html додамо наступний код, прямо перед елементом {{htmlelement("script")}}: + +
    <button>Change user</button>
    +
  2. +
  3. У файлі main.js, в  кінці вставте наступний код . Він отримує посилання на нову кнопку та заголовок і зберігає їх до нових відповідних змінних: +
    var myButton = document.querySelector('button');
    +var myHeading = document.querySelector('h1');
    +
  4. +
  5. Тепер додамо наступні функції, щоб налаштувати персоналізоване привітання - воно в такому стані не працюватиме, та скоро ми це виправимо: +
    function setUserName() {
    +  var myName = prompt('Please enter your name.');
    +  localStorage.setItem('name', myName);
    +  myHeading.textContent = 'Mozilla is cool, ' + myName;
    +}
    + Ця функція містить функцію prompt(), яка викликає діалогове вікно, подібно до alert(). Функція prompt(), однак, запитує в користувача дані, зберігаючи їх у відповідній змінній одразу після того як буде натиснута кнопка OK. В цьому випадку, ми питаємо в користувача його ім'я. Далі, ми звертаємось до API, що має назву localStorage, що дозволяє нам зберігати дані у браузері, а потім звертатись до них. Ми використовуємо з localStorage функцію setItem(), щоб створити та зберегти дані в 'name', та присвоїти це значення змінній myName, що міститиме дані, введені користувачем. Наприкінці, присвоюємо textContent заголовка рядок, додаючи щойно збережене користувачем ім'я.
  6. +
  7. Після цього, допишемо цей блок if ... else — ми можемо назвати його ініціалізацією, оскільки він структуруватиме логіку сторінки при запуску: +
    if(!localStorage.getItem('name')) {
    +  setUserName();
    +} else {
    +  var storedName = localStorage.getItem('name');
    +  myHeading.textContent = 'Mozilla is cool, ' + storedName;
    +}
    + Блок спочатку використовує оператор заперечення (логічне NOT, представлене "!") щоб перевірити, чи існують дані name. Якщо ні, функція setUserName() запуститься, щоб створити їх. Якщо існують (означає, що вони були створені, коли користувач минулого разу відвідував сайт), ми поновлюємо збережене ім'я за допомогою getItem() та присвоюємо заголовку textContent рядок, додаючи ім'я користувача, так само, як і у setUserName().
  8. +
  9. Для завершення, прив'яжемо подію onclick до кнопки. Коли відбудеться клік, функція setUserName() запуститься. Це дозволить змінювати ім'я користувача, коли виникне в цьому потреба, натиснувши на кнопку: +
    myButton.onclick = function() {
    +  setUserName();
    +}
    +
    +
  10. +
+ +

Тепер при, першому відвідуванні сайту, він запитає ваше ім'я, а потім відобразить персоналізоване привітання. Ви в будь-який момент можете змінити ім'я, натиснувши на кнопку. Як бонус, через те, що ім'я зберігається у localStorage, воно залишиться навіть, якщо закрити сторінку, зберігаючи персоналізоване привітання з вашим іменем!

+ +

Висновок

+ +

Якщо ви слідували всім інструкціям, під кінець у вас мало б вийти щось накшталт цього (якщо ні, то можете подивитись нашу версію тут):

+ +

+ +

Якщо ви десь застрягли, можете порівняти свою роботу з нашим завершеним зразком коду на Github.

+ +

Тут ми ледь пошкрябали велику глибу можливостей JavaScript. Якщо вам сподобалось і ви бажаєте продовжити, перейдіть на наш план вивчення JavaScript.

+ +

{{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/uk/learn/getting_started_with_the_web/publishing_your_website/index.html b/files/uk/learn/getting_started_with_the_web/publishing_your_website/index.html new file mode 100644 index 0000000000..a0d1a5e00f --- /dev/null +++ b/files/uk/learn/getting_started_with_the_web/publishing_your_website/index.html @@ -0,0 +1,111 @@ +--- +title: Публікація вашого сайту +slug: Learn/Getting_started_with_the_web/Publishing_your_website +tags: + - Веб-сервер + - Доменне ім'я + - Мова + - Початківцям + - Публікація + - Українська + - Хостинг +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")}}
+ +
+

Коли ви закінчили писати код і організували всі файли, які складають ваш проект, ви маєте викласти все це онлайн, щоб ваш веб-сайт можна було побачити. У цій статті пояснюється, як без особливих зусиль викласти простий веб-сайт онлайн. 

+
+ +

Які варіанти?

+ +

Публікація сайту є складною темою, переважно тому, що існує дуже багато шляхів як це зробити. У цій статті ми не ставимо за мету розказати про всі можливі варіанти. Натомість ми поговоримо про "плюси" і "мінуси" трьох найбільш популярних стратегій виходу в онлайн з точки зору початківців, а потім розкажемо про один із способів, який нам найбільше підходить на даному етапі. 

+ +

Хостинг і доменне ім'я

+ +

Якщо ви хочете повністю контролювати ваш опублікований веб-сайт, то вам потрібно купити:

+ + + +

Багато професійних веб-сайтів виходять онлайн таким способом. 

+ +

На додачу, вам знадобиться програма {{Glossary("FTP", "File Transfer Protocol (FTP)")}} (див. How much does it cost: software), щоб передавати ваші файли на сервер. Є багато різних програм FTP, але загалом для користування вам потрібно залогінитися на ваш веб-сервер (реєстраційні данні, наприклад, ім'я користувача, пароль, ім'я хоста, надаються хостинговою компанією). Потім програма покаже ваші локальні файли і файли на веб-сервері у двох вікнах, так що ви зможете переносити файли туди і назад:

+ +

+ +

Поради з пошуку хостингу і доменів

+ + + +

Онлайн-інструменти GitHub і Google App Engine

+ +

Деякі інструменти дозволяють вам публікувати ваш сайт онлайн:

+ + + +

На відміну від більшості хостингів, такі інструменти переважно безкоштовні, але з обмеженою кількістю функцій. 

+ +

Веб-середовища розробки (IDE), такі як Thimble

+ +

Є кілька веб-додатків, які відтворюють середовище веб-розробки онлайн, дозволяючи писати HTML, CSS і JavaScript і відображаючи оброблений результат — і все це у вкладці браузера. Ці інструменти прості у користуванні, чудово підходять для навчання і є безкоштовними (принаймні базові функції), крім того, вони хостять вашу сторінку за її унікальною адресою. Однак, базові функції доволі обмежені, і такі сервіси зазвичай не надають місця для зберігання матеріалів сайту (наприклад, зображень).

+ +

Спробуйте покористуватися сервісами нижче і виберіть, який підходить вам найбільше:

+ + + +

+ +

Публікація через GitHub

+ +

Тепер поговоримо про те, як легко опублікувати ваш сайт за допомогою GitHub Pages.

+ +
    +
  1. По-перше, зареєструйтеся на GitHub і підтвердіть вашу електронну адресу.
  2. +
  3. Далі, створіть репозиторій, у якому будуть зберігатися фаші файли.
  4. +
  5. На цій сторінці, у полі Repository name введіть username.github.io, де username це ваше ім'я користувача. Наприклад, наш друг bobsmith ввів би bobsmith.github.io.
    + Також поставте "галочку" в полі Initialize this repository with a README і потім клікніть Create repository.
  6. +
  7. Після цього, перетягніть файли вашого сайту в репозиторій і клікніть Commit changes.
    + +
    +

    Примітка: переконайтеся, що ваша папка має файл index.html.

    +
    +
  8. +
  9. +

    Тепер у браузері перейдіть за адресою username.github.io, щоб побачити ваш сайт онлайн. Наприклад, користувач з іменем chrisdavidmills має перейти на chrisdavidmills.github.io.

    + +
    +

    Примітка: публікація вашого сайту онлайн може зайняти кілька хвилин. Якщо ви не побачите його відразу, почекайте кілька хвилин і спробуйте знову. 

    +
    +
  10. +
+ +

Щоб дізнатися більше, дивіться GitHub Pages Help.

+ +

Додаткові матеріали

+ + + +

{{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")}}

diff --git a/files/uk/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html b/files/uk/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html new file mode 100644 index 0000000000..3a64823681 --- /dev/null +++ b/files/uk/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html @@ -0,0 +1,118 @@ +--- +title: Який вигляд матиме ваш сайт? +slug: Learn/Getting_started_with_the_web/What_will_your_website_look_like +tags: + - Вміст + - Дизайн + - Навчання + - Початківець + - матеріали + - планування + - шрифти +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")}}
+ +
+

В Який вигляд матиме ваш сайт? ми розглянемо, яку попередню планувальну та дизайнерську роботу потрібно зробити до того, як ви почнете писати код. Яку інформацію надаватиме сайт, які шрифти та кольори використати та що фактично робитиме веб-сторінка. 

+
+ +

Спершу планування

+ +

Перш, ніж щось робити, потрібні ідеї. Що саме ваш сайт має робити? Він може що завгодно, але для першого разу краще обрати щось простіше. Почнемо з простої веб-сторінки зі заголовком, зображенням і кількома абзацами. 

+ +

Для початку дайте відповідь на запитання:

+ +
    +
  1. Про що ваш сайт? Ви любите собак, Нью-Йорк, Пекмена?
  2. +
  3. Яку інформацію по темі ви маєте надати? Напишіть заголовок і кілька абзаців і подумайте щодо зображення для них. 
  4. +
  5. Який вигляд матиме ваш сайт у загальних простих термінах? Який колір тла? Які шрифти підійдуть: ділові, коміксні, грубі та крикливі, прості?
  6. +
+ +
+

Примітка: складні проекти вимагають детальної документації, включно з вказаними конкретно кольорами, шрифтами, відстанями між частинами контенту, стилем тексту тощо. Іноді це називається посібником зі стилю чи бренд-буком.

+
+ +

Ескіз вашого дизайну

+ +

Візьміть олівець і папір та приблизно замалюйте  вигляд вашого сайту. Для простої сторінки не варто малювати багато, але вам потрібно виробити звичку це робити. Це справді допомагає — вам не потрібно бути Ван Гогом!

+ +

+ +
+

Примітка: навіть у випадку справжніх складних сайтів команда дизайнерів починає з попередніх ескізів на папері, а вже потім робить цифрові макети у графічному редакторі чи онлайн-сервісах. 

+ +

Команди веб-розробників зазвичають мають графічного дизайнера і дизайнера по {{Glossary("ДК", "досвіду користування")}}. Графічні дизайнери відповідають за візуальну складову сайту. Дизайнери по досвіду користування — за те, як відвідувачі будуть користовуватись сайтом та взаємодіяти з ним. 

+
+ +

Вибір матеріалів

+ +

На цьому етапі починіть працювати над вмістом, який потім з'явиться на вашій веб-сторінці.

+ +

Текст

+ +

Попередньо ви вже маєте свої тексти та назви. Тримайте їх напоготові. 

+ +

Кольорова тема

+ +

Щоб вибрати колір, який вам подобається, скористайтеся Color Picker. Коли ви клацнете по кольору, ви побачите незвичну комбінацію з шести символів, на зразок #660066. Це — hex-код (від hexadecimal — шістнадцяткова системи числення), що відповідає вибраному кольору. Збережіть десь.

+ +

+ +

Зображення

+ +

Щоб вибрати зображення, пошукайте щось на Google Images.

+ +
    +
  1. Коли ви знайдете потрібне, то кляцніть по зображенню. 
  2. +
  3. Натисніть кнопку «Переглянути зображення».
  4. +
  5. На наступній сторінці, правою кнопкою миші кляцніть по зображенню, виберіть «Зберегти як...» і  десь його збережіть. Або скопіюйте веб-адресу зображення, щоб скористатись потім.
  6. +
+ +

+ +

+ +
+

Примітка: більшість зображень у мережі, включно з Google Images, захищені авторським правом. Щоб не порушити його, скористайтеся фільтром прав: 1) клацніть по Інструменти, а потім по 2) Права на використання:

+ +

+
+ +

Шрифт

+ +

Вибір шрифту:

+ +
    +
  1. Щоб знайти шрифт, який вам подобається, зайдіть на Google Fonts і погортайте сторінку. Також можете скористатися фільтром справа.
  2. +
  3. Натисніть значок "плюс" (Select this font) поруч із потрібним шрифтом.
  4. +
  5. Натисніть кнопку «* Family Selected» на панелі в низу сторінки («*» залежить від кількості вибраних шрифтів).
  6. +
  7. У спливаючому вікні побачите рядки коду. Можете скопіювати їх, щоб зберегти на потім. 
  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")}}

+ +

 

+ +

У цьому розділі

+ + + +

 

diff --git "a/files/uk/learn/getting_started_with_the_web/\321\226\320\275\321\202\320\265\321\200\320\275\320\265\321\202_\321\202\320\260_\320\262\320\265\320\261-\321\201\321\202\320\260\320\275\320\264\320\260\321\200\321\202\320\270/index.html" "b/files/uk/learn/getting_started_with_the_web/\321\226\320\275\321\202\320\265\321\200\320\275\320\265\321\202_\321\202\320\260_\320\262\320\265\320\261-\321\201\321\202\320\260\320\275\320\264\320\260\321\200\321\202\320\270/index.html" new file mode 100644 index 0000000000..c25cffdea8 --- /dev/null +++ "b/files/uk/learn/getting_started_with_the_web/\321\226\320\275\321\202\320\265\321\200\320\275\320\265\321\202_\321\202\320\260_\320\262\320\265\320\261-\321\201\321\202\320\260\320\275\320\264\320\260\321\200\321\202\320\270/index.html" @@ -0,0 +1,164 @@ +--- +title: Інтернет та веб-стандарти +slug: Learn/Getting_started_with_the_web/Інтернет_та_веб-стандарти +translation_of: Learn/Getting_started_with_the_web/The_web_and_web_standards +--- +

{{learnsidebar}}

+ +

This article provides some useful background on the Web — how it came about, what web standard technologies are, how they work together, why "web developer" is a great career to choose, and what kinds of best practices you'll learn about through the course.

+ +

Brief history of the web

+ +

We'll keep this very brief, as there are many (more) detailed accounts of the web's history out there, which we'll link to later on (also try searching for "history of the web" in your favorite search engine and see what you get, if you are interested in more detail.)

+ +

In the late 1960s, the US military developed a communication network called ARPANET. This can be considered a forerunner of the Web, as it worked on packet switching, and featured the first implementation of the TCP/IP protocol suite. These two technologies form the basis of the infrastructure that the internet is built on.

+ +

In 1980, Tim Berners-Lee (often referred to as TimBL) wrote a notebook program called ENQUIRE, which featured the concept of links between different nodes. Sound familiar?

+ +

Fast forward to 1989, and TimBL wrote Information Management: A Proposal and HyperText and CERN; these two publications together provided the background for how the web would work. They received a fair amount of interest, enough to convince TimBL's bosses to allow him to go ahead and create a global hypertext system.

+ +

By late 1990, TimBL had created all the things needed to run the first version of the web — HTTP, HTML, the first web browser, which was called WorldWideWeb, an HTTP server, and some web pages to look at.

+ +

In the next few years that followed, the web exploded, with multiple browsers being released, thousands of web servers being set up, and millions of web pages being created. OK, that's a very simple summary of what happened, but I did promise you a brief summary.

+ +

One last significant data point to share is that in 1994, TimBL founded the World Wide Web Consortium (W3C), an organization that brings together representatives from many different technology companies to work together on the creation of web technology specifications. After that other technologies followed such as CSS and JavaScript, and the web started to look more like the web we know today.

+ +

Web standards

+ +

Web standards are the technologies we use to build web sites. These standards exist as long technical documents called specifications, which detail exactly how the technology should work. These documents are not very useful for learning how to use the technologies they describe (this is why we have sites like MDN Web Docs), but instead are intended to be used by software engineers to implement these technologies (usually in web browsers).

+ +

For example, the HTML Living Standard describes exactly how HTML (all the HTML elements, and their associated APIs, and other surrounding technologies) should be implemented.

+ +

Web standards are created by standards bodies — institutions that invite groups of people from different technology companies to come together and agree on how the technologies should work in the best way to fulfill all of their use cases. The W3C is the best known web standards body, but there are others such as the WHATWG (who were responsible for the modernization of the HTML language), ECMA (who publish the standard for ECMAScript, which JavaScript is based on), Khronos (who publish technologies for 3D graphics, such as WebGL), and others.

+ +

"Open" standards

+ +

One of the key aspects of web standards, which TimBL and the W3C agreed on from the start, is that the web (and web technologies) should be free to both contribute and use, and not encumbered by patents/licensing. Therefore anyone can write the code to build a website for free, and anyone can contribute to the standards creation process, where the specs are written.

+ +

Because web technologies are created openly, in collaboration between many different companies, it means that no one company gets to control them, which is a really good thing. You wouldn't want a single company suddenly deciding to put the entire web behind a paywall, or releasing a new version of HTML that everyone has to buy to continue making web sites, or worse still, just deciding they aren't interested any more and just turning it off.

+ +

This allows the web to remain a freely-available public resource.

+ +

Don't break the web

+ +

Another phrase you'll hear around open web standards is "don't break the web" — the idea is that any new web technology that is introduced should be backwards compatible with what went before it (i.e. old web sites will still continue to work), and forwards compatible (future technologies in turn will be compatible with what we currently have). As you go through the learning material presented here, you'll start to learn how this is made possible with some very clever design and implementation work.

+ +

Being a web developer is good

+ +

The web industry is a very attractive market to enter if you are looking for a job. Recent published figures say that there are currently around 19 million web developers in the world, and that figure is set more than double in the next decade. And at the same time, there is a skill shortage in the industry — so what better time to learn web development?

+ +

It isn't all fun and games however — building web sites is a more complicated proposition than it used to be, and you'll have to put some time in to studying all the different technologies you need to use, all the techniques and best practices you need to know, and all the typical patterns you'll be called upon to implement. It'll take you a few months to really start to get into it, and then you'll need to keep learning so that your knowledge stays up-to-date with all the new tools and features that appear on the web platform, and keep practicing and refining your craft.

+ +

The only constant is change.

+ +

Does this sound hard? Don't worry — we aim to give you everything you need to know to get started, and things will get easier. Once you embrace the constant change and uncertainty of the web, you'll start to enjoy yourself. As a part of the web community, you'll have an entire web of contacts and useful material to help you, and you'll start to enjoy the creative possibilities it brings.

+ +

You're a digital creative now. Enjoy the experience, and the potential for earning a living.

+ +

Overview of modern web technologies

+ +

There are a number of technologies to learn if you want to be a front-end web developer. In this section we will describe them briefly. For a more detailed explanation of how some of them work together, read our article How the web works.

+ +

Browsers

+ +

You are probably reading these words inside a web browser in this very moment (unless you've printed it out, or are using assistive technology, such as a screenreader to read it out to you). Web browsers are the software programs people use to consume the web, and include Firefox, Chrome, Opera, Safari, and Edge.

+ +

HTTP

+ +

Hypertext Transfer Protocol, or HTTP, is a messaging protocol that allows web browsers to communicate with web servers (where web sites are stored). A typical conversation goes something like

+ +
"Hello web server. Can you give me the files I need to render bbc.co.uk"?
+
+"Sure thing web browser — here you go"
+
+[Downloads files and renders web page]
+ +

The actual syntax for HTTP messages (called requests and responses) is not that human-readable, but this gives you the basic idea.

+ +

HTML, CSS, and JavaScript

+ +

HTML, CSS, and JavaScript are the main three technologies you'll use to build a website:

+ + + +

Tooling

+ +

Once you've learned the "raw" technologies that can be used to build web pages (such as HTML, CSS, and JavaScript), you'll soon start to come across various tools that can be used to make your work easier or more efficient. Examples include:

+ + + +

Server-side languages and frameworks

+ +

HTML, CSS, and JavaScript are front-end (or client-side) languages, which means they are run by the browser to produce a website front-end that your users can use.

+ +

There are another class of languages called back-end (or server-side) languages, meaning that they are run on the server before the result is then sent to the browser to be displayed. A typical use for a server-side language is to get some data out of a database and generate some HTML to contain the data, before then sending the HTML over to the browser to display it to the user.

+ +

Example server-side languages include ASP.NET, Python, PHP, and NodeJS.

+ +

Web best practices

+ +

We have briefly talked about the technologies that you'll use to build websites. Now let's discuss the best practices you should employ to make sure you are using those technologies in the best way that you can.

+ +

When doing web development, the main cause of uncertainty comes from the fact that you don't know what combination of technology each user will use to view your web site:

+ + + +

Because you don't know exactly what your users will use, you need to design defensively — make your web site as flexible as possible, so that all of the above users can make use of it, even if they might not all get the same experience. In short, we are trying to make the web work for all, as much as possible.

+ +

You'll come across the below concepts at some point in your studies.

+ + + +

See also

+ + diff --git a/files/uk/learn/how_to_contribute/index.html b/files/uk/learn/how_to_contribute/index.html new file mode 100644 index 0000000000..9d73e3f192 --- /dev/null +++ b/files/uk/learn/how_to_contribute/index.html @@ -0,0 +1,83 @@ +--- +title: Як зробити внесок до навчальної бази MDN? +slug: Learn/How_to_contribute +translation_of: Learn/How_to_contribute +--- +
{{LearnSidebar}}
+ +
Якщо ви тут вперше або після довгих пошуків, це можливо тому що ви зацікавлені зробити власний внесок до області навчання MDN. Це гарні новини!
+ +

На цій сторінці ви знайдете все що вам потрібно для того щоб почати допомагати удосконалювати навчаний контент MDN. Є багато речей, які ви можете робити, залежно від кількості наявного часу та на якому етапі ви знаходитесь e початківець, веб розробник, або вчитель.

+ +
+

Примітка: Ви можете знайти мануал по написанню нової навчальної статті на сторінці Як написати статтю, щоб допомогти людям вивчити Веб.

+
+ +

Знайдіть конкретні завдання

+ +

Поширеним спосіб, яким люди роблять внески до навчальної бази є читання стеттей, виправлення друкарських помилок та пропозиція покращень. Ми також відаємо додавання прикладів до нашого GitHub сховища. Зв'яжіться з нами якщо ви хочете запитати що ще потрібно зробити. 

+ +

Додавання внесків це чудовий спосіб розважитися під час вивчення нових речей. Якщо ви коли-небудь відчуваєте себе загубленим або маєте запитання, не соромтесь звернутися до нас в Навчальній темі для дискусій or IRC channel (see at the bottom of this page for details). Chris Mills is the topic driver for the Learning Area — you could also try pinging him directly.

+ +

The following sections provide some general ideas of the types of tasks you can do.

+ +

I'm a beginner

+ +

That's awesome! Beginners are very important and valuable for creating and giving feedback on learning material. You have a unique perspective on these articles as a member of their target audience, which can make you an invaluable member of our team. Indeed, if you're using one of our articles to learn something and you get stuck, or find the article confusing in some way, you can either fix it or let us know about the problem so we can be sure it gets fixed.

+ +

Here are some suggested ways you can contribute:

+ +
+
Add tags to our articles (5 min)
+
Tagging MDN content is one of the easiest ways to contribute to MDN. As many of our features use tags to help present information in context, helping with tagging is a very valuable contribution. Take a look at the lists of glossary entries and learning articles without any tags to get started.
+
Read and review a glossary entry (5 min)
+
As a beginner, we need your fresh eyes looking at our content. If you find a glossary entry hard to understand, it means that entry needs to be improved. Feel free to make any changes you think are necessary. If you do not think you have the proper skill to edit the entry yourself, please bring it to our attention on our mailing list.
+
Write a new glossary entry (20 minutes)
+
This is the most effective way to learn something new. Pick a concept you want to understand, and as you learn about it, write a glossary entry about it. Explaining something to others is a great way to "cement" the knowledge in your brain, and to help you make sense of things yourself, all while helping other people. Everybody wins!
+
Read and review a learning article (2 hours)
+
This is very much like reviewing glossary entries (see above); it just takes more time, since these articles are typically quite a bit longer.
+
+ +

I'm a web developer

+ +

Fantastic! Your technical skills are just what we need to be sure we provide technically accurate content for beginners. As this specific part of MDN is dedicated to learning the Web, be sure your explanations are as simple as possible, without being so simple that they're not useful. It's often more important to be understandable than to be overly precise.

+ +
+
Read and review a glossary entry (5 min)
+
As a web developer, we need you to make sure our content is technically accurate without being too pedantic. Feel free to make any changes you think are necessary. If you want to discuss the content before editing, ping us on our mailing list or IRC channel.
+
Write a new glossary entry (20 minutes)
+
Clarifying technical jargon is a very good way to learn and be both technically accurate and simple. Beginners will thank you for that. We have many undefined terms which need your attention. Pick one and you're good to go.
+
Read and review a learning article (2 hours)
+
This is the same thing as reviewing a glossary entry (see above); it just takes a bit more time as those articles are quite a bit longer.
+
Write a new learning article (4 hours or more)
+
MDN is lacking simple straightforward articles about using web technologies (HTML, CSS, JavaScript, etc). We also have old content on MDN that deserves to be reviewed and reshaped. Push your skills to the limit to make web technologies usable even by beginners.
+
Create exercises, code samples or interactive learning tools (? hours)
+
All our learning articles require what we call "active learning" materials, because people learn best by doing something themselves. Such materials are exercises or interactive content that help a user to apply and manipulate the concepts detailed in an article. There are many possible ways to make active learning content, from creating code samples with JSFiddle or similar, to building fully hackable interactive content with Thimble. Unleash your creativity!
+
+ +

I'm a teacher

+ +

MDN has a long history of technical excellence, but we lack depth of understanding of the best way to teach concepts to newcomers. This is where we need you, as a teacher or educator. You can help us ensure that our materials provide a good, practical educational track for our readers.

+ +
+
Read and review a glossary entry (15 min)
+
Check out a glossary entry and feel free to make any changes you think are necessary. If you want to discuss the content before editing, ping us on our mailing list or IRC channel.
+
Write a new glossary entry (1 hour)
+
Clear, simple definitions of terms and basic overviews of concepts in the glossary are critical in meeting beginners' needs. Your experience as an educator can help create excellent glossary entries; we have many undefined terms which need your attention. Pick one and go for it.
+
Add illustrations and/or schematics to articles (1 hour)
+
As you might know, illustrations are an invaluable part of any learning content. This is something we often lack on MDN and your skills can make a difference in that area. Check out the articles that lack illustrative content and pick one you'd like to create graphics for.
+
Read and review a learning article (2 hours)
+
This is similar to reviewing glossary entries (see above), but it requires more time since the articles are typically quite a bit longer.
+
Write a new learning article (4 hours)
+
We need simple, straightforward articles about the Web ecosystem and other functional topics around it. Since these learning articles need to be educational rather than trying to literally cover everything there is to know, your experience in knowing what to cover and how will be a great asset.
+
Create exercises, quizzes or interactive learning tools (? hours)
+
All our learning articles require "active learning" materials. Such materials are exercises or interactive content which help a user learn to use and expand upon the concepts detailed in an article. There are lots of things you can do here, from creating quizzes to building fully hackable interactive content with Thimble. Unleash your creativity!
+
Create learning pathways (? hours)
+
In order to provide progressive and comprehensible tutorials, we need to shape our content into pathways. It's a way to gather existing content and figure out what is missing.
+
+ +

See also

+ + diff --git a/files/uk/learn/html/forms/index.html b/files/uk/learn/html/forms/index.html new file mode 100644 index 0000000000..be1e8bd595 --- /dev/null +++ b/files/uk/learn/html/forms/index.html @@ -0,0 +1,77 @@ +--- +title: Веб-форми +slug: Learn/HTML/Forms +translation_of: Learn/Forms +--- +
{{LearnSidebar}}
+ +

Цей модуль містить низку статей, що допоможуть Вам освоїти форми в  HTML. HTML форми  дуже потужний інструмент для взаємодії з користувачами, хоча з історичних та технічних проблем є не завжди очевидним, як повністю використовувати їхній потенціал.  В цьому путівнику ми розкриємо усі аспекти HTML форм, починаючи від структури до стилів, від обробки даних до віджетів користувачів.

+ +

Передумови

+ +

Перед початком цього модуля Вам необхідно щонайменше пройти Вступ до HTML.

+ +
+

Нотатка: Якщо Ви працюєте на компьютері/планшеті/іншому пристрої на якому Ви не маєте можливості створити власні файли, Ви можете спробувати онлайн редактори для написання коду такі як JSBin чи Thimble.

+
+ +

Основні інструкції

+ +

В наступних посібниках Ви зможете вивчити основи HTML форм і пізніше освоїти дещо складніші теми.

+ +

Ваша перша HTML форма

+ +

Перша стаття з нашої серії надасть Вам необхідний досвід в створенні HTML  форми, включаючи проектування простої форми, реалізацїю її використовуючи правильні HTML елементи, додавання деяких дуже простих стілів за допомогою CSS  і відправлення даних на сервер.

+ +

Як структурувати HTML форму

+ +

Спираючись на основи, тепер ми більш детально поглянемо на елементи, які використовуються для забезпечення структури і значення різних частин форми.

+ +
+
Рідні віджети форми
+
+
Тепер ми поглянемо на функціональність різних віджетів форм більш детально, розглянувши які налаштування доступні для одержання різних видів інформації.
+
+
Надсилання даних форми
+
В цій статті розглянемо, що відбувається, коли корисувач надсилає форму — куди надходить інформація, і як ми її обробляємо коли вона туди потрапляє? Ми також розглянемо деякі проблеми безпеки, пов'язані з надсиланням даних форми.
+
Підтвердження даних форми
+
Надсилання даних недостатньо — нам також потрібно впевнитися, що дані, надані користувачем у формі, коректні для їх успішної подальшої обробки і вони не нашкодять нашій програмі. Ми також хочемо допомогти нашим користувачам заповнити наші форми правильно і не розчаруватися під час спроби використання наших додатків. Відправлення форми забезпечує виконання поставлених перед нами цілей - ця стання донесе Вам те, що Ви маєте знати.
+
+ +

Розширені інструкції

+ +

Ці інструкції дозволять поглянути на більш розширені варіанти форм, які Ви знайдете корисними після освоєння основ застосування форм.

+ +
+
Як створювати користувацькі віджети форм
+
Ви стикнетесь з випадками, в яких стандартні віджети форм не зможуть забезпечити Вам всього, чого Ви потребуєте через невідповідний стиль чи недостатню функціональність. В таких випадках Вам потрібно буде створити власний віджет форми використовуючи чистий HTML. У цій статті пояснюється як Ви можете зробити це та що потрібно при цьому знати із практичними прикладами.
+
Надсилання форми використовуючи JavaScript
+
Ця стання покаже Вам шляхиThis article looks at ways to use a form to assemble an HTTP request and send it via custom JavaScript, rather than standard form submission. It also looks at why you'd want to do this, and the implications of doing so. (See also Using FormData objects.)
+
HTML forms in legacy browsers
+
Article covering feature detection, etc. This should be redirected to the cross browser testing module, as the same stuff is covered better there.
+
HTML5 form updates
+
This article provides a reference to the new additions we saw added to HTML forms by the HTML5 spec.
+
+ +

Form styling guides

+ +

These guides to styling forms with CSS really belong in the CSS Learning Area topic, but we are keeping them here for now until we find the time to move them.

+ +
+
Styling HTML forms
+
This article provides an introduction to styling forms with CSS, including all the basics you might need to know for basic styling tasks.
+
Advanced styling for HTML forms
+
Here we look at some more advanced form styling techniques that need to be used when trying to deal with some of the more difficult-to-style elements.
+
Property compatibility table for form widgets
+
This last article provides a handy reference allowing you to look up what CSS properties are compatible with what form elements.
+
+ +

Assessments

+ +

TBD

+ +

See also

+ + diff --git a/files/uk/learn/html/forms/your_first_form/index.html b/files/uk/learn/html/forms/your_first_form/index.html new file mode 100644 index 0000000000..e34ac6a346 --- /dev/null +++ b/files/uk/learn/html/forms/your_first_form/index.html @@ -0,0 +1,298 @@ +--- +title: Your first form +slug: Learn/HTML/Forms/Your_first_form +translation_of: Learn/Forms/Your_first_form +--- +
{{LearnSidebar}}{{NextMenu("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms")}}
+ +

Першa стаття в нашій серії допоможе вам у створенні власної першої інтернет-форми, включаючи розробку простої форми, реалізуючи її за допомогою використання елементів керування формою в HTML і інших HTML елементів, добавляючи деякі дуже прості стилі в CSS, і обписуючи як дані надсилаються на сервер. В цьому модулі ми розгорнемо кожну з вищенаведених тем.

+ + + + + + + + + + + + +
Вимоги:Загальна комп'ютерна грамотність, і базове розуміння HTML.
Мета:Зрозуміти, що таке інтернет-форми, для чого вони використовується, як обдумувати їхнє оформлення, і основні HTML елементи, які потрібні в нескладних випадках
+ +

Що таке інтернет-форми?

+ +

Web forms are one of the main points of interaction between a user and a web site or application. Forms allow users to enter data, which is generally sent to a web server for processing and storage (see Sending form data later in the module), or used on the client-side to immediately update the interface in some way (for example, add another item to a list, or show or hide a UI feature).

+ +

A web form's HTML is made up of one or more form controls (sometimes called widgets), plus some additional elements to help structure the overall form — they are often referred to as HTML forms. The controls can be single or multi-line text fields, dropdown boxes, buttons, checkboxes, or radio buttons, and are mostly created using the {{htmlelement("input")}} element, although there are some other elements to learn about too.

+ +

Form controls can also be programmed to enforce specific formats or values to be entered (form validation), and paired with text labels that describe their purpose to both sighted and blind users.

+ +

Designing your form

+ +

Before starting to code, it's always better to step back and take the time to think about your form. Designing a quick mockup will help you to define the right set of data you want to ask your user to enter. From a user experience (UX) point of view, it's important to remember that the bigger your form, the more you risk frustrating people and losing users. Keep it simple and stay focused: ask only for the data you absolutely need.

+ +

Designing forms is an important step when you are building a site or application. It's beyond the scope of this article to cover the user experience of forms, but if you want to dig into that topic you should read the following articles:

+ + + +

In this article, we'll build a simple contact form. Let's make a rough sketch.

+ +

The form to build, roughly sketch

+ +

Our form will contain three text fields and one button. We are asking the user for their name, their e-mail and the message they want to send. Hitting the button will send their data to a web server.

+ +

Active learning: Implementing our form HTML

+ +

Ok, let's have a go at creating the HTML for our form. We will use the following HTML elements: {{HTMLelement("form")}}, {{HTMLelement("label")}}, {{HTMLelement("input")}}, {{HTMLelement("textarea")}}, and {{HTMLelement("button")}}.

+ +

Before you go any further, make a local copy of our simple HTML template — you'll enter your form HTML into here.

+ +

The {{HTMLelement("form")}} element

+ +

All forms start with a {{HTMLelement("form")}} element, like this:

+ +
<form action="/my-handling-form-page" method="post">
+
+</form>
+ +

This element formally defines a form. It's a container element like a {{HTMLelement("section")}} or {{HTMLelement("footer")}} element, but specifically for containing forms; it also supports some specific attributes to configure the way the form behaves. All of its attributes are optional, but it's standard practice to always set at least the action and method attributes:

+ + + +
+

Note: We'll look at how those attributes work in our Sending form data article later on.

+
+ +

For now, add the above {{htmlelement("form")}} element into your HTML {{htmlelement("body")}}.

+ +

The {{HTMLelement("label")}}, {{HTMLelement("input")}}, and {{HTMLelement("textarea")}} elements

+ +

Our contact form is not complex: the data entry portion contains three text fields, each with a corresponding {{HTMLelement("label")}}:

+ + + +

In terms of HTML code we need something like the following to implement these form widgets:

+ +
<form action="/my-handling-form-page" method="post">
+ <ul>
+  <li>
+    <label for="name">Name:</label>
+    <input type="text" id="name" name="user_name">
+  </li>
+  <li>
+    <label for="mail">E-mail:</label>
+    <input type="email" id="mail" name="user_mail">
+  </li>
+  <li>
+    <label for="msg">Message:</label>
+    <textarea id="msg" name="user_message"></textarea>
+  </li>
+ </ul>
+</form>
+ +

Update your form code to look like the above.

+ +

The {{HTMLelement("li")}} elements are there to conveniently structure our code and make styling easier (see later in the article). For usability and accessibility, we include an explicit label for each form control. Note the use of the for attribute on all {{HTMLelement("label")}} elements, which takes as its value the id of the form control with which it is associated — this is how you associate a form with its label.

+ +

There is great benefit to doing this — it associates the label with the form control, enabling mouse, trackpad, and touch device users to click on the label to activate the corresponding control, and it also provides an accessible name for screen readers to read out to their users. You'll find further details of form labels in How to structure a web form.

+ +

On the {{HTMLelement("input")}} element, the most important attribute is the type attribute. This attribute is extremely important because it defines the way the {{HTMLelement("input")}} element appears and behaves. You'll find more about this in the Basic native form controls article later on.

+ + + +

Last but not least, note the syntax of <input> vs. <textarea></textarea>. This is one of the oddities of HTML. The <input> tag is an empty element, meaning that it doesn't need a closing tag. {{HTMLElement("textarea")}} is not an empty element, meaning it should be closed it with the proper ending tag. This has an impact on a specific feature of forms: the way you define the default value. To define the default value of an {{HTMLElement("input")}} element you have to use the value attribute like this:

+ +
<input type="text" value="by default this element is filled with this text">
+ +

On the other hand,  if you want to define a default value for a {{HTMLElement("textarea")}}, you put it between the opening and closing tags of the {{HTMLElement("textarea")}} element, like this:

+ +
<textarea>
+by default this element is filled with this text
+</textarea>
+ +

The {{HTMLelement("button")}} element

+ +

The markup for our form is almost complete; we just need to add a button to allow the user to send, or "submit", their data once they have filled out the form. This is done by using the {{HTMLelement("button")}} element; add the following just above the closing </form> tag:

+ +
<li class="button">
+  <button type="submit">Send your message</button>
+</li>
+ +

The {{htmlelement("button")}} element also accepts a type attribute — this accepts one of three values: submit, reset, or button.

+ + + +
+

Note: You can also use the {{HTMLElement("input")}} element with the corresponding type to produce a button, for example <input type="submit">. The main advantage of the {{HTMLelement("button")}} element is that the {{HTMLelement("input")}} element only allows plain text in its label whereas the {{HTMLelement("button")}} element allows full HTML content, allowing more complex, creative button content.

+
+ +

Basic form styling

+ +

Now that you have finished writing your form's HTML code, try saving it and looking at it in a browser. At the moment, you'll see that it looks rather ugly.

+ +
+

Note: If you don't think you've got the HTML code right, try comparing it with our finished example — see first-form.html (also see it live).

+
+ +

Forms are notoriously tricky to style nicely. It is beyond the scope of this article to teach you form styling in detail, so for the moment we will just get you to add some CSS to make it look OK.

+ +

First of all, add a {{htmlelement("style")}} element to your page, inside your HTML head. It should look like so:

+ +
<style>
+
+</style>
+ +

Inside the style tags, add the following CSS:

+ +
form {
+  /* Center the form on the page */
+  margin: 0 auto;
+  width: 400px;
+  /* Form outline */
+  padding: 1em;
+  border: 1px solid #CCC;
+  border-radius: 1em;
+}
+
+ul {
+  list-style: none;
+  padding: 0;
+  margin: 0;
+}
+
+form li + li {
+  margin-top: 1em;
+}
+
+label {
+  /* Uniform size & alignment */
+  display: inline-block;
+  width: 90px;
+  text-align: right;
+}
+
+input,
+textarea {
+  /* To make sure that all text fields have the same font settings
+     By default, textareas have a monospace font */
+  font: 1em sans-serif;
+
+  /* Uniform text field size */
+  width: 300px;
+  box-sizing: border-box;
+
+  /* Match form field borders */
+  border: 1px solid #999;
+}
+
+input:focus,
+textarea:focus {
+  /* Additional highlight for focused elements */
+  border-color: #000;
+}
+
+textarea {
+  /* Align multiline text fields with their labels */
+  vertical-align: top;
+
+  /* Provide space to type some text */
+  height: 5em;
+}
+
+.button {
+  /* Align buttons with the text fields */
+  padding-left: 90px; /* same size as the label elements */
+}
+
+button {
+  /* This extra margin represent roughly the same space as the space
+     between the labels and their text fields */
+  margin-left: .5em;
+}
+ +

Save and reload, and you'll see that your form should look much less ugly.

+ +
+

Note: You can find our version on GitHub at first-form-styled.html (also see it live).

+
+ +

Sending form data to your web server

+ +

The last part, and perhaps the trickiest, is to handle form data on the server side. The {{HTMLelement("form")}} element defines where and how to send the data thanks to the action and method attributes.

+ +

We provide a name to each form control. The names are important on both the client- and server-side; they tell the browser which name to give each piece of data and, on the server side, they let the server handle each piece of data by name. The form data is sent to the server as name/value pairs.

+ +

To name the data in a form you need to use the name attribute on each form widget that will collect a specific piece of data. Let's look at some of our form code again:

+ +
<form action="/my-handling-form-page" method="post">
+ <ul>
+  <li>
+    <label for="name">Name:</label>
+    <input type="text" id="name" name="user_name" />
+  </li>
+  <li>
+    <label for="mail">E-mail:</label>
+    <input type="email" id="mail" name="user_email" />
+  </li>
+  <li>
+    <label for="msg">Message:</label>
+    <textarea id="msg" name="user_message"></textarea>
+  </li>
+
+  ...
+
+ +

In our example, the form will send 3 pieces of data named "user_name", "user_email", and "user_message". That data will be sent to the URL "/my-handling-form-page" using the HTTP POST method.

+ +

On the server side, the script at the URL "/my-handling-form-page" will receive the data as a list of 3 key/value items contained in the HTTP request. The way this script will handle that data is up to you. Each server-side language (PHP, Python, Ruby, Java, C#, etc.) has its own mechanism of handling form data. It's beyond the scope of this guide to go deeply into that subject, but if you want to know more, we have provided some examples in our Sending form data article later on.

+ +

Summary

+ +

Congratulations, you've built your first web form. It looks like this live:

+ +

{{ EmbedLiveSample('A_simple_form', '100%', '240', '', 'Learn/Forms/Your_first_form/Example') }}

+ +

That's only the beginning, however — now it's time to take a deeper look. Forms have way more power than what we saw here and the other articles in this module will help you to master the rest.

+ +

{{NextMenu("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms")}}

+ +

In this module

+ + + +

Advanced Topics

+ + diff --git a/files/uk/learn/html/index.html b/files/uk/learn/html/index.html new file mode 100644 index 0000000000..708f04d792 --- /dev/null +++ b/files/uk/learn/html/index.html @@ -0,0 +1,54 @@ +--- +title: HTML +slug: Learn/HTML +translation_of: Learn/HTML +--- +
{{LearnSidebar}}
+ +

Щоб створювати сайти, спершу слід вивчити {{Glossary('HTML')}} — це фундаментальна технологія, за допомогою якої створюється структура веб-сторінки. HTML використовується, щоб вказати тип вмісту на сторінці: абзац, список, заголовок, посилання, зображення, мультимедіа-плеєр, формуляр або один з багатьох інших елементів.

+ +

Шлях навчання

+ +

Найкраще розпочати вивчення веб-розробки з HTML. Почніть зі Вступу до HTML. Після цього можна розпочати вивчення більш складних тем, наприклад:

+ + + +

Для початку навчання необхідно мати щонайменше базові знання комп'ютера та досвід в користуванні інтернетом (перегляд сайтів, відео та аудіо). Також потрібно мати основні робочі інструменти описані в розділі Встановлення основного програмного забезпечення та знати, як створювати та керувати файлами, це описано в розділі Робота з файлами. Ці два розділи знаходяться в модулі для початківців Початок роботи з WEB.

+ +

Перед вивченням рекомендується ознайомится зі статтею Початок роботи з WEB, але це необов'язково. Багато матеріалу зі статті Основи HTML більш детально охоплює модуль Вступ до HTML.

+ +

Модулі

+ +

Ця тема містить модулі, які рознашовані в порядку вивчення. Слід розпочати навчання від першого з них:

+ +
+
Вступ до HTML
+
Цей модуль надає базові знання для подальщої роботи. Він знайомить з важливими поняттями синтаксису та вчить застосовувати код HTML до тексту, створювати посилання, та створювати структуру сторінки за допомогою HTML.
+
Вставки мультимедіа
+
Цей модуль навчить використовувати HTML для вставки мультимедіа-файлів на вашу сторінку. Ви навчитеся вставляти на вашу сторінку зображення, відео, аудіо та навіть цілі сторінки.
+
Таблиці HTML
+
Відображення табличних даних на сторінці зрозумілим, {{glossary("Accessibility", "доступним")}} шляхом, може стати викликом. Цей модуль охоплює основи розмітки таблиць, а також більш складні понняття, наприклад, додавання заголовків колонок.
+
Формуляри HTML
+
Формуляри є дуже важливою частиною Web — вони забезпечують переважну частину функціональності для взаємодії з веб-сайтом, наприклад, реєстрація чи вхід, залишення коментаря, покупка продуктів та інше. Цей модуль навчить вас створювати формуляри, якими користується клієнт.
+
+ +

Вирішення основних проблем HTML

+ +

Вирішення основних проблем HTML містить посилання на секції, в яких пояснюється як використовувати HTML для вирішення основних проблем пристворенні веб-сторінки: робота з заголовками, додавання зображень чи відео, підкреслення вмісту, ствонення простого формуляру тощо.

+ +

Дивіться також

+ +
+
+
     
+
     Веб форми
+
Цей модуль містить низку статей, які допоможуть вам засвоїти основи веб-форм. Веб-форми - це дуже потужний інструмент для взаємодії з користувачами - найчастіше вони використовуються для збору даних від користувачів або дозволяють їм контролювати користувальницький інтерфейс. Однак з історичних та технічних причин не завжди очевидно, як використати їх на повний потенціал. Ми охопимо всі основні аспекти веб-форм, включаючи розміщення їх структури HTML, стилі управління формами, перевірку даних форми та подання даних на сервер.
+
+
     HTML (HyperText Markup Language) на MDN
+
Основа документації HTML на MDN. Вона містить детальні описи елементу (тега) та його атрибути — якщо ви хочете знати, які атрибути та значення може мати елемент, вам варто ознайомитися з цим розділом.
+
+
diff --git a/files/uk/learn/html/introduction_to_html/creating_hyperlinks/index.html b/files/uk/learn/html/introduction_to_html/creating_hyperlinks/index.html new file mode 100644 index 0000000000..4d333ac64a --- /dev/null +++ b/files/uk/learn/html/introduction_to_html/creating_hyperlinks/index.html @@ -0,0 +1,322 @@ +--- +title: Створення гіперпосилань +slug: Learn/HTML/Introduction_to_HTML/Creating_hyperlinks +translation_of: Learn/HTML/Introduction_to_HTML/Creating_hyperlinks +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}
+ +

Гіперпосилання дійсно важливі — це те що робить Інтернет інтернетом. Ця стаття показує необхідний синтаксис для створення гіперпосилання а також практику їхнього використання. 

+ + + + + + + + + + + + +
Передумови:Базове знання HTML (Getting started with HTML). Форматування тексту (HTML text fundamentals).
Мета:Вивчити як користуватись гіперпосиланнями ефективно і з'єднювати декілька файлів разом.
+ +

Що таке гіперпосилання?

+ +

Гіперпосилання це одне з найбільш вражаючих інновацій, що Інтернет може нам запропонувати. Хоча, вони були ще з самогу початку Інтернету, але вони це те що робить Інтернет Інтернетом — вони дозволяють зв'язати наші документи з будь-яким іншим документом (або іншим ресурсом), ми також можем зробити посилання на конкретні частини документу, і можемо зробити наші документи, (сайти, ресурси) доступними використовуючи просту адресу (на відміну від звичайних програм, які повинні буди встановлені і налаштовані). Практично будь-який контент може бути перетворений в посилання. Клік на таке посилання переведе користувача на іншу веб-адресу ({{glossary("URL")}}).

+ +
+

Примітка: URL може посилатись на HTML файли, текстові файли, зображення, текстові документи, відео і аудіо файли, та будь-які інші ресурси які можуть знаходитись в Інтернеті. Якщо браузер не знає як відобразити або опрацювати файл, він запитає у користувача чи він хоче відкрити файл (в такому випадку процес відкриття і обробки файлу передається до відповідної програми) або завантажити файл (в такому випадку користувач може повернутись до завантаженого файлу пізніше.)

+
+ +

Домашня сторінка BBC, для прикладу, містить велику кількість посилань нетільки на новини, але також на різні розділи сайту (навігація), сторінки логіну та реєстрації (інструменти користувача) та інші.

+ +

frontpage of bbc.co.uk, showing many news items, and navigation menu functionality

+ + + +

A basic link is created by wrapping the text (or other content, see {{anch("Block level links")}}) you want to turn into a link inside an {{htmlelement("a")}} element, and giving it an {{htmlattrxref("href", "a")}} attribute (also known as a Hypertext Reference , or target) that will contain the web address you want the link to point to.

+ +
<p>I'm creating a link to
+<a href="https://www.mozilla.org/en-US/">the Mozilla homepage</a>.
+</p>
+ +

This gives us the following result:

+ +

I'm creating a link to the Mozilla homepage.

+ +

Adding supporting information with the title attribute

+ +

Another attribute you may want to add to your links is title; this is intended to contain supplementary useful information about the link, such as what kind of information the page contains, or things to be aware of. For example:

+ +
<p>I'm creating a link to
+<a href="https://www.mozilla.org/en-US/"
+   title="The best place to find more information about Mozilla's
+          mission and how to contribute">the Mozilla homepage</a>.
+</p>
+ +

This gives us the following result (the title will come up as a tooltip when the link is hovered over):

+ +

I'm creating a link to the Mozilla homepage.

+ +
+

Note: A link title is only revealed on mouse hover, which means that people relying on keyboard controls to navigate web pages will have difficulty accessing title information. If a title's information is truly important to the usability of page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.

+
+ + + +

Active learning time: we'd like you to create an HTML document using your local code editor (our getting started template would do just fine.)

+ + + + + +

As mentioned before, you can turn just about any content into a link, even block level elements. If you had an image you wanted to turn into a link, you could just put the image between <a></a> tags.

+ +
<a href="https://www.mozilla.org/en-US/">
+  <img src="mozilla-image.png" alt="mozilla logo that links to the mozilla homepage">
+</a>
+ +
+

Note: You'll find out a lot more about using images on the Web in a future article.

+
+ +

A quick primer on URLs and paths

+ +

To fully understand link targets, you need to understand URLs and file paths. This section gives you the information you need to achieve this.

+ +

A URL, or Uniform Resource Locator is simply a string of text that defines where something is located on the Web. For example Mozilla's English homepage is located at https://www.mozilla.org/en-US/.

+ +

URLs use paths to find files. Paths specify where in the filesystem the file you are interested in is located. Let's look at a simple example of a directory structure (see the creating-hyperlinks directory.)

+ +

A simple directory structure. The parent directory is called creating-hyperlinks and contains two files called index.html and contacts.html, and two directories called projects and pdfs, which contain an index.html and a project-brief.pdf file, respectively

+ +

The root of this directory structure is called creating-hyperlinks. When working locally with a web site, you will have one directory that the whole site goes inside. Inside the root, we have an index.html file and a contacts.html. In a real website, index.html would be our home page or landing page (a web page that serves as the entry point for a website or a particular section of a website.).

+ +

There are also two directories inside our root — pdfs and projects. These each have a single file inside them — a PDF (project-brief.pdf) and an index.html file, respectively. Note how you can quite happily have two index.html files in one project as long as they are in different locations in the filesystem. Many web sites do. The second index.html would perhaps be the main landing page for project-related information.

+ + + +
+

Note: You can combine multiple instances of these features into complex URLs, if needed, e.g. ../../../complex/path/to/my/file.html.

+
+ +

Document fragments

+ +

It is possible to link to a specific part of an HTML document (known as a document fragment), rather than just to the top of the document. To do this you first have to assign an {{htmlattrxref("id")}} attribute to the element you want to link to. It normally makes sense to link to a specific heading, so this would look something like the following:

+ +
<h2 id="Mailing_address">Mailing address</h2>
+ +

Then to link to that specific id, you'd include it at the end of the URL, preceded by a hash/pound symbol, for example:

+ +
<p>Want to write us a letter? Use our <a href="contacts.html#Mailing_address">mailing address</a>.</p>
+ +

You can even use the document fragment reference on its own to link to another part of the same document:

+ +
<p>The <a href="#Mailing_address">company mailing address</a> can be found at the bottom of this page.</p>
+ +

Absolute versus relative URLs

+ +

Two terms you'll come across on the Web are absolute URL and relative URL:

+ +

absolute URL: Points to a location defined by its absolute location on the web, including {{glossary("protocol")}} and {{glossary("domain name")}}. So for example, if an index.html page is uploaded to a directory called projects that sits inside the root of a web server, and the web site's domain is http://www.example.com, the page would be available at http://www.example.com/projects/index.html (or even just http://www.example.com/projects/, as most web servers just look for a landing page such as index.html to load if it is not specified in the URL.)

+ +

An absolute URL will always point to the same location, no matter where it is used.

+ +

relative URL: Points to a location that is relative to the file you are linking from, more like what we looked at in the previous section. For example, if we wanted to link from our example file at http://www.example.com/projects/index.html to a PDF file in the same directory, the URL would just be the filename — e.g. project-brief.pdf — no extra information needed. If the PDF was available in a subdirectory inside projects called pdfs, the relative link would be pdfs/project-brief.pdf (the equivalent absolute URL would be http://www.example.com/projects/pdfs/project-brief.pdf.)

+ +

A relative URL will point to different places depending on where the file it is used inside is located — for example if we moved our index.html file out of the projects directory and into the root of the web site (the top level, not in any directories), the pdfs/project-brief.pdf relative URL link inside it would now point to a file located at http://www.example.com/pdfs/project-brief.pdf, not a file located at http://www.example.com/projects/pdfs/project-brief.pdf.

+ +

Of course, the location of the project-brief.pdf file and pdfs folder won't suddenly change because you moved the index.html file — this would make your link point to the wrong place, so it wouldn't work if clicked on. You need to be careful!

+ + + +

There are some best practices to follow when writing links. Let's look at these now.

+ + + + + +

It's easy to throw links up on your page. That's not enough. We need to make our links accessible to all readers, regardless of their current context and which tools they prefer. For example:

+ + + +

Let's look at a specific example:

+ +

Good link text: Download Firefox

+ +
<p><a href="https://firefox.com/">
+  Download Firefox
+</a></p>
+ +

Bad link text: Click here to download Firefox

+ +
<p><a href="https://firefox.com/">
+  Click here
+</a>
+to download Firefox</p>
+
+ +

Other tips:

+ + + + + +

From the description above, you might think that it is a good idea to just use absolute links all the time; after all, they don't break when a page is moved like relative links. However, you should use relative links wherever possible when linking to other locations within the same website (when linking to another website, you will need to use an absolute link):

+ + + +

Linking to non-HTML resources — leave clear signposts

+ +

When linking to a resource that will be downloaded (like a PDF or Word document) or streamed (like video or audio) or has another potentially unexpected effect (opens a popup window, or loads a Flash movie), you should add clear wording to reduce any confusion. It can be quite annoying for example:

+ + + +

Let's look at some examples, to see what kind of text can be used here:

+ +
<p><a href="http://www.example.com/large-report.pdf">
+  Download the sales report (PDF, 10MB)
+</a></p>
+
+<p><a href="http://www.example.com/video-stream/" target="_blank">
+  Watch the video (stream opens in separate tab, HD quality)
+</a></p>
+
+<p><a href="http://www.example.com/car-game">
+  Play the car game (requires Flash)
+</a></p>
+ +

Use the download attribute when linking to a download

+ +

When you are linking to a resource that is to be downloaded rather than opened in the browser, you can use the download attribute to provide a default save filename. Here's an example with a download link to the latest Windows version of Firefox:

+ +
<a href="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=en-US"
+   download="firefox-latest-64bit-installer.exe">
+  Download Latest Firefox for Windows (64-bit) (English, US)
+</a>
+ +

Active learning: creating a navigation menu

+ +

For this exercise, we'd like you to link some pages together with a navigation menu to create a multi-page website. This is one common way in which a website is created — the same page structure is used on every page, including the same navigation menu, so when links are clicked it gives the impression that you are staying in the same place, and different content is being brought up.

+ +

You'll need to make local copies of the following four pages, all in the same directory (see also the navigation-menu-start directory for a full file listing):

+ + + +

You should:

+ +
    +
  1. Add an unordered list in the indicated place on one page, containing the names of the pages to link to. A navigation menu is usually just a list of links, so this is semantically ok.
  2. +
  3. Turn each page name into a link to that page.
  4. +
  5. Copy the navigation menu across to each page.
  6. +
  7. On each page, remove just the link to that same page — it is confusing and pointless for a page to include a link to itself, and the lack of a link acts a good visual reminder of what page you are currently on.
  8. +
+ +

The finished example should end up looking something like this:

+ +

An example of a simple HTML navigation menu, with home, pictures, projects, and social menu items

+ +
+

Note: If you get stuck, or are not sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer.

+
+ + + +

It is possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. This is done using the {{HTMLElement("a")}} element and the mailto: URL scheme.

+ +

In its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. For example:

+ +
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>
+
+ +

This results in a link that looks like this: Send email to nowhere.

+ +

In fact, the email address is even optional. If you leave it out (that is, your {{htmlattrxref("href", "a")}} is simply "mailto:"), a new outgoing email window will be opened by the user's mail client that has no destination address specified yet. This is often useful as "Share" links that users can click to send an email to an address of their choosing.

+ +

Specifying details

+ +

In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term.

+ +

Here's an example that includes a cc, bcc, subject and body:

+ +
<a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email">
+  Send mail with cc, bcc, subject and body
+</a>
+ +
+

Note: The values of each field must be URL-encoded, that is with non-printing characters (invisible characters like tabs, carriage returns, and page breaks) and spaces percent-escaped. Also note the use of the question mark (?) to separate the main URL from the field values, and ampersands (&) to separate each field in the mailto: URL. This is standard URL query notation. Read The GET method to understand what URL query notation is more comonly used for.

+
+ +

Here are a few other sample mailto URLs:

+ + + +

Summary

+ +

That's it for links, for now anyway! You'll return to links later on in the course when you start to look at styling them. Next up for HTML, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful — Advanced text formatting is your next stop.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}

+ +

In this module

+ + diff --git a/files/uk/learn/html/introduction_to_html/debugging_html/index.html b/files/uk/learn/html/introduction_to_html/debugging_html/index.html new file mode 100644 index 0000000000..1c6e107e7b --- /dev/null +++ b/files/uk/learn/html/introduction_to_html/debugging_html/index.html @@ -0,0 +1,186 @@ +--- +title: Дебаґінг HTML +slug: Learn/HTML/Introduction_to_HTML/Debugging_HTML +tags: + - HTML + - Розмітка + - валідатор + - веб-сторінок + - виправлення + - дебаґінг + - для початківців + - кодинг + - перевірка + - помилок + - уроки + - як перевірити +translation_of: Learn/HTML/Introduction_to_HTML/Debugging_HTML +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
+ +

Написати HTML добре, але що, якщо щось піде не так, і ви не можете з'ясувати, де помилка в коді? Ця стаття представить вам деякі інструменти, які допоможуть вам знайти та виправити помилки в HTML.

+ + + + + + + + + + + + +
Передумови:Знайомство з HTML, як наведено в прикладі Початок роботи з HTML, Основи HTML та Створення гіперпосилань.
Мета:Дізнатись основи використання інструментів налагодження (дебаґінга), щоб знайти проблеми в HTML.
+ +

Дебаґінг не страшний

+ +

Коли ви пишете код певного виду, все, як правило, добре, доки не настає страшний момент, коли виникла помилка - ви зробили щось не так, тому ваш код не працює - або взагалі, або не зовсім так, як ви хотіли. Наприклад, наведене нижче показує помилку при спробі {{glossary("compile")}} просту програму, написану на мові "Rust".

+ +

A console window showing the result of trying to compile a rust program with a missing quote around a string in a print statement. The error message reported is error: unterminated double quote string. Тут повідомлення про помилку досить легко зрозуміти — "неузгоджений подвійний ланцюг кодування". Якщо ви подивитеся на цей список, можливо, ви побачите, як це зробити println!(Hello, world!"); може логічно не вистачати подвійної цитати. Проте повідомлення про помилку можуть швидко ускладнюватися і менш легко інтерпретуватися, коли програми стають більшими, і навіть прості випадки можуть трохи налякати того, хто не знає про Руст.

+ +

Дебаґінг не повинен бути страшним - це ключ до комфортного написання і налагоджування будь-якої мови програмування або коду, знайомство як з мовою так і з інструментами.

+ +

HTML та дебаґінг

+ +

HTML не так складно зрозуміти, як Rust. HTML не компілюється в іншу форму, перш ніж браузер проаналізує його та покаже результат (він інтерпретується, а не компілюється). І синтаксис HTML {{glossary("element")}} набагато легше зрозуміти, ніж "справжню мову програмування", таку як Rust, {{glossary("JavaScript")}}, або {{glossary("Python")}}. Спосіб, за допомогою якого веб-браузери аналізують HTML є набагато більш дозвільним, ніж мови програмування, що є і добре, і погано одночасно.

+ +

Дозвільний код

+ +

Отже, що ми маємо на увазі під дозвільним? Ну, звичайно, коли ви робите щось неправильне в коді, є два основних типи помилок, які ви зустрінете:

+ + + +

Сам по собі HTML не страждає від синтаксичних помилок, оскільки браузери розуміють його належним чином, що означає, що сторінка все одно відображатиметься, навіть якщо є синтаксичні помилки. Браузери мають вбудовані правила, які визначають, як інтерпретувати неправильно написану розмітку, тому ви все одно щось отримаєте, навіть якщо це не те, що ви очікували. Це, звичайно, може бути проблемою!

+ +
+

Примітка: Розібратись в HTML легко, тому що коли веб-мережа була тільки створена, було вирішено, що надання користувачам можливостей публікувати свій вміст було важливішим, ніж переконатися, що синтаксис абсолютно правильний. Веб-мережа, ймовірно, не була б настільки популярною, як є сьогодні, якщо б вона була більш складною від самого початку.

+
+ +

Активне навчання: вивчення допустимого коду

+ +

Настав час вивчити дозвільний характер HTML-коду.

+ +
    +
  1. По-перше, завантажте наш debug-example demo і збережіть його локально. Ця демоверсія спеціально написана, щоб мати деякі помилки в ньому, щоб ми могли їх досліджувати (розмітка HTML, як наголошується, погано сформована, на відміну від добре сформованої).
  2. +
  3. Далі відкрийте його в браузері. Ви побачите щось подібне:A simple HTML document with a title of HTML debugging examples, and some information about common HTML errors, such as unclosed elements, badly nested elements, and unclosed attributes.
  4. +
  5. Це відразу не виглядає чудово; давайте подивимося на вихідний код, щоб побачити, чи зможемо ми зрозуміти, чому (показано лише вміст body); +
    <h1>Приклади HTML дебаґінга</h1>
    +
    +<p>Що викликає помилки в HTML?
    +
    +<ul>
    +  <li>Незамкнені елементи: Якщо елемент <strong> не закрито належним чином,
    +      його ефект може поширюватися на ті області, які ви не мали наміру ним огортати.
    +
    +  <li>Погано вкладені елементи:  правильне вставлення елементів також дуже важливо
    +      для правильного кодування. <strong>strong <em>виділено strong?</strong>
    +      що це таке?</em>
    +
    +  <li>Незакриті атрибути: Інше поширене джерело HTML-проблем.
    +      Давайте розглянемо приклад: <a href="https://www.mozilla.org/>Посилання
    +      на домашню сторінку Mozilla</a>
    +</ul>
    +
  6. +
  7. Давайте розглянемо проблеми: +
      +
    • {{htmlelement("p","paragraph")}} та {{htmlelement("li","list item")}} елементи не мають закриваючих тегів. Дивлячись на зображення вище, це, здається, не вплинуло на рендеринг розмітки надто погано, оскільки легко визначити, де повинен закінчуватися один елемент, а інший повинен починатися.
    • +
    • Перший {{htmlelement("strong")}} елемент не має закриваючого тега. Це дещо ускладнює, оскільки важко сказати, де елемент повинен закінчуватися. Фактично, всю решту тексту було виділено.
    • +
    • Цей розділ погано вкладено: <strong>strong <em>виділено strong?</strong> що це таке?</em>. Складно сказати, як це було інтерпретовано із-за попередньої проблеми.
    • +
    • {{htmlattrxref("href","a")}} Значення атрибута має відсутні подвійні лапки закриття. Це, здається, викликало найбільшу проблему - посилання взагалі не відображається.
    • +
    +
  8. +
  9. Тепер давайте подивимось на розмітку браузера, на відміну від розмітки в вихідному коді. Для цього ми можемо використовувати інструменти розробника веб-браузера. Якщо ви не знайомі з використанням інструментів розробника веб-браузера, перегляньте кілька хвилин Discover browser developer tools.
  10. +
  11. В інспекторі DOM ви можете дізнатись, як виглядає виділена розмітка:The HTML inspector in Firefox, with our example's paragraph highlighted, showing the text "What causes errors in HTML?" Here you can see that the paragraph element has been closed by the browser.
  12. +
  13. Використовуючи інспектора DOM, давайте розглянемо наш код докладно, щоб побачити, як веб-браузер намагався виправити наші помилки HTML (ми зробили огляд у Firefox, інші сучасні браузери повинні дати той самий результат): +
      +
    • У параграфах та пунктах списку були додані закриті теги.
    • +
    • Не зрозуміло, де слід закрити перший елемент <strong>, тому браузер обгорнув кожен окремий блок тексту своїм тегом strong, аж донизу документа!
    • +
    • Неправильне вкладення було виправлено браузером, як це: +
      <strong>strong
      +  <em>виділено strong?</em>
      +</strong>
      +<em> що це таке?</em>
      +
    • +
    • Посилання з відсутніми подвійними лапками повністю вилучено. Останній елемент списку виглядає так : +
      <li>
      +  <strong>Незакриті атрибути: Інше поширене джерело проблем з HTML.
      +  Давайте подивимось на приклад: </strong>
      +</li>
      +
    • +
    +
  14. +
+ +

Валідація HTML

+ +

Таким чином, ви можете побачити з наведеного вище прикладу, що ви дійсно хочете, щоб ваш HTML був добре сформований! Але як? У невеликому прикладі, подібному до вищенаведенного, легко пройти по строках та знайти помилки, а як при величезному, складному HTML-документі?

+ +

Найкраща стратегія полягає в тому, щоб запустити HTML-сторінку за допомогою Markup Validation Service — сервісу, що створений та підтримується W3C, організацією, яка стежить за специфікаціями, що визначають HTML, CSS та інші веб-технології. Ця веб-сторінка приймає HTML-документ у вигляді входу, проходить через нього і дає вам звіт, в якому показує, що неправильно з вашим HTML.

+ +

The HTML validator homepage

+ +

Щоб вказати HTML для перевірки, ви можете надати цьому сервісу адресу свого сайту, завантажити файл HTML або безпосередньо ввести якийсь HTML-код.

+ +

Активне навчання: перевірка документа HTML

+ +

Давайте спробуємо це з нашим sample document.

+ +
    +
  1. По-перше, завантажте Markup Validation Service в одній із вкладок браузера, якщо вона ще не відкрита.
  2. +
  3. Перейдіть на вкладку Validate by Direct Input (Перевірити за прямим введенням).
  4. +
  5. Скопіюйте весь приклад коду документу (а не тільки body) і вставте його у велику область тексту, показану в Markup Validation Service.
  6. +
  7. Натисніть кнопку Check (Перевірити).
  8. +
+ +

В результаті з'явиться список помилок та інша інформація.

+ +

A list of of HTML validation results from the W3C markup validation service

+ +

Інтерпретація повідомлень про помилки

+ +

Повідомлення про помилки зазвичай корисні, але іноді вони не настільки корисні; трохи попрактикувавшись, ви зможете розібратися, як інтерпретувати їх, щоб виправити ваш код. Давайте пройдемось по повідомленням про помилку і що вони означають. Ви побачите, що кожне повідомлення містить номер рядка та стовпчика, які допоможуть легко знайти помилку.

+ + + +

Якщо ви не можете з'ясувати, що означає кожне повідомлення про помилку, не хвилюйтеся - хороша ідея - спробувати одночасно виправити кілька помилок. Потім спробуйте повторно підтвердити свій HTML, щоб показати, які помилки залишаються. Іноді виправлення попередньої помилки також позбуває інших повідомлень про помилку - деякі помилки часто можуть бути викликані однією проблемою, що тягне інші, як ефект доміно.

+ +

Ви будете знати, коли всі ваші помилки виправлені, коли ви побачите наступний банер у вашому виводі:

+ +

Banner that reads "The document validates according to the specified schema(s) and to additional constraints checked by the validator."

+ +

Тобто, "Документ перевірений відповідно до зазначених схем та додаткових обмежень, перевірених валідатором".

+ +

Резюме

+ +

Отже, у нас є вступ до дебаґінга в HTML, який повинен надати вам деякі корисні навички, щоб розраховувати, коли ви почнете налагоджувати CSS, JavaScript та інші типи коду пізніше в своїй кар'єрі. Це також означає завершення вивчення статей "Введення в модулі HTML" - тепер ви можете продовжувати тестування самостійно з нашими оцінками: перший з них за посиланням нижче.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

diff --git a/files/uk/learn/html/introduction_to_html/getting_started/index.html b/files/uk/learn/html/introduction_to_html/getting_started/index.html new file mode 100644 index 0000000000..d1250c915c --- /dev/null +++ b/files/uk/learn/html/introduction_to_html/getting_started/index.html @@ -0,0 +1,522 @@ +--- +title: Початок роботи з HTML +slug: Learn/HTML/Introduction_to_HTML/Getting_started +tags: + - HTML + - Мова + - Основи + - Розмітка + - атрибути + - веб-сторінки + - для початківців + - елементи + - лапки + - символи + - теги + - українською мовою +translation_of: Learn/HTML/Introduction_to_HTML/Getting_started +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML")}}
+ +

У цій статті ми пояснимо найбільш базові поняття HTML — що таке елементи, атрибути та інші терміни, які ви могли чути, і яке завдання вони виконують. Ми покажемо, як побудований елемент HTML і з чого складається типова HTML-сторінка, а також пояснимо інші особливості мови. В процесі навчання ми будемо трохи бавитися з кодом, щоб вам було цікаво!

+ + + + + + + + + + + + +
Передумови:Базове знання комп'ютера, встановлене основне програмне забезпечення, базове розуміння роботи з файлами.
Мета:Отримати базове розуміння мови HTML і попрактикуватися в написанні кількох HTML-елементів.
+ +

Що таке HTML?

+ +

{{glossary("HTML")}} (Hypertext Markup Language — мова гіпертекстової розмітки) не є мовою програмування. Це мова розмітки, яка каже браузеру, як відобразити сторінку, яку ви відвідуєте. HTML може бути простим чи складним, залежно від бажання його розробника. HTML складається з серії {{glossary("Element", "елементів")}}, які ви використовуєте для того, щоб вкласти, загорнути чи розмітити частини сторінки, щоб вони мали певний вигляд. {{glossary("Tag", "Теги")}} можуть перетворити частину тексту на посилання на іншу сторінку, виділити її курсивом тощо. Наприклад, візьміть такий рядок тексту:

+ +

Мій кіт дуже сердитий

+ +

Якщо ми хочемо, щоб цей рядок був сам по собі, ми можемо вказати, що це параграф (абзац), загорнувши його тегом елементу ({{htmlelement("p")}}):

+ +
<p>Мій кіт дуже сердитий</p>
+ +

Анатомія елементу HTML

+ +

Погляньмо на елемент "параграф" детальніше. 

+ +

+ +

Основні частини елементу такі:

+ +
    +
  1. Початковий тег: містить назву елементу (в цьому випадку, p), загорнену в кутові дужки. Цей тег позначає початок елементу, або місце, де елемент починає діяти. У даному випадку — це місце, де починається параграф. 
  2. +
  3. Кінцевий тег: такий самий тег, як і початковий, тільки тепер він містить скісну риску перед назвою елементу. Цей тег позначає місце закінчення елементу — у цьому випадку, місце, де закінчується параграф. Одна з найпоширеніших помилок початківців — це забути поставити кінцевий тег, що може призвести до несподіваних результатів. 
  4. +
  5. Вміст: вміст елементу, у цьому випадку — просто текст. 
  6. +
  7. Елемент: початковий тег разом із кінцевим тегом та вмістом між ними складають елемент.
  8. +
+ +

Активне навчання: створення вашого першого HTML-елементу

+ +

Відредагуйте рядок нижче у полі Input,  загорнувши його тегами <em> та </em> (поставте <em> на початку, щоб відкрити елемент, та </em> в кінці, щоб закрити елемент) — це має виділити рядок курсивом! Ви маєте побачити зміни в полі Output.

+ +

Якщо ви зробите помилку, ви можете завжди скинути редагування кнопкою Reset. Якщо ви справді застрягнете, натисніть кнопку Show solution, щоб побачити відповідь.

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 300) }}

+ +

Вкладені елементи

+ +

Ви можете вкладати одні елементи всередину інших. Це називаєте вкладенням. Якщо ми хочемо наголосити, що наш кіт дуже сумний, ми можемо загорнути слово "дуже" в елемент {{htmlelement("strong")}}, який означає, що слово особливо сильно наголошене:

+ +
<p>My cat is <strong>very</strong> grumpy.</p>
+ +

Важливо пам'ятати правильне вкладення елементів: у прикладі вище ми спершу відкрили елемент {{htmlelement("p")}}, а потім елемент <strong>, що означає, що першим ми маємо закрити внутрішній елемент {{htmlelement("strong")}}, а потім зовнішній {{htmlelement("p")}}. Приклад нижче неправильний:

+ +
<p>My cat is <strong>very grumpy.</p></strong>
+ +

Елемент має закриватися або всередині, або ззовні іншого елемента. Якщо кінцевий тег зовнішнього елемента іде перед кінцевим тегом внутрішнього елемента, ваш браузер спробує здогадатися, що ви хотіли цим сказати, і результати цього можуть бути неочікуваними. Тому не робіть так!

+ +

Блокові та рядкові елементи

+ +

Існують дві важливі категорії елементів у HTML, про які вам слід знати — блокові та рядкові.

+ + + +

Візьміть такий приклад:

+ +
<em>перший</em><em>другий</em><em>третій</em>
+
+<p>четвертий</p><p>п'ятий</p><p>шостий</p>
+ +

{{htmlelement("em")}} є рядковим елементом, тому перші три елементи розміщують в одному рядку, без відстаней між ними. Натомість {{htmlelement("p")}} є блоковим елементом, він розміщується з нового рядка і має відстані над і під ним (ці відстані визначаються у стиляхt CSS, які браузер за замовчанням застосовує до параграфів).

+ +

{{ EmbedLiveSample('Block_versus_inline_elements', 700, 200) }}

+ +
+

Примітка: HTML5 пропонує інший підхід до визначення категорій елементів (див. Element content categories). Хоча нові категорії є більш точними, ніж ті, про які йшлося вище, вони також є значно складнішими для розуміння, ніж "блокові" і "рядкові". Тому ми будемо вживати саме ці дві категорії. 

+
+ +
+

Примітка: ви можете знайти корисні посилання на перелік усіх блокових та рядкових елементів — див. Block-level elements та Inline elements.

+
+ +

Порожні елементи

+ +

Не всі елементи утворюються за шаблоном початковий тег, вміст, кінцевий тег. Деякі елементи мають лише один тег, який зазвичай вставляє щось на певне місце в документі. Це, наприклад, {{htmlelement("img")}}, який вставляє зображення на те місце, куди він поставлений:

+ +
<img src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png">
+ +

Такий вигляд він має на сторінці:

+ +

{{ EmbedLiveSample('Empty_elements', 700, 300) }}

+ +

Атрибути

+ +

Елементи також можуть мати атрибути, які мають такий вигляд: 

+ +

&lt;p class="editor-note">My cat is very grumpy&lt;/p>

+ +

Атрибути містять додаткову інформацію про елемент, яка не відображається в самому контенті. У прикладі вище class це ім'я атрибута, а editor-note — це значення атрибута. Атрибут class дозволяє надати елементу певний ідентифікатор, який пізніше можна використати для того, щоб доступитися до цього елемента і змінити його стиль.

+ +

Атрибут завжди повинен мати:

+ +
    +
  1. Пробіл між ім'ям атрибута і назвою елементу (або попереднім атрибутом, якщо такий є).
  2. +
  3. Ім'я атрибута, за яким іде знак дорівнює.
  4. +
  5. Значення атрибута, загорнене в прямі лапки.
  6. +
+ +

Активне навчання: додавання атрибута до елемента

+ +

Поглянемо на інший елемент — {{htmlelement("a")}} (від anchor — "якір"), який робить гіперпосиланням текст, загорнений в нього. Цей елемент може мати кілька атрибутів, наприклад: 

+ + + +

Відредагуйте рядок нижче в полі Input,так щоб він став посиланням на ваш улюблений сайт. Спочатку додайте елемент <a>, потім атрибути href і title. Насамкінець вкажіть значення атрибута target, так щоб посилання відкривалося в новій вкладці. Ви побачите свої зміни в полі Output. Ви маєте побачити посилання, яке має відображати заголовок (title) при наведенні курсору, а при кліку — переходити за адресою, вказаною в атрибуті href element. Пам'ятайте ставити пробіли між іменем елемента та кожним атрибутом. 

+ +

Ви завжди можете скинути всі зміни кнопкою Reset. Також ви можете подивитися відповідь, натиснувши кнопку Show solution.

+ + + +

{{ EmbedLiveSample('Playable_code2', 700, 300) }}

+ +

Булеві атрибути

+ +

Іноді ви можете побачити в коді лише назву атрибута, без вказаного значення. Це цілком нормальні атрибути, вони називаються булевими. Вони мають лише одне значення, зазвичай таке ж саме, як і назва самого атрибута. Для прикладу візьмемо атрибут {{htmlattrxref("disabled", "input")}}, який робить поля форми неактивними (засіреними), щоб користувачі не могли їх заповнити. 

+ +
<input type="text" disabled="disabled">
+ +

Скорочений запис цілком може мати такий вигляд (ми також додали активне поле для кращого розуміння): 

+ +
<input type="text" disabled>
+
+<input type="text">
+
+ +

Обидва записи дадуть такий результат: 

+ +

{{ EmbedLiveSample('Boolean_attributes', 700, 100) }}

+ +

Опускання лапок навколо значень атрибутів

+ +

Іноді в мережі ви можете побачити багато різних прикладів дивної розмітки, наприклад, значення атрибутів, записані без лапок. Хоча за деяких обставин такий запис є прийнятним, в інших випадках він може поламати розмітку. Наприклад, у нашому посиланні з прикладу вище ми можемо записати атрибут href так:

+ +
<a href=https://www.mozilla.org/>favourite website</a>
+ +

Однак, якщо ми додамо другий атрибут title, розмітка порушиться:

+ +
<a href=https://www.mozilla.org/ title=The Mozilla homepage>favourite website</a>
+ +

Таку розмітку браузер розуміє неправильно, вважаючи, що title — це насправді три атрибути: атрибут "title" зі значенням "The" і два інші атрибути булевого типу, Mozilla і homepage. Така поведінка не є очікуваною і може призвести до помилок, як показано в прикладі нижче. Спробуйте навести курсор на текст, щоб подивитися, який текст у заголовку. 

+ +

{{ EmbedLiveSample('Omitting_quotes_around_attribute_values', 700, 100) }}

+ +

Ми радимо завжди писати атрибути в лапках, це дозволяє уникнути багатьох проблем і робить код більш читабельним. 

+ +

Лапки подвійні чи одинарні?

+ +

У цій статті всі значення атрибутів загорнені в звичайні прямі лапки. Проте іноді ви можете побачити, що значення загортається прямими апострофами на початку і в кінці (одинарні лапки). Вживання перших і других в HTML є питанням смаку, ви можете сміливо використовувати ті лапки, які зручно. Обидва записи будуть рівноцінними.

+ +
<a href="http://www.example.com">A link to my example.</a>
+
+<a href='http://www.example.com'>A link to my example.</a>
+ +

Однак, не можна змішувати лапки різного типу в одному записі. Наприклад, такий запис є неправильним:

+ +
<a href="http://www.example.com'>A link to my example.</a>
+ +

Якщо ви використали лапки одного типу в записі, всередину ви можете вкласти лапки іншого типу. Наприклад, тут апостроф вживається всередині значення в подвійних лапках:

+ +
<a href="http://www.example.com" title="Isn't this fun?">A link to my example.</a>
+ +

Для вкладення лапок того самого типу потрібно користуватися спеціальними символами, про які піде мова нижче.

+ +

Анатомія HTML-документу

+ +

Все зазначене вище є основами HTML, але окремо взяті елементи самі по собі мало на що здатні. Тепер ми поглянемо на те, як окремі елементи формують цілу веб-сторінку:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My test page</title>
+  </head>
+  <body>
+    <p>This is my page</p>
+  </body>
+</html>
+ +

Тут ми маємо:

+ +
    +
  1. <!DOCTYPE html>: Доктайп (тип документу). В ті часи, коли HTML тільки зароджувався (близько 1991/2), доктайпы (doctypes) використовувалися як посилання на набір правил, яким HTML-сторінка повинна була слідувати, щоб вважатись написаною хорошим HTML-кодом, що може означати автоматичну перевірку помилок та інші корисні речі. Доктайп приблизно такий вигляд: + +
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    + Проте в наші дні ніхто справді не дбає про них, і вони насправді є лише історичним артефактом, який потрібно включити в документ, щоб той правильно працював<!DOCTYPE html> це найкоротший рядок символів, який вважається валідним доктайпом; це все, що вам дійсно потрібно знати.
  2. +
  3. <html></html>: Елемент {{htmlelement("html")}}. Цей елемент огортає весь зміст (контент) на всій сторінці, іноді його називають кореневим (root) елементом.
  4. +
  5. <head></head>: Елемент {{htmlelement("head")}}. Цей елемент діє як контейнер для всього матеріалу, який ви хочете включити в сторінку HTML, але який не є вмістом, що ви надаєте для перегляду відвідувачам вашої сторінки. Він включає в себе такі речі, як ключові слова та опис сторінки, які ви хочете відобразити в результатах пошуку, CSS, щоб стилізувати вміст сторінки, оголошення підтримуваного набору символів тощо. Ви дізнаєтеся більше про це в наступній статті цієї серії.
  6. +
  7. <meta charset="utf-8">: Цей елемент встановлює в якості символьного кодування для вашого документу UTF-8, що включає більшість символів з переважної більшості письмових мов людей. По суті, це дає змогу обробляти будь-який текстовий вміст, який ви можете додати до документу. Немає причин не встановлювати таке кодування, і це допоможе уникнути деяких проблем пізніше.
  8. +
  9. <title></title>: Елемент {{htmlelement("title")}}. Цей елемент встановлює назву вашої сторінки, що є заголовком, який відображається на вкладці веб-браузера, на якій завантажується сторінка, і використовується для опису сторінки під час додавання/уподобання її.
  10. +
  11. <body></body>: Елемент {{htmlelement("body")}}. Цей елемент містить весь контент, який ви хочете показати веб-користувачам під час відвідування вашої сторінки, незалежно від того, чи це є текст, зображення, відео, ігри, відтворювані звукові доріжки тощо.
  12. +
+ +

Активне навчання: додавання деяких функцій у документ HTML

+ +

Якщо ви хочете поекспериментувати з написанням HTML-коду на вашому локальному комп'ютері, ви можете зробити наступне:

+ +
    +
  1. Скопіюйте наведений вище приклад HTML сторінки.
  2. +
  3. Створіть новий файл у текстовому редакторі.
  4. +
  5. Вставте код у новий текстовий файл.
  6. +
  7. Збережіть файл як index.html.
  8. +
+ +
+

Примітка: Ви також можете знайти цей основний HTML шаблон на MDN Learning Area Github repo.

+
+ +

Тепер ви можете відкрити цей файл у веб-браузері, щоб побачити, як має вигляд відображення вірного коду, а потім відредагувати код та оновити веб-браузер, щоб побачити результат. Спочатку це матиме такий вигляд:

+ +

A simple HTML page that says This is my page В цій вправі ви можете редагувати код локально на своєму комп'ютері, як зазначено вище, або можете редагувати його в запропонованому редакторі нижче (у вікні редактора в цьому прикладі показано лише зміст елемента {{htmlelement("body")}}) Спробуйте зробити наступне:

+ + + +

Якщо ви зробите помилку, ви завжди можете скинути її за допомогою кнопки Reset. Якщо ви дійсно заплутались, натисніть кнопку Show solution, щоб побачити відповідь.

+ + + +

{{ EmbedLiveSample('Playable_code3', 700, 600) }}

+ +

Пробіли в HTML

+ +

У наведених вище прикладах, мабуть, ви помітили, що багато пробілів в коді - це взагалі не обов'язково; два наступні фрагменти коду є еквівалентними:

+ +
<p>Dogs are silly.</p>
+
+<p>Dogs        are
+         silly.</p>
+ +

Незалежно від того, скільки пустого місця ви використовуєте (яке може містити пробіл, а також відступи рядків), HTML-аналізатор зменшує кожен з них до одного пробілу під час відтворення коду. Тож навіщо використовувати так багато пробілів? Відповідь - зручність читання - набагато легше зрозуміти, що відбувається у вашому коді, якщо у вас це чудово відформатовано, а не просто зібрано разом у великий хаос. У нашому HTML-коді кожен вкладений елемент має два пробіли, ніж той, в якому він розміщений всередині. Ви самі визначаєте стиль форматування, який ви використовуєте (скільки пробілів для кожного рівня відступу, наприклад), але ви повинні розглянути можливість використання якогось форматування.

+ +

Посилання на об'єкт: включаючи спеціальні символи в HTML

+ +

В HTML символи <, >,",' та & є спеціальними символами. Вони є частинами самого синтаксису HTML, тому як вводити один з цих символів у ваш текст, наприклад, якщо ви дійсно хочете використати амперсанд або знак менше, і не трактувати його як код, як це можуть зробити деякі веб-браузери?

+ +

В такому випадку ми повинні використовувати символьні посилання - спеціальні коди, що представляють символи, і можуть використовуватися в конкретних обставинах. Кожне посилання символів починається з амперсанда (&), а закінчується двокрапкою (;).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Буквений символЕквівалентне написання символів
<&lt;
>&gt;
"&quot;
'&apos;
&&amp;
+ +

У наведеному нижче прикладі ви можете побачити два абзаци, які говорять про веб-технології:

+ +
<p>In HTML, you define a paragraph using the <p> element.</p>
+
+<p>In HTML, you define a paragraph using the &lt;p&gt; element.</p>
+ +

Нижче наводиться приклад, в якому ви можете побачити, що перший абзац вийшов не так, тому що браузер вважає, що другий елемент <p> починає новий абзац. Другий абзац виглядає чудово, тому що ми замінили кутові дужки на символьні посилання.

+ +

{{ EmbedLiveSample('Entity_references_including_special_characters_in_HTML', 700, 200) }}

+ +
+

Примітка: У графіку всіх доступних посилань на об'єкти HTML можна знайти у Вікіпедії: List of XML and HTML character entity references.

+
+ +

Коментарі HTML

+ +

В HTML, як і у більшості мов програмування, існує механізм, доступний для написання коментарів у коді - коментарі браузером ігноруються і невидимі для користувача, їхня мета полягає у тому, щоб дозволити вам додавати коментарі до коду, щоб пояснити, як ваш код працює, що роблять різні частини коду тощо. Це може бути дуже корисним, якщо ви повернетеся до свого коду, над яким ви не працювали, наприклад, протягом шести місяців, і не пам'ятаєте, що ви робили, або якщо над вашим кодом ще хтось працював.

+ +

Щоб перетворити розділ вмісту всередині вашого HTML-файлу в коментар, вам необхідно обгорнути його спеціальними маркерами <!-- та -->, наприклад:

+ +
<p>I'm not inside a comment</p>
+
+<!-- <p>I am!</p> -->
+ +

Як ви можете побачити, перший абзац відображається на сторінці, а другий - ні.

+ +

{{ EmbedLiveSample('HTML_comments', 700, 100) }}

+ +

Підсумок

+ +

Ви досягли кінця статті - ми сподіваємося, що вам сподобалась ваша мандрівка по основах HTML! На цьому етапі ви повинні розуміти, як має вигляд мова, як вона працює на базовому рівні, і вміти писати кілька елементів і атрибутів. Це ідеальне місце, щоб розпочати навчання прямо зараз і продовжити вивчати далі наступні статті модуля. Ви розглянете деякі речі, з якими ви вже ознайомлені, але більш докладно, і дізнаєтесь про деякі нові можливості мови HTML. Залишайтеся на зв'язку!

+ +
+

Примітка: На цьому етапі, коли ви почнете більше дізнаватися про HTML, ви також можете почати вивчати основи каскадних таблиць стилів або CSS. CSS - це мова, яку ви використовуєте для стилізації веб-сторінок (наприклад, зміна шрифту або кольорів, або зміна макета сторінки). HTML та CSS дуже добре співпрацюють, в чому ви незабаром переконаєтесь.

+
+ +
{{NextMenu("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML")}}
diff --git a/files/uk/learn/html/introduction_to_html/html_text_fundamentals/index.html b/files/uk/learn/html/introduction_to_html/html_text_fundamentals/index.html new file mode 100644 index 0000000000..7387e08725 --- /dev/null +++ b/files/uk/learn/html/introduction_to_html/html_text_fundamentals/index.html @@ -0,0 +1,953 @@ +--- +title: HTML text fundamentals +slug: Learn/HTML/Introduction_to_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")}}
+ +

Одне з головних завдань HTML полягає в тому, щоб надати текстову структуру та смислове значення (також відоме як {{glossary("семантика")}}) таким чином, щоб браузер міг відобразити зміст на сторінці коректно. У цій статті пояснюється, у який спосіб можна використовувати {{glossary("HTML")}}, щоб структурувати текст на сторінці, додавши заголовки та параграфи, підкреслюючи слова, створюючи списки та інше.

+ + + + + + + + + + + + +
Передумови:Базове знайомство з HTML, як описано в Початок роботи з HTML.
Мета:Дізнайтеся, як позначити основну сторінку тексту, щоб надати йому структуру та зміст - включаючи абзаци, заголовки, списки, акцент та цитати.
+ +

Основа: заголовки та абзаци

+ +

Найбільш структурований текст складається з заголовків і параграфів, незалежно від того, чи читаєте ви історію, газету, підручник з коледжу, журнал тощо.

+ +

An example of a newspaper front cover, showing use of a top level heading, subheadings and paragraphs.

+ +

Структурований вміст полегшує та покращує досвід читання.

+ +

У HTML кожен абзац повинен бути загорнутий у елемент {{htmlelement ("p")}}, так:

+ +
<p>Я абзац,о так, це я.</p>
+ +

Кожен заголовок має бути загорнутий в елемент заголовка:

+ +
<h1>Я назва цієї історії.</h1>
+ +

Є шість елементів заголовку — {{htmlelement("h1")}}, {{htmlelement("h2")}}, {{htmlelement("h3")}}, {{htmlelement("h4")}}, {{htmlelement("h5")}}, та {{htmlelement("h6")}}. Кожен елемент представляє інший рівень вмісту документа;<h1> являє собою основний заголовок, <h2> представляє підзаголовки, <h3> представляє наступні підзаголовки тощо.

+ +

Впровадження структурної ієрархії

+ +

Наприклад, у історії <h1> буде представляти назву історії, <h2> s представлятиме назву кожного розділу, а <h3> представлятиме підрозділи кожного розділу тощо.

+ +
<h1>Нищівна свердловина</h1>
+
+<p>Кріс Міллс</p>
+
+<h2>Розділ 1: Темна ніч</h2>
+
+<p>Це була темна ніч. Десь, сова вигукувала. Дощ обрушився на ...</p>
+
+<h2>Розділ 2: Вічна тиша</h2>
+
+<p>Наш головний герой міг не стільки шепотом вийти з тіньової фігури ...</p>
+
+<h3>Привид говорить</h3>
+
+<p>Минуло ще кілька годин, коли раптово, побачивши привида, випрямився і вигукнув: «Будь ласка, помилуй мою душу!"</p>
+ +

Це дійсно залежить від вас, які саме елементи ви використовуєте, тоді ієрархія має сенс. Вам просто потрібно мати на увазі кілька найкращих практик, коли ви створюєте такі структури:

+ + + +

Чому нам потрібна структура?

+ +

Щоб відповісти на це запитання, давайте подивимося на text-start.html - початкову точку нашого запущеного прикладу для цієї статті (хороший рецепт хумусу). це потрібно для вправ пізніше. В даний час у цьому документі міститься кілька фрагментів вмісту - вони не позначені жодним чином, але розділені проривами рядків (Enter / Return натиснуто, щоб перейти до наступного рядка).

+ +

Однак, коли ви відкриваєте документ у вашому браузері, ви побачите, що текст з'являється суцільним шматком!

+ +

A webpage that shows a wall of unformatted text, because there are no elements on the page to structure it.

+ +

Це пояснюється тим, що немає елементів, які б давали структуру контенту, тому браузер не знає, що є заголовок а що є абзацом. Крім того:

+ + + +

Тому нам необхідно надати нашому контенту структурну розмітку.

+ +

Активне навчання: Надання нашої структури змісту

+ +

Давайте розглянемо живой приклад. У наведеному нижче прикладі додайте елементи до вихідного тексту у полі Введення так, щоб він з'являвся у вигляді заголовка та двох абзаців у полі Вивід.

+ +

Якщо ви зробите помилку, ви завжди можете скинути її за допомогою кнопки скидання. Якщо ви застрягли, натисніть кнопку Показати рішення, щоб побачити відповідь.

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 400, "", "", "hide-codepen-jsfiddle") }}

+ +

Чому нам потрібна семантика?

+ +

Семантика  всюди навколо нас - ми покладаємося на попередній досвід, щоб розповісти вам, що таке функція повсякденних об'єктів; коли ми щось бачимо, ми знаємо, якою буде її функція. Так, наприклад, ми очікуємо, що червоний світлофор означає "зупинка", а зелений світлофор означає "іти". Речі можуть бути дуже складними дуже швидко, якщо застосовується неправильна семантика (чи будь-яка країна використовує червоний, щоб означати "йти"?

+ +

У подібному дусі, ми повинні переконатися, що ми використовуємо правильні елементи, надаючи нашому змісту правильний сенс, функцію або зовнішній вигляд. У цьому контексті елемент {{htmlelement ("h1")}} також є семантичним елементом, який надає тексту, який він обертає навколо ролі (або значення) "заголовка верхнього рівня на вашій сторінці".

+ +
<h1>Це заголовок верхнього рівня</h1>
+ +

За замовчуванням браузер надасть йому великий розмір шрифту для того, щоб він виглядав як заголовок (хоча ви могли б такий стиль текста, могли отримати, використовуючи CSS). Більш важливо, що його семантичне значення буде використовуватися кількома способами, наприклад, пошуковими системами та програмами для читання з екрана (як згадано вище).

+ +

З іншого боку, ви можете зробити будь-який елемент схожим на елемент верхнього рівня. Розгляньте наступне:

+ +
<span style="font-size: 32px; margin: 21px 0;">Це заголовок верхнього рівня?</span>
+ +

Це елемент {{htmlelement ("span")}}. Вона не має семантики. Ви використовуєте його, щоб загорнути вміст, коли ви хочете застосувати до нього CSS (або зробити щось із цим за допомогою JavaScript), не надаючи йому жодного додаткового сенсу (про це пізніше ви знайдете в курсі.) Ми застосували деякі CSS, щоб він виглядав як заголовок верхнього рівня, але оскільки він не має семантичного значення, він не отримає жодної з додаткових переваг, описаних вище. Це гарна ідея використовувати відповідний елемент HTML для завдання.

+ +

Списки

+ +

Тепер звернемо увагу до списків. Списки знаходяться в усьому нашому житті - від списку покупок до списку напрямків, які ви підсвідомо дотримуєтеся, щоб дістатися до вашого будинку щодня, до списків інструкцій, які ви дотримуєтеся в цих підручниках! Списки знаходяться всюди в Інтернеті, і ми маємо три різні типи, про які потрібно знати.

+ +

Невпорядкований

+ +

Невпорядковані списки використовуються для позначення списків пунктів, для яких не має значення порядок позицій - візьмемо, наприклад, список покупок.

+ +
молоко
+яйця
+хліб
+гумус
+ +

Кожен невпорядкований список починається з елемента {{htmlelement ("ul")}}, який обертається навколо всіх елементів списку:

+ +
<ul>
+молоко
+яйцчя
+хліб
+гумус
+</ul>
+ +

Останнім кроком є перенесення кожного елемента списку в елемент {{htmlelement ("li")}} (елемент списку):

+ +
<ul>
+  <li>молоко</li>
+  <li>яйцчя</li>
+  <li>хліб</li>
+  <li>гумус</li>
+</ul>
+ +

Активне навчання: розмітка невпорядкованого списку

+ +

Спробуйте відредагувати живий зразок нижче, щоб створити свій власний HTML-невпорядкований список.

+ + + +

{{ EmbedLiveSample('Playable_code_2', 700, 400, "", "", "hide-codepen-jsfiddle") }}

+ +

Замовлено

+ +

Упорядковані списки - це списки, в яких має значення порядок елементів - приведемо приклад набору напрямків:

+ +
Проїдьте до кінця дороги
+Поверніть праворуч
+Ідіть прямо по перших двох роз'їздів
+На третьому кільці поверніть ліворуч
+Школа знаходиться справа від вас, 300 метрів вперед по дорозі
+ +

Структура розмітки така ж, як і для невпорядкованих списків, за винятком того, що ви повинні обернути елементи списку в елемент {{htmlelement("ol")}}, а не <ul>:

+ +
<ol>
+  <li>Проїдьте до кінця дороги</li>
+  <li>Поверніть праворуч</li>
+  <li>Ідіть прямо по перших двох роз'їздів</li>
+  <li>На третьому кільці поверніть ліворуч</li>
+  <li>Школа знаходиться справа від вас, 300 метрів вперед по дорозі</li>
+</ol>
+ +

Активне навчання: розмітка впорядкованого списку

+ +

Спробуйте відредагувати живий зразок нижче, щоб створити свій власний HTML-список.

+ + + +

{{ EmbedLiveSample('Playable_code_3', 700, 500, "", "", "hide-codepen-jsfiddle") }}

+ +

Активне навчання: Розмітка сторінки рецепта

+ +

Таким чином, на даний момент у статті, у вас є вся інформація, необхідна для позначення нашого прикладу сторінки рецептів. Ви можете зберегти локальну копію нашої text-start.html запустіть файл і виконайте роботу там, або зробіть це в прикладі, що можна редагувати нижче. Можливо, це краще робити локально, оскільки ви зможете зберегти роботу, яку ви виконуєте, тоді як, якщо ви заповните її у редагований приклад, вона буде втрачена під час наступного відкриття сторінки. Обидва варіанти мають плюси і мінуси.

+ + + +

{{ EmbedLiveSample('Playable_code_4', 900, 500, "", "", "hide-codepen-jsfiddle") }}

+ +

Якщо ви застрягли, ви завжди можете натиснути кнопку Показувати рішення або перевірити наш text-complete.html приклад на нашому github репозиторії.

+ +

Вкладені списки

+ +

Цілком нормально вкласти один список у інший. Ви, можливо, захочете, щоб деякі підпункти знаходились під  верхным рівнем. Візьмемо другий список з нашого прикладу рецептів:

+ +
<ol>
+  <li>Видаліть шкіру з часнику і грубо наріжте.</li>
+  <li>Видаліть все насіння і стебло з перцю і грубо наріжте.</li>
+  <li>Додайте всі інгредієнти в кухонний комбайн.</li>
+  <li>Переробіть всі інгредієнти в пасту.</li>
+  <li>Якщо ви хочете грубий "кремезний" гумус, переробляйте його короткий час.</li>
+  <li>Якщо ви хочете гладкий гумус, переробляйте його довше.</li>
+</ol>
+ +

Оскільки останні дві кулі дуже тісно пов'язані з тією, що була перед ними (вони читаються, як під-інструкції або варіанти, які підходять нижче цієї кулі), може мати сенс вкладати їх у свій власний невпорядкований список і розміщувати цей список всередині четверта куля. Це виглядатиме так:

+ +
<ol>
+  <li>Видаліть шкіру з часнику і грубо наріжте.</li>
+  <li>Видаліть все насіння і стебло з перцю і грубо наріжте.</li>
+  <li>Додайте всі інгредієнти в кухонний комбайн.</li>
+  <li>Переробіть всі інгредієнти в пасту.
+    <ul>
+      <li>Якщо ви хочете грубий "кремезний" гумус, переробляйте його короткий час.</li>
+      <li>Якщо ви хочете гладкий гумус, переробляйте його довше.</li>
+    </ul>
+  </li>
+</ol>
+ +

Спробуйте повернутися до попереднього активного прикладу навчання та оновити другий список, подібний до цього.late

+ +

Акцент і важливість

+ +

У людській мові ми часто підкреслюємо певні слова, щоб змінити зміст речення, і ми часто хочемо позначити певні слова як важливі або різні. HTML надає різні семантичні елементи, які дозволяють нам розмічати текстовий вміст з такими ефектами, і в цьому розділі ми розглянемо деякі з найбільш поширених.

+ +

Акцент

+ +

Коли ми хочемо додати акцент у розмовній мові, ми підкреслюємо певні слова, тонко змінюючи сенс того, що ми говоримо. Аналогічно, у письмовій мові ми схильні підкреслювати слова, виділяючи їх курсивом. Наприклад, наступні два речення мають різне значення.

+ +

Я радий, що ви не запізнилися.

+ +

Я радий, що ви не запізнилися.

+ +

Перше речення звуки справді полегшено, що людина не запізнився. Навпаки, другий звучить саркастично або пасивно-агресивно, висловлюючи досаду, що людина прибула трохи пізно.

+ +

У HTML ми використовуємо елемент {{htmlelement ("em")}} (вираз) для позначення таких екземплярів. Окрім того, що документ є цікавішим для читання, вони розпізнаються читачами екрану та висловлюються іншим тоном голосу. Браузери за замовчуванням створюють цей стиль як курсив, але ви не повинні використовувати цей тег, щоб отримати стиль курсиву. Для цього потрібно використовувати елемент {{htmlelement ("span")}} і деякий CSS, або, можливо, елемент {{htmlelement ("i")}} (див. Нижче).

+ +
<p>Я <em>радий</em>, що ви не <em>запізнилися</em>.</p>
+ +

Велике значення

+ +

Щоб підкреслити важливі слова, ми прагнемо підкреслити їх у розмовній мові і сміливо їх писати. Наприклад:

+ +

Ця рідина дуже токсична.

+ +

Я розраховую на вас. Не запізнюйтеся!

+ +

У HTML ми використовуємо {{htmlelement("strong")}} (strong важливий) елемент для позначення таких випадків. Окрім того, що документ стане більш корисним, вони знову розпізнаються читачами екрану та говорять різним тоном голосу. За умовчанням у браузерах цей текст виділено напівжирним шрифтом, але ви не повинні використовувати цей тег лише для отримання жирного стилю. Для цього потрібно використати {{htmlelement("span")}} елемент і деякі CSS, або, можливо,елемент{{htmlelement("b")}} (дивись нижче.)

+ +
<p>Ця рідина є <strong>дуже токсичною</strong>.</p>
+
+<p>Я розраховую на вас. <strong>Не </strong> запізнюйтесь!</p>
+ +

За бажанням можна вмонтовувати strong і акцентувати всередині один одного:

+ +
<p>Ця рідина є <strong>дуже токсичною</strong> —
+якщо ви її вип'єте, <strong>Ви можете <em>померти</em></strong>.</p>
+ +

Активне навчання: Давайте будемо уважними!

+ +

У цьому розділі активного навчання ми надали приклад, який можна редагувати. Усередині неї ми хотіли б, щоб ви спробували додати акцент і важливе значення словам, які ви вважаєте потрібними їм, просто щоб мати певну практику.

+ + + +

{{ EmbedLiveSample('Playable_code_5', 700, 500, "", "", "hide-codepen-jsfiddle") }}

+ +

Курсив, жирний, підкреслений ...

+ +

Елементи, які ми обговорювали до цих пір, мають чітко виражену семантику. Ситуація з {{htmlelement("b")}}, {{htmlelement("i")}}, та {{htmlelement("u")}} дещо складніше. Вони прийшли так, щоб люди могли писати напівжирний, курсив або підкреслений текст в епоху, коли CSS все ще підтримувався погано або зовсім не підтримувався. Такі елементи, які впливають лише на презентацію, а не на семантику, відомі як елементи презентації і більше не повинні використовуватися, оскільки, як ми бачили раніше, семантика настільки важлива для доступності, SEO та ін.

+ +

HTML5 перевизначено <b>, <i> та <u> з новими, дещо заплутаними, семантичними ролями.

+ +

Ось найкраще правило: скоріше за все доцільно використовувати <b>, <i> або <u>, щоб передати значення, яке традиційно передається жирним шрифтом, курсивом або підкресленням, за умови, що немає більш відповідного елемента. Тим не менш, завжди залишається критично важливим збереження мислення доступності. Концепція курсиву не дуже корисна людям, які використовують читання з екрану, або людям, які використовують систему письма, окрім латинського алфавіту.

+ + + +
+

Попередження про підкреслення: люди пов'язують підкреслення з гіперпосиланнями. Тому в Інтернеті краще підкреслити лише посилання. Використовуйте елемент <u>, якщо він семантично доречний, але розгляньте можливість використання CSS для зміни підкресленого підкреслення на щось більш доречне в Інтернеті. Наведений нижче приклад ілюструє, як це можна зробити.

+
+ +
<!-- наукові назви -->
+<p>
+  Рубінова колібрі (<i> Archilochus colubris </i>)
+   є найбільш поширеним колібром у Східній Північній Америці.
+</p>
+
+<!-- іноземні слова -->
+<p>
+  Меню було морем екзотичних слів <i lang="uk-latn">ватрушка</i>,
+  <i lang="id">nasi goreng</i> та <i lang="fr">soupe à l'oignon</i>.
+</p>
+
+<!-- відоме неправильне написання -->
+<p>
+  Коли-небудь я дізнаюся, як це зробити <u>spel</u> better.
+</p>
+
+<!-- Виділіть ключові слова в наборі інструкцій -->
+<ol>
+  <li>
+    <b>Фрагмент</b> два шматки хліба з буханки.
+  </li>
+  <li>
+    <b>Вставити</b> шматочок томата і лист салату між шматочками хліба.
+  </li>
+</ol>
+
+
+ +

Підсумок

+ +

Ось це зараз! Ця стаття повинна була дати вам гарне уявлення про те, як почати розмітку тексту в HTML, і познайомили вас з деякими з найважливіших елементів у цій області. Існує набагато більше семантичних елементів для висвітлення в цій області, і ми розглянемо набагато більше в нашій статті "Більше семантичних елементів", що пізніше буде в курсі. У наступній статті ми детально розглянемо, як створювати гіперпосилання , можливо, найважливіший елемент на Web.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML")}}

+ +

У цьому модулі

+ + diff --git a/files/uk/learn/html/introduction_to_html/index.html b/files/uk/learn/html/introduction_to_html/index.html new file mode 100644 index 0000000000..9b9ee8d4a6 --- /dev/null +++ b/files/uk/learn/html/introduction_to_html/index.html @@ -0,0 +1,55 @@ +--- +title: Вступ до HTML +slug: Learn/HTML/Introduction_to_HTML +translation_of: Learn/HTML/Introduction_to_HTML +--- +
{{LearnSidebar}}
+ +

{{glossary("HTML")}} є відносно простою мовою. Вона складається з елементів, які можуть застосовуватися до різних частин тексту і надавати їм певного значення в документі (наприклад, цей текст є параграфом, цей — ненумерованим списком, цей — частиною таблиці), розбивати документ на логічні частини (це заголовок, це три колонки контенту, це меню навігації), а також вставляти контент, такий як відео чи зображення, у документ. У цьому розділі ми поговоримо про перші два з цих завдань, а також розглянемо базові поняття і синтаксис, які потрібні для розуміння HTML.

+ +

Передумови

+ +

Для цього розділу вам не потрібні попередні знання з HTML, але потрібно бути користувачем комп'ютерів і мережі (принаймні на рівні переглядання сайтів). Також вам буде потрібне базове робоче середовище, встановлення якого описане в статті Встановлення основного програмного забезпечення, і розуміння того, як створювати і керувати файлами, як описано в статті Робота з файлами — обидві статті є частинами розділу Початок роботи з вебом.

+ +
+

Примітка: якщо ви працюєте на комп'ютері/планшеті/іншому пристрої, на якому не маєте можливості створювати файли, спробуйте писати код в онлайн-програмах, таких як  JSBin чи Thimble.

+
+ +

Посібники

+ +

Статті у цьому розділі пояснюють базову теорію HTML і надають можливість перевірити ваші навички.

+ +
+
Початок роботи з HTML
+
Стаття пояснює елементарні основи HTML — що таке елементи, атрибути та інші важливі поняття, які ви могли чути, і яке завдання вони виконують. Ми також покажемо, як побудований елемент HTML, як побудована типова сторінка HTML, і пояснимо інші основні особливості мови. В процесі роботи ми трохи пограємо з HTML, щоб вам було цікаво!
+
Що в head? Метадані в HTML
+
Head в HTML-документі є частиною, яка не відображається в веб-браузері коли сторінка завантажується. Вона містить інформацію про сторінку, такі як {{htmlelement("title")}}, посилання на {{glossary("CSS")}} (якщо ви хочете надати стиль вашому HTML-змісту за допомогою CSS), посилання до користувальницьких favicons та метаданих (тобто даних про HTML, наприклад, хто його написав (автор) і важливі ключові слова (keywords), що описують документ.)
+
Основи HTML-тексту
+
Одним із основних завдань HTML є надання текстового значення (також відомого як семантика), щоб браузер знав, як правильно відображати його. У цій статті розглядається, як правильно використовувати HTML, щоб розбити блок тексту на структуру заголовків та абзаців (параграфів), додати акцент/важливість слів, створити списки і багато іншого.
+
Створення гіперпосилань
+
Гіперпосилання дійсно важливі — саме вони роблять Інтернет павутиною. Ця стаття показує синтаксис, необхідний для створення посилання і обговорює кращі практичні поради.
+
Розширене форматування тексту
+
В HTML є багато інших елементів для форматування тексту, про які ми не вказали в статті Основи HTML тексту. Елементи, що знаходяться тут, менш відомі, але їх все ж корисно знати. Тут ви дізнаєтесь про позначення цитат, списки опису, комп'ютерний код та інший пов'язаний текст, індекс та верхній індекс, контактну інформацію та багато іншого.
+
Структура документу та веб-сайту
+
Крім визначення окремих частин вашої сторінки (наприклад "абзац" або "зображення"), HTML також використовується для визначення областей вашого веб-сайту (таких як "заголовок", "навігаційне меню", "колонка основного змісту".) У цій статті розглянуто, як планувати основну структуру веб-сайту, а також написати HTML-код для представлення цієї структури.
+
Відлагодження HTML
+
Написали HTML-код файно, але що робити, якщо щось йде неправильно і ви не можете з'ясувати, де помилка в коді? В цій статті ви ознайомитесь з деякими інструментами, які зможуть вам допомогти.
+
+ +

Оцінки

+ +

Наступні оцінки допоможуть перевірити ваше розуміння базових основ HTML, описаних вище в посібниках.

+ +
+
Розмітка/Форматування листа
+
Ми всі вчимося писати листи рано чи пізно. Це також корисний приклад, щоб перевірити свої навички у форматуванні тексту. Отже, в цій оцінці вам буде надіслано листа для форматування.
+
Структурування сторінки змісту
+
Ця оцінка перевіряє ваше вміння використовувати HTML для структурування простої сторінки змісту, що містить заголовок (header), нижній колонтитул (footer), навігаційне меню (navigation menu), основний зміст (main content), і бічну панель (sidebar).
+
+ +

Дивіться також

+ +
+
Основи веб-грамотності 1
+
Відмінний курс навчання Mozilla foundation, який навчає та випробовує багато навичок, про які говорилося в модулі Вступ до HTML. Учні знайомляться з читанням, написанням та участю в Інтернеті в цьому шестичастинному модулі. Дізнайтеся про основи Інтернету за допомогою виробництва та співпраці.
+
diff --git a/files/uk/learn/html/introduction_to_html/scho_v_head_metadani_v_html/index.html b/files/uk/learn/html/introduction_to_html/scho_v_head_metadani_v_html/index.html new file mode 100644 index 0000000000..63ac7a8cfa --- /dev/null +++ b/files/uk/learn/html/introduction_to_html/scho_v_head_metadani_v_html/index.html @@ -0,0 +1,276 @@ +--- +title: Що в head? Метадані в HTML +slug: Learn/HTML/Introduction_to_HTML/scho_v_head_metadani_v_HTML +tags: + - CSS + - HTML + - head + - Заголовок + - Мова + - Основи + - Розмітка + - веб-сторінки + - голова + - для початківців + - значки + - мета +translation_of: Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML")}}
+ +

Елемент {{glossary("Head", "head")}} документа HTML - це частина, яка не відображається у веб-браузері під час завантаження сторінки. Він містить таку інформацію, як назва сторінки {{htmlelement("title")}}, посилання на файл стилів {{glossary("CSS")}} (якщо ви хочете стилізувати ваш HTML контент за допомогою CSS), посилання на  власні іконки та інші метадані (дані про HTML, наприклад, хто його написав, та важливі ключові слова, які описують документ.) У цій статті ми розглянемо все перераховане вище та інше, щоб дати вам гарну основу для роботи з розміткою.

+ + + + + + + + + + + + +
Передумови:Знання основ HTML, як описано в Початок роботи з HTML.
Мета:Дізнатись про заголовок (head) в HTML, які в нього задачі, найважливіші елементи, які він може містити, і який вплив він може мати на HTML-документ.
+ +

Що таке заголовок (head) HTML?

+ +

Давайте перейдемо до простого HTML документу, який ми розглянули в попередній статті:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My test page</title>
+  </head>
+  <body>
+    <p>This is my page</p>
+  </body>
+</html>
+ +

Заголовок HTML (head) - це вміст елементу {{htmlelement("head")}} — на відміну від вмісту елемента {{htmlelement("body")}} (яке відображається на сторінці при завантаженні в браузері), вміст head не відображається на сторінці. Головним завданням заголовку є містити {{glossary("Metadata", "метадані")}} про документ. У наведеному вище прикладі заголовок досить малий:

+ +
<head>
+  <meta charset="utf-8">
+  <title>My test page</title>
+</head>
+ +

Однак у більших сторінках заголовок може містити досить велику кількість інформації - спробуйте перейти на деякі з ваших улюблених веб-сайтів та за допомогою інструментів розробника перевірте вміст заголовку. Наша мета полягає не в тому, щоб показати вам, як використовувати все, що може бути поставлено в заголовок, а навчити вас використовувати найочевидніші речі, які ви хочете включити в заголовок і ознайомити з ними. Давайте розпочнемо.

+ +

Додавання назви сторінки

+ +

Ми вже бачили елемент елемент {{htmlelement("title")}} в дії — він може бути використаний для додавання назви (title) документа. Однак його можна зплутати з елементом {{htmlelement("h1")}}, який використовується для додавання заголовка верхнього рівня до вашого вмісту body - його також іноді називають заголовком сторінки. Але це різні речі!

+ + + +

Активне навчання: перевірка простого прикладу

+ +
    +
  1. Щоб розпочати це активне навчання, ми хотіли б, щоб ви перейшли на наш GitHub репозиторій та завантажили копію нашої title-example.html сторінки. Для цього також + +
      +
    1. Скопіюйте та вставте код із сторінки в новий текстовий файл у редакторі коду, а потім збережіть його в зручному місці.
    2. +
    3. Натисніть кнопку "Raw" на сторінці, яка призведе до появи вихідного коду на новій вкладці веб-браузера. Потім виберіть у меню вашого браузера  Файл > Зберегти як... а потім виберіть місце для збереження файлу.
    4. +
    +
  2. +
  3. Тепер відкрийте файл у своєму веб-браузері. Ви повинні побачити щось подібне: +

    A simple web page with the title set to <title> element, and the <h1> set to <h1> element. Тепер повинно бути абсолютно зрозуміло, в чому різниця між <h1> та <title>!

    +
  4. +
  5. Ви також маєте спробувати відкрити код в редакторі коду, відредагувати вміст цих елементів, а потім оновити сторінку у своєму веб-браузері. Поекспериментуйте з кодом, змінюючи його!
  6. +
+ +

Зміст елементу <title> також використовується в інший спосіб. Наприклад, якщо ви спробуєте закласти сторінку (Закладки > Закласти цю сторінку або значок зірки в адресному рядку в Firefox), ви побачите зміст <title> заповнений як назва закладки.

+ +

A webpage being bookmarked in firefox; the bookmark name has been automatically filled in with the contents of the <title> element

+ +

Вміст <title> також використовується в результатах пошуку, як ви побачите нижче.

+ +

Метадані: елемент <meta>

+ +

Метадані - це дані, які описують дані, і HTML має "офіційний" спосіб додавання метаданих до документа - елемент {{htmlelement("meta")}}. Звичайно, інші речі, про які ми говоримо в цій статті, також можуть розглядатися як метадані. Існує багато різних типів елементів <meta> які можуть бути включені в <head> вашої сторінки, але не будемо намагатись пояснити їх усі на даному етапі, оскільки це може вас заплутати. Замість цього ми пояснимо декілька речей, які ви, можливо, зазвичай бачите, щоб розібратись, що до чого.

+ +

Визначення кодування символів документа

+ +

У прикладі, показаному вище, цей рядок також включений:

+ +
<meta charset="utf-8">
+ +

Цей елемент просто вказує кодування символів документа - набір символів, який документ може використовувати. utf-8 - це універсальний набір символів, що включає практично будь-які символи з будь-якої людської мови. Це означає, що ваша веб-сторінка зможе обробляти будь-яку мову; тому правильно встановити це кодування на кожній веб-сторінці, яку ви створюєте! Наприклад, ваша сторінка може чудово відображатись англійською та японською мовами:

+ +

a web page containing English and Japanese characters, with the character encoding set to universal, or utf-8. Both languages display fine, Якщо ви встановите кодування символів, наприклад, ISO-8859-1,  (набір символів для латинського алфавіту), виведенний текст сторінок буде зіпсованим:

+ +

a web page containing English and Japanese characters, with the character encoding set to latin. The Japanese characters don't display correctly

+ +

Активне навчання: експеримент із кодуванням символів

+ +

Щоб спробувати це, перегляньте простий шаблон HTML, який ви отримали в попередньому розділі <title> (the title-example.html page), спробуйте змінити значення мета-кодування на ISO-8859-1, і додайте японську мову на свою сторінку. Це текст, який ми використовували (до речі, там написано "рис гарячий"):

+ +
<p>Japanese example: ご飯が熱い。</p>
+ +

Додавання автора та опису

+ +

Багато елементів <meta> містять атрибути name та content:

+ + + +

Два таких мета-елемента, які корисні для включення в сторінку, визначають автора сторінки та надають стислий опис сторінки. Давайте подивимось на приклад:

+ +
<meta name="author" content="Chris Mills">
+<meta name="description" content="Учбовий центр MDN спрямований на те,
+щоб надати всім новачкам в Інтернеті все, що їм необхідно знати,
+щоб приступити до розробки веб-сайтів і додатків.">
+ +

Вказівка імені автора корисна по кількох причинах: корисно вміти розібратися, хто написав сторінку, якщо ви захочете зв'язатися з ним з питаннями про вміст. Деякі системи керування вмістом (CMS) мають можливості для автоматичного виявлення інформації про автора сторінок та надання доступу до них.

+ +

Вказування опису, що містить ключові слова, що відносяться до вмісту вашої сторінки, є корисним, оскільки він може призвести до того, що ваша сторінка буде відображатися вище в результатах пошуку, що виконуються пошуковими системами (такі дії називаються Пошуковою оптимізацією, або {{glossary("SEO")}}.)

+ +

Активне навчання: використання опису в пошукових системах

+ +

Опис також використовується на сторінках результатів пошуку. Давайте пройдемо вправу, щоб вивчити це:

+ +
    +
  1. Перейдіть на головну сторінку Mozilla Developer Network.
  2. +
  3. Перегляньте джерело сторінки (клікніть правою кнопкою миші на сторінці, виберіть Програмний код сторінки (View Page Source) із контекстного меню.
  4. +
  5. Знайдіть опис метатегів. Він буде виглядати так: +
    <meta name="description" content="The Mozilla Developer Network (MDN) provides
    +information about Open Web technologies including HTML, CSS, and APIs for both
    +Web sites and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
    +
  6. +
  7. Тепер знайдіть "Mozilla Developer Network" у вашій улюбленій пошуковій системі (Ми використовуємо Yahoo.) Ви помітите опис елементів вмісту <meta> та <title>, що використовуються в результатах пошуку — безумовно їх варто вказувати! +

    A Yahoo search result for "Mozilla Developer Network"

    +
  8. +
+ +
+

Примітка: В Google ви побачите деякі важливі субсторінки MDN під посиланням на головну сторінку MDN - вони називаються посилання на сайт (sitelinks) і налаштовуються в інструментах Google для веб-майстрів Google's webmaster toolsце спосіб зробити результати пошуку вашого сайту кращими в пошуковій системі Google.

+
+ +
+

Примітка: Багато функцій <meta> більше не використовуються. Наприклад, ключове слово <meta> елемента (<meta name="keywords" content="заповнити, в, ваші, ключові, слова, тут">) — який повинен забезпечити ключові слова для пошукових систем, щоб визначити релевантність цієї сторінки для різних пошукових термінів - нині ігноруються пошуковими системами, оскільки спамери просто заповнювали список ключових слів на сторінці сотнями ключових слів, щоб їх сайти з'являлись в результатах пошуку якомога вище.

+
+ +

Інші типи метаданих

+ +

Мандруючи Інтернетом ви також можете знайти інші типи метаданих. Багато функцій, які ви бачитимете на веб-сайтах, є власне створеними, призначеними для надання деяким сайтам (наприклад, сайтам соціальних мереж) певної інформації, яку вони можуть використовувати.

+ +

Наприклад, Open Graph Data є протоколом метаданих, який Facebook винайшов для надання більш багатих метаданих для веб-сайтів. У коді MDN ви знайдете це:

+ +
<meta property="og:image" content="https://developer.cdn.mozilla.net/static/img/opengraph-logo.dc4e08e2f6af.png">
+<meta property="og:description" content="The Mozilla Developer Network (MDN) provides
+information about Open Web technologies including HTML, CSS, and APIs for both Web sites
+and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
+<meta property="og:title" content="Mozilla Developer Network">
+ +

Одним з ефектів цього є те, що, коли ви посилаєтеся на MDN на Facebook, посилання з'являється разом із зображенням та описом: більш зручно для користувачів.

+ +

Open graph protocol data from the MDN homepage as displayed on facebook, showing an image, title, and description.Twitter також має власні аналогічні запатентовані метадані, що мають подібний ефект, коли URL-адреса сайту відображається на twitter.com. Наприклад:

+ +
<meta name="twitter:title" content="Mozilla Developer Network">
+ +

Додавання власних іконок на сайт

+ +

Щоб ще більше збагатити дизайн сайту, ви можете в метадані додавати посилання на власні іконки, і вони будуть відображатися у певних контекстах.

+ +

Цей скромний значок, який існує протягом багатьох років, був першою піктограмою такого типу, значок 16 x 16 пікселів, який використовується в багатьох місцях. Ви побачите значки, які відображатимуться на вкладці веб-переглядача, що містять кожна відкрита сторінка, а також поруч зі сторінками, закладеними на панелі закладок.

+ +

Іконка може бути додана на сторінку за допомогою:

+ +
    +
  1. Зберігаючи її в тому самому каталозі, що й індексна сторінка сайту (index), збережена у форматі .ico (більшість браузерів підтримуватиме функцію favicons у більш поширених форматах, наприклад .gif або .png, але за допомогою формату ICO це гарантує, що він буде працювати ще в Internet Explorer 6).
  2. +
  3. Додайте наступний рядок в <head> HTML документу, щоб вказати іконку: +
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    +
  4. +
+ +

Ось приклад піктограми на панелі закладок:

+ +

The Firefox bookmarks panel, showing a bookmarked example with a favicon displayed next to it.

+ +

Також існує безліч інших типів іконок. Наприклад, ви знайдете їх в вихідному коді домашньої сторінки MDN:

+ +
<!-- third-generation iPad with high-resolution Retina display: -->
+<link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://developer.cdn.mozilla.net/static/img/favicon144.a6e4162070f4.png">
+<!-- iPhone with high-resolution Retina display: -->
+<link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://developer.cdn.mozilla.net/static/img/favicon114.0e9fabd44f85.png">
+<!-- first- and second-generation iPad: -->
+<link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://developer.cdn.mozilla.net/static/img/favicon72.8ff9d87c82a0.png">
+<!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
+<link rel="apple-touch-icon-precomposed" href="https://developer.cdn.mozilla.net/static/img/favicon57.a2490b9a2d76.png">
+<!-- basic favicon -->
+<link rel="shortcut icon" href="https://developer.cdn.mozilla.net/static/img/favicon32.e02854fdcf73.png">
+ +

У коментарях пояснюється, для чого використовується кожна іконка, наприклад, при додаванні сторінки на головний екран iPad буде використана іконка високої роздільної здатності.

+ +

Не хвилюйтеся щодо впровадження всіх цих типів іконок прямо зараз - це досить просунута функція, і від вас не очікується знання про це, щоб просунутися в курсі. Основна мета тут полягає в тому, щоб повідомити вам про такі речі, і не лякайтеся, якщо ви зустрінете їх під час перегляду вихідних кодів інших веб-сайтів.

+ +

Застосування CSS та JavaScript в HTML

+ +

Практично всі веб-сайти, якими ви користуєтесь на сьогоднішній день, використовують {{glossary("CSS")}} щоб виглядати класно та {{glossary("JavaScript")}} для роботи інтерактивних функцій, таких як відеоплеєри , карти, ігри тощо. Зазвичай пов'язані стилі додають на сторінку за допомогою елементу {{htmlelement("link")}}, а скрипти за допомогою елементу {{htmlelement("script")}} відповідно.

+ + + +

Активне навчання: застосування CSS та JavaScript на сторінці

+ +
    +
  1. Щоб розпочати це активне навчання, візьміть копії наших meta-example.html, script.js та style.css файлів, і збережіть їх на своєму комп'ютері в тій же директорії. Переконайтеся, що вони збережені з правильними іменами та розширеннями файлів.
  2. +
  3. Відкрийте файл HTML у вашому браузері та текстовий редактор.
  4. +
  5. Виконавши ці кроки, додайте до вашого HTML документу елементи {{htmlelement("link")}} та {{htmlelement("script")}}, щоб CSS та JavaScript застосувались до HTML-документу.
  6. +
+ +

Якщо все правильно зроблено, коли ви збережете свій HTML-код і оновите свій браузер, то побачите, що на сторінці все змінилося:

+ +

Example showing a page with CSS and JavaScript applied to it. The CSS has made the page go green, whereas the JavaScript has added a dynamic list to the page.

+ + + +
+

Примітка: Якщо ви застрягли в цій вправі і не можете застосувати CSS/JS на сторінці, то перегляньте нашу сторінку css-and-js.html з прикладом.

+
+ +

Встановлення основної мови документа

+ +

Нарешті, варто зазначити, що ви можете (і це необхідно) встановити мову своєї сторінки. Це можна зробити, додавши lang attribute (атрибут мови) до відкриваючого HTML-тегу (як показано в прикладі meta-example.html і показано нижче).

+ +
<html lang="en-US">
+ +

Це корисно в багатьох випадках. Ваш HTML-документ буде більш ефективно індексований пошуковими системами, які використовують це, щоб ефективніше індексувати сторінки — наприклад, показувати їх користувачам, які використовують відповідну мову (дозволяючи їй відображатися належним чином), і це корисно для людей з порушеннями зору, що використовують програми зчитування з екрана - скрінрідери (наприклад, слово "динозавр" говорять як українською, так й іншими мовами, але воно вимовляється по-різному).

+ +

Ви також можете встановити підрозділи вашого документа, щоб вони розпізнавались різними мовами. В нашому прикладі з фрагментом японською мовою правильно вказати мову так:

+ +
<p>Japanese example: <span lang="jp">ご飯が熱い。</span>.</p>
+ +

Ці коди визначаються стандартом ISO 639-1. Ви можете дізнатись більше про них в Language tags in HTML and XML.

+ +

Підсумок

+ +

На цьому закінчим наш короткий огляд заголовку HTML — там ще багато всього корисного, але зараз повний перелік буде нудним і заплутає вас. Ви вже маєте загальне уявлення про найпоширеніші і використовуваніші елементи. У наступній статті ми розглянемо основи розмітки тексту в HTML.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML")}}

+ +

 

+ +

 

diff --git a/files/uk/learn/html/multimedia_and_embedding/index.html b/files/uk/learn/html/multimedia_and_embedding/index.html new file mode 100644 index 0000000000..6dccf89410 --- /dev/null +++ b/files/uk/learn/html/multimedia_and_embedding/index.html @@ -0,0 +1,55 @@ +--- +title: Вставки мультимедіа +slug: Learn/HTML/Multimedia_and_embedding +translation_of: Learn/HTML/Multimedia_and_embedding +--- +

{{LearnSidebar}}

+ +

До цього часу ми переглянули багато тексту в цьому курсі, але Інтернет буде справді нудним лише за допомогою тексту. Давайте почнемо дивитись на те, як зробити веб-сайт живим, з більш цікавим вмістом! Цей модуль вивчає, як використовувати HTML для включення мультимедійних даних на ваші веб-сторінки, в тому числі різні способи додавання зображень, а також можливість вставки відео, аудіо та навіть цілих веб-сторінок.

+ +

Передумови

+ +

Перш ніж запускати цей модуль, ви повинні мати достатні знання про основи HTML, як це було описано раніше в "Вступ до HTML". Якщо ви не працювали через цей модуль (або щось подібне), спочатку спробуйте його, а потім поверніться!

+ +
+

Примітка: Якщо ви працюєте на комп'ютері / планшеті / іншому пристрої, де ви не можете створювати власні файли, ви можете спробувати (більшість) прикладів коду в онлайн-програмі кодування, наприклад JSBin або Thimble.

+ +

 

+
+ +

Довідники

+ +

Цей модуль містить наступні статті, в яких ви знайдете всі основи вставки мультимедіа на веб-сторінках.

+ +
+
Зображення у форматі HTML
+
Існують і інші види мультимедійних засобів, але це логічно починати з скромного елемента {{htmlelement ("img")}}, який використовується для вставки простого зображення на веб-сторінку. У цій статті ми подивимося, як використовувати його більш глибоко, включаючи основні, анотований його підписом за допомогою {{htmlelement ("figure")}} і як він відноситься до фонових зображень CSS.
+
Відео та аудіозапис
+
Далі ми розглянемо, як використовувати HTML5 елементи {{htmlelement ("video")}} та {{htmlelement ("audio")}}, щоб вставити відео та аудіо на наші сторінки; включаючи основи, надання доступу до різних форматів файлів до різних веб-переглядачів, додавання субтитрів та субтитрів, а також можливість додавання відмов для застарілих веб-переглядачів.
+
Від <object> до <iframe> - інші технології вбудовування
+
На цьому етапі ми хотіли б трохи побороти крок, поглянувши на кілька елементів, які дозволяють вставляти різноманітні типи вмісту на свої веб-сторінки: {{htmlelement ("iframe")}}, елементи {{htmlelement ("embed")}} і {{htmlelement ("object")}}.  <iframe> для вбудовування інших веб-сторінок, а інші два дозволяють вставляти PDF-файли, SVG і навіть Flash-технологію на виході, але які ви все ще можете побачити напів-регулярно.
+
Додавання векторної графіки до Інтернету
+
Векторна графіка може бути дуже корисною в певних ситуаціях. На відміну від звичайних форматів, таких як PNG / JPG, вони не спотворюють / пікселюються при збільшенні - вони можуть залишатися гладкими при масштабування. Ця стаття знайомить вас із векторною графікою та як включити популярний {{glossary ("SVG")}} формат на веб-сторінках.
+
Відповідні зображення
+
За допомогою настільки різних типів пристроїв, які тепер можуть переглядати веб-сайти - від мобільних телефонів до настільних комп'ютерів - важливим поняттям для оволодіння сучасним веб-сайтом є чудовий дизайн. Це стосується створення веб-сторінок, які можуть автоматично змінювати свої функції відповідно до різних розмірів екрана, дозволів і т. Д. Це буде детально розглянуто в модулі CSS пізніше, але зараз ми розглянемо інструменти HTML доступний для створення чутливих зображень, включаючи елемент {{htmlelement ("picture")}}.
+
+ +

Оцінки

+ +

Наступні оцінки допоможуть перевірити розуміння базових основ HTML, описаних вище в посібниках.

+ +
+
Сторінка сплесків Mozilla
+
У цій оцінці ми перевіримо ваші знання про деякі методи, описані в статтях цього модуля, що допоможе вам додати деякі зображення та відео на приголомшливу сторінку про все про Mozilla!
+
+ +

Дивись також

+ +
+
Додайте візитну карту догори зображення
+
Карти зображень забезпечують механізм створення різних частин посилання на зображення на різні місця (подумайте про карту, посилаючись на додаткову інформацію про кожну країну, на яку ви натискаєте). Ця техніка іноді може бути корисною.
+
Основи веб-грамотності 2
+
+

Відмінний курс навчання Mozilla, який вивчає та випробовує деякі з навичок, про які говорили в модулі мультимедіа та вбудовування. Зануртеся в основу створення веб-сторінок, розробки для доступності, спільного використання ресурсів, використання онлайн-засобів масової інформації та відкритої роботи (це означає, що ваш вміст є вільно доступним і доступним для обміну іншими користувачами).

+
+
diff --git a/files/uk/learn/html/tables/index.html b/files/uk/learn/html/tables/index.html new file mode 100644 index 0000000000..3e5350587c --- /dev/null +++ b/files/uk/learn/html/tables/index.html @@ -0,0 +1,40 @@ +--- +title: HTML-таблиці +slug: Learn/HTML/Tables +translation_of: Learn/HTML/Tables +--- +
{{LearnSidebar}}
+ +

Доволі поширеним завданням в HTML є структуризація табличних даних, і HTML має набір елементів та атрибутів саме для таких цілей. В поєднанні з CSS для стилізації, HTML полегшує відображення в інтернеті такої інформації, як шкільний навчальний план, розклад занять у вашому басейні, або статистику про ваших улюблених динозаврів чи футбольні команди. Даний модуль містить усе, що необхідно знати про структуризацію табличних даних за допомогою HTML.

+ +

Передумови

+ +

Перед тим як почати даний модуль, ви повинні пройти базовий курс HTML — дивіться Вступ до HTML.

+ +
+

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

+
+ +

Зміст

+ +

Даний модуль містить наступні статті:

+ +

Основи HTML таблиць

+ +
+
Дана стаття дозволить вам розпочати роботу з HTML таблицями, ознайомить з такими основними поняттями як рядки та клітини, заголовки, як розширити клітини на декілька колонок та рядків, а також як згрупувати усі клітини разом з метою стилізації.
+
+ +

Особливості та доступність HTML таблиць

+ +
+
В другій статті даного модулю ми більш детально розгядаємо особливості HTML таблиць - такі як captions/summaries та групування рядків в head, body та footer секції вашої таблиці - а також розглядаємо доступність таблиць для користувачів з вадами зору.
+
+ +

Оцінювання

+ +
+
Структуризація даних про планети
+

+ У нашій табличній оцінці ми надаємо вам деякі дані про планети в нашій сонячній системі, які ви зможете структурувати в HTML таблицю.
+
diff --git a/files/uk/learn/index.html b/files/uk/learn/index.html new file mode 100644 index 0000000000..ad19811666 --- /dev/null +++ b/files/uk/learn/index.html @@ -0,0 +1,112 @@ +--- +title: Вчимо веб-розробку +slug: Learn +tags: + - WWW + - Веб + - Покажчик + - Початківець + - вивчення +translation_of: Learn +--- +
{{LearnSidebar}}
+ +
+

Ласкаво просимо до навчальної зони MDN. Ці статті покликані забезпечити початківців у веб-розробці всім необхідним, аби почати писати код простих сайтів.

+
+ +

Мета цієї частини MDN не в тому, щоб зробити вас з «початківця» відразу «експертом» , а зробити вас «знаючим». Потім ви самі зможете вибрати подальший шлях, вивчаючи решту MDN, та інші розширені та професійні ресурси, що будуть підсумовувати попередні знання.

+ +

Якщо ви цілковитий початківець, веб-розробка може стати певним викликом для вас — ми підтримаємо вас та дамо детальну інформацію, щоб ви почували себе комфортно та вивчили тему як слід. Почувайте себе як риба у воді, незалежно від того, чи ви студент, який вивчає веб-розробку (самостійно або в аудиторії), вчитель, який шукає матеріали для занять, аматор або просто прагнете детальніше зрозуміти, як працють веб-технології.

+ +
+

Важливо: Вміст навчальної зони постійно оновлюється. Якщо ви маєте запитання стосовно тем, які на вашу думку не висвітлені, зверніться до секції {{anch("Зв'яжіться з нами")}} нижче.

+
+ +

З чого почати

+ + + +
+

Нотатка: Наш Словник надає визначення термінологій.

+
+ +

{{LearnBox({"title":"Випадковий запис в словнику"})}}

+ +

Охоплені теми

+ +

Нижче наведено список усіх тем, які ми розглядаємо в навчальній зоні MDN.

+ +
+
Початок роботи з Інтернетом
+
Забезпечує практичне введення до веб-розробки для цілковитих початківців.
+
HTML - структурування інтернету
+
HTML - це мова, яку ми використовуємо для структурування різних частин нашого вмісту та визначення їх змісту чи призначення. Ця тема детально вчить HTML.
+
CSS — стилізація інтернету
+
CSS - це мова, яку ми можемо використовувати для зміни вигляду та представлення веб-контенту, а також додавання поведінки, як-от анімація. Ця тема всебічно охоплює CSS.
+
JavaScript — динамічні сценарії на стороні клієнта
+
JavaScript - це скриптова мова, що використовується для додавання динамічних функцій веб-сторінкам. Ця тема викладає всі необхідні, для комфортного написання та розуміння JavaScript, елементи.
+
Доступність — зробити інтернет зручним для всіх
+
Доступність - це практика створення веб-контенту для максимально можливої кількості людей незалежно від інвалідності, пристрою, мови та інших факторів, що відрізняються. Ця тема дає вам все, що вам потрібно знати.
+
Інструменти та тестування
+
Ця тема охоплює інструменти, які розробники використовують для полегшення їх роботи, як-от інструменти крос-браузерного тестування.
+
Програмування сайту на стороні сервера
+
Навіть якщо ви зосереджені на розробці веб-сторінок на стороні клієнта, корисно знати про те, як працюють сервери та серверні компоненти коду. Тема дає загальне уявлення про те, як працює серверна частина, а також докладні підручники, в яких описано, як створити серверну програму за допомогою двох популярних фреймворків — Django (Python) та Express (node.js). 
+
+ +

Отримання прикладів нашого коду

+ +

Всі приклади коду, які ви зустрінете в зоні навчання, доступні на GitHub. Якщо ви хочете скопіювати їх усі на свій комп'ютер, найпростішим способом є:

+ +
    +
  1. Встановіть Git на вашу машину. Це основне програмне забезпечення системи керування версіями, на якому працює GitHub.
  2. +
  3. Отримайте обліковий запис на GitHub.
  4. +
  5. Після реєстрації, увійдіть на github.com за допомогою свого імені користувача та пароля.
  6. +
  7. Відкрийте командний рядок комп'ютера (Windows) або термінал (Linux, macOS).
  8. +
  9. Щоб скопіювати репозиторій зони навчання до папки під назвою learning area у поточному розташуванні, яке вказує ваш командний рядок/термінал, скористайтеся цією командою: +
    git clone https://github.com/mdn/learning-area
    +
  10. +
  11. Тепер ви можете ввести каталог та потім знаходити ваші файли, (використовуючи шукач/файловий провідник або команду cd).
  12. +
+ +

Ви можете оновити репозиторій learning-area з будь-якими змінами, внесеними до основної версії на GitHub, таким чином:

+ +
    +
  1. У командному рядку/терміналі перейдіть до каталогу learning-area, використовуючи cd. Наприклад, якщо ви були в батьківському каталозі: + +
    cd learning-area
    +
  2. +
  3. Оновіть репозиторій, використовуючи таку команду: +
    git pull
    +
  4. +
+ +

Зв'яжіться з нами

+ +

Якщо ви хочете зв'язатись з нами з будь-якої підстави, надішліть нам листа на поштові списки або в IRC канал. Ми хочемо дізнатись вашу думку стосовно помилок та неточностей на сайті, запити нових навчальних тем, запити про допомогу по незрозумілим інструментам чи будь-що інше.

+ +

Якщо ви зацікавлені розвивати/вдосконалювати зміст, погляньте Як ви можете допомогти, і дайтесь чути! Ми будемо надзвичайно щасливі поспілкуватись з вами, не дивлячись на те, хто ви — студент, викладач, досвідчений веб-розробник або будь-хто зацікавлений допомогти у вдосконалені навчального досвіду.

+ +

Дивіться також

+ +
+
Mozilla Developer Newsletter
+
Наш інформаційний бюлетень для веб-розробників, який є чудовим ресурсом для всіх рівнів досвіду.
+
Codecademy
+
Чудовий інтерактивний сайт для вивчення мов програмування з нуля.
+
Code.org
+
Базова теорія написання коду та практика, здебільшого для дітей та повних новачків.
+
EXLskills 
+
Безкоштовні та відкриті курси для вивчення технічних навичок, з наставництвом та проектом навчання
+
Web Literacy Map
+
Платформа для початкового рівня веб-грамотності та навичок 21 століття, що також забезпечує доступ до викладацьких матеріалів, відсортованих за категоріями.
+
Teaching activities
+
Серія навчальних матеріалів для викладання (та навчання), створених Фондом Мозіла, що охоплює все, починаючи від базової грамотності в Інтернеті та конфіденційності, до JavaScript і зламу Minecraft.
+
Edabit
+
Сотні безкоштовних інтерактивних завдань по кодуванню на різних мовах.
+
diff --git a/files/uk/learn/javascript/client-side_web_apis/index.html b/files/uk/learn/javascript/client-side_web_apis/index.html new file mode 100644 index 0000000000..ee5df2ea53 --- /dev/null +++ b/files/uk/learn/javascript/client-side_web_apis/index.html @@ -0,0 +1,43 @@ +--- +title: Веб-APIs на стороні клієнта +slug: Learn/JavaScript/Client-side_web_APIs +translation_of: Learn/JavaScript/Client-side_web_APIs +--- +
{{LearnSidebar}}
+ +
При написанні клієнтського JavaScript для веб-сайтів або додатків, ви досить скоро зустрінитесь з Інтерфейсами для Програмування Додатків (APIs). APIs є функціями програмування, що надають можливість маніпулювання різними аспектами браузера та операційної системи, на якій працює сайт, або обробки даних з інших веб-сайтів або службю. У цьому модулі ми розглянемо, що таке API, і як використовувати деякі з найбільш поширених API, які ви часто зустрічаєте в процесі розробки.
+ +

Prerequisites

+ +

Щоб даний модуль був максимально корисним, ми рекомендуємо вам пройти попередні JavaScript модулі у серії (First steps, Building blocks, та JavaScript objects). Дані модулі, як правило, передбачають просте використання API, тому що зачасту досить важко писати приклади клієнтського JavaScript без них. Для даної інструкції ми припустимо, що ви ознайомлені з основами мови JavaScript, та вивчимо загальні Web APIs більш детально.

+ +

Базові знання HTML та CSS також будуть корисними.

+ +
+

Note: If you are working on a device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

+
+ +

Guides

+ +
+
Introduction to web APIs
+
Перш за все, ми почнемо з розгляду APIs з високого рівня - що вони собою представляють, як вони працюють, як використовувати їх у власному коді та яку вони мають структуру? Ми також розглянемо, що таке різні основні класи APIs та як вони використовуються.
+
+ +
+
Manipulating documents
+
При написанні веб-сторінок і додатків однією з найпоширеніших речей, яку ви захочете зробити це маніпуляція веб-документами. Зазвичай це робиться за допомогою об'єктної моделі документа (DOM), набору API для керування HTML та інформацією про стиль, яка використовує об'єкт {{domxref ("Document")}}. У цій статті ми детально розглянемо, як використовувати DOM, а також деякі інші цікаві API, які можуть змінити ваше середовище цікавими способами.
+
Fetching data from the server
+
Іншим дуже поширеним завданням на сучасних веб-сайтах і додатках є отримання окремих елементів даних з сервера для оновлення розділів веб-сторінки без необхідності завантажувати абсолютно нову сторінку. Ця, здавалося б, невелика деталь мала величезний вплив на продуктивність і поведінку сайтів. У цій статті ми пояснимо концепцію і розглянемо технології, які роблять це можливим, наприклад, {{domxref ("XMLHttpRequest")}} і Fetch API.
+
Third party APIs
+
APIs, які ми розглянули є вбудованими в браузер, але не всі APIs є частиною браузерів. Багато великих веб-сайтів і служб, таких як Google Maps, Twitter, Facebook, PayPal тощо, надають API, що дозволяють розробникам використовувати свої дані (наприклад, показувати ваш Twitter  у вашому блозі) або послуги (наприклад, показувати індивідуально налаштовані Google Maps на вашому сайті або використання логіна Facebook для входу в систему користувачів. У цій статті розглядаються відмінності між API браузера та APIs третьої сторони і показано деякі типові використання останнього.
+
+ +
+
Drawing graphics
+
Браузер містить деякі дуже потужні засоби графічного програмування, від мови масштабованої векторної графіки (SVG), до APIs для малювання елементів HTML {{htmlelement ("canvas")}} (див. The Canvas API та WebGL). Ця стаття містить вступ до Canvas API, а також додаткові ресурси, які дозволять вам дізнатися більше.
+
Video and audio APIs
+
HTML5 поставляється з елементами для вбудовування мультимедійних даних у документи - {{htmlelement ("відео")}} і {{htmlelement ("аудіо")}} - які, в свою чергу, мають власні APIs для керування відтворенням, пошуком і т.д. Дана стаття демонструє, як виконувати звичайні завдання, наприклад, створювати власні елементи керування відтворенням.
+
Client-side storage
+
Сучасні веб-браузери мають ряд різних технологій, які дозволяють зберігати дані, пов'язані з веб-сайтами, і отримувати їх у разі необхідності, дозволяючи зберігати дані на довгий термін, зберігати сайти в автономному режимі та багато іншого. У цій статті пояснюються основи як це все працює.
+
diff --git a/files/uk/learn/javascript/first_steps/index.html b/files/uk/learn/javascript/first_steps/index.html new file mode 100644 index 0000000000..023c9c97e6 --- /dev/null +++ b/files/uk/learn/javascript/first_steps/index.html @@ -0,0 +1,69 @@ +--- +title: Перші кроки у JavaScript +slug: Learn/JavaScript/First_steps +tags: + - Arrays + - Article + - Assessment + - Beginner + - CodingScripting + - Guide + - JavaScript + - Landing + - Module + - Numbers + - Operators + - Variables + - maths + - strings + - Мова + - Україньська +translation_of: Learn/JavaScript/First_steps +--- +
{{LearnSidebar}}
+ +

У нашому першому модулі JavaScript ми спочатку відповімо на деякі фундаментальні питання, такі як "Що таке JavaScript?", "Як він виглядає?" Та "Що він може робити?", Перш ніж перейти до першого практичного досвіду написання JavaScript. Після цього ми детально обговоримо деякі основні елементи, такі як змінні, рядки, числа та масиви.

+ +

Передумови

+ +

Для того щоб почати з цього модуля, вам не потрібні попередні знання JavaScript, однак ви повинні бути добре знайомі з HTML та CSS. Перед початком роботи з JavaScript вам рекомендується виконати такі модулі:

+ + + +
+

Примітка: Якщо ви працюєте на комп'ютері / планшеті / іншому пристрої, де ви не можете створювати власні файли, можна спробувати (більшість) прикладів коду в онлайн-програмі кодування, наприклад, JSBin або Thimble.

+
+ +

Посібники

+ +
+
Що таке JavaScript?
+
Ласкаво просимо до курсу JavaScript для новачків MDN! У цій першій статті ми розглянемо JavaScript з висоти, відповідаючи на такі запитання, як "що це таке?" Та "що воно робить?", і переконаємось у тому, що JavaScript відповідає вашим вимогам.
+
Перші спроби на JavaScript
+
Тепер ви дізнались щось про теорію JavaScript, і що ви можете з ним робити, ми збираємося дати вам курс по написанню основних функцій JavaScript за допомогою повністю практичного підручника. Тут ви створите просту гру "Вгадай номер", крок за кроком.
+
Що пішло не так? Усунення несправностей JavaScript
+
Коли ви створили гру "Вгадай номер" в попередній статті, ви помітили, що программа не працює. Ніколи не бійтеся - ця стаття спрямована на те, щоб позбавити вас від виривання волосся на голові при виникненні таких проблем, надаючи вам прості поради щодо того, як знайти та виправити помилки у програмах JavaScript.
+
Збереження потрібної вам інформації - змінні
+
Тепер прочитавши останні пару статей, ви повинні знати, що таке JavaScript, що він може зробити для вас, як вам використовувати його разом з іншими веб-технологіями та які його функції є високорівневими. У цій статті ми перейдемо до справжніх основ дивлячись як працювати з основними будівельними блоками JavaScript-змінних.
+
Основи математики в JavaScript - цифри та оператори
+
На цьому етапі ми обговорюємо математику в JavaScript - як ми можемо об'єднати оператори та інші функції, щоб успішно оперувати числами в наших командах.
+
Обробка текстових рядків у JavaScript
+
Далі ми звернемо увагу на рядки - що є фрагментами тексту при програмуванні. У цій статті ми розглянемо всі загальні речі, які ви повинні знати про рядки при вивченні JavaScript, такі як створення рядків, використання лапок в рядку, та їх об'єднання.
+
Корисні рядкові методи
+
Тепер коли ми розглянули основи рядків, давайте перейдемо до механізму та почнемо вивчати корисні операції які ми можемо виконувати в рядках за допомогою вбудованих методів, таких як пошук довжини текстового рядка, об'єднання та розбиття рядків, заміна одного символу в рядку іншим, і так далі.
+
Масиви
+
У заключній статті цього модуля ми розглянемо масиви - обережний спосіб зберігання списку елементів даних під одним ім'ям змінної. Тут ми розглянемо, чому це корисно, а потім навчимось створювати масиви, витягувати, додавати і видаляти елементи, що зберігаються в масиві, і інше.
+
+ +

Оцінки

+ +

Наступна оцінка перевірить ваше розуміння базових правил JavaScript, описаних вище в посібниках.

+ +
+
Генератор випадкових історій
+
У цьому оцінюванні вам буде запропоновано застосувати деякі знання, здобуті у статтях цього модуля, і застосувати їх для створення веселого прикладу, який генеруватиме випадкові історії. Порозважайтеся!
+
diff --git a/files/uk/learn/javascript/first_steps/what_is_javascript/index.html b/files/uk/learn/javascript/first_steps/what_is_javascript/index.html new file mode 100644 index 0000000000..a3ca8c054d --- /dev/null +++ b/files/uk/learn/javascript/first_steps/what_is_javascript/index.html @@ -0,0 +1,422 @@ +--- +title: What is JavaScript? +slug: Learn/JavaScript/First_steps/What_is_JavaScript +translation_of: Learn/JavaScript/First_steps/What_is_JavaScript +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}
+ +
Ласкаво просимо до курсу для новачків від MDN! В цій статті ми подивимося на JavaScript в загальному, пробуючи дати відповідь на запитання "Що це таке?" і "Що ти можеш з ним зробити?". Нашою ціллю буде ознайомити тебе з метою JavaScript-та в ІТ сфері.
+ + + + + + + + + + + + +
Потрібні знання:Базове розуміння культури програмування, базові знання HTML і CSS
Ціль: +

Отримати розуміння, що таке JavaScript, на що він здатний, і як він забезпечує роботу веб сторінок

+
+ +

Поверхневе визначення

+ +

JavaScript - це мова програмування, що дозволяє тобі створювати складні речі на веб сторінках. Якщо веб сторінка робить, щось більше ніж просто показує статичну інформацію, наприклад: виконує моніторинг в реальному часі, інтерактивні карти, анімовану 2D/3D графіку, здатна на параллакс-скроллинг - ти можеш бути досить впевненим, що це без JavaScript там не обійшлося. Це є третій шар стандартного веб торту, з двома з них (HTML і CSS) ми ознайомилися в більших деталях в інших частинах курсу Навчальної зони (Learning Area).

+ +

+ + + +

The three layers build on top of one another nicely. Let's take a simple text label as an example. We can mark it up using HTML to give it structure and purpose:

+ +
<p>Player 1: Chris</p>
+ +

+ +

Then we can add some CSS into the mix to get it looking nice:

+ +
p {
+  font-family: 'helvetica neue', helvetica, sans-serif;
+  letter-spacing: 1px;
+  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;
+}
+ +

+ +

And finally, we can add some JavaScript to implement dynamic behaviour:

+ +
const para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  let name = prompt('Enter a new name');
+  para.textContent = 'Player 1: ' + name;
+}
+
+ +

{{ EmbedLiveSample('A_high-level_definition', '100%', 80, "", "", "hide-codepen-jsfiddle") }}

+ +

Try clicking on this last version of the text label to see what happens (note also that you can find this demo on GitHub — see the source code, or run it live)!

+ +

JavaScript can do a lot more than that — let's explore what in more detail.

+ +

So what can it really do?

+ +

The core client-side JavaScript language consists of some common programming features that allow you to do things like:

+ + + +

What is even more exciting however is the functionality built on top of the client-side 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:

+ +
const para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  let 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 consoleTypeError: 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. The code is received in its programmer-friendly text form and processed directly from that.

+ +

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. The program is executed from a binary format which was generated from the original program source code.

+ +

JavaScript is a lightweight interpreted programming language. The web browser receives the JavaScript code in its original text form and runs the script from that. From a technical standpoint, most modern JavaScript interpreters actually use a technique called just-in-time compiling to improve performance; the JavaScript source code gets compiled into a faster, binary, format while the script is being used, so that it can be run as quickly as possible. However, JavaScript is still considered an intepreteted language, since the compilation is being handled at run time, rather than ahead of time.

+ +

There are advantages to both types of language, but we won't discuss them right now.

+ +

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 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, 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() {
    +    let para = document.createElement('p');
    +    para.textContent = 'You clicked the button!';
    +    document.body.appendChild(para);
    +  }
    +
    +  const buttons = document.querySelectorAll('button');
    +
    +  for(let 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() {
    +  let para = document.createElement('p');
    +  para.textContent = 'You clicked the button!';
    +  document.body.appendChild(para);
    +}
    +
    +const buttons = document.querySelectorAll('button');
    +
    +for(let 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() {
+  let 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_js_example', '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:

+ +
const buttons = document.querySelectorAll('button');
+
+for(let 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 defer attribute, which tells the browser to continue downloading the HTML content once the <script> tag element has been reached.

+ +
<script src="script.js" defer></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 defer attribute solved the problem for us. We didn't use the defer solution for the internal JavaScript example because defer only works for external scripts.

+
+ +

An 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 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.

+ +

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 appends it to the bottom of the HTML body.
+
+function createParagraph() {
+  let para = document.createElement('p');
+  para.textContent = 'You clicked the button!';
+  document.body.appendChild(para);
+}
+
+/*
+  1. Get references to all the buttons on the page in an array format.
+  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.
+*/
+
+const buttons = document.querySelectorAll('button');
+
+for (let i = 0; i < buttons.length ; i++) {
+  buttons[i].addEventListener('click', createParagraph);
+}
+ +
+

Note: In general more comments is usually better than less, but you should be careful if you find yourself adding lots of comments to explain what variables are (your variable names perhaps should be more intuitive), or to explain very simple operations (maybe your code is overcomplicated).

+
+ +

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/uk/learn/javascript/index.html b/files/uk/learn/javascript/index.html new file mode 100644 index 0000000000..151ff7435e --- /dev/null +++ b/files/uk/learn/javascript/index.html @@ -0,0 +1,65 @@ +--- +title: JavaScript +slug: Learn/JavaScript +tags: + - Beginner + - CodingScripting + - JavaScript + - JavaScripting beginner + - Landing + - Module + - Topic + - Мова + - Українська +translation_of: Learn/JavaScript +--- +
{{LearnSidebar}}
+ +

{{Glossary("JavaScript")}} — це мова програмування, що дозволяє вам створювати живі, динамічні веб-сторінки. Кожного разу, коли веб-сторінка робить більше, ніж просто відображає Вам статичну інформацію для перегляду, відображає своєчасне оновлення вмісту або інтерактивні карти або анімовану 2D / 3D-графіку, або прокручує відео в медіапрогравачі, і таке інше — ви можете бути впевнені, що це робота JavaScript.

+ +

Навчальний шлях

+ +

Навряд чи JavaScript важче вивчати, ніж суміжні технології, такі як HTML та CSS. Але перш ніж намагатися вивчити JavaScript, вам настійно рекомендується спочатку ознайомитись хоча б з цими двома технологіями та, можливо, з деякими іншими. Почніть свою роботу з таких модулів:

+ + + +

Попередній досвід роботи з іншими мовами програмування також може допомогти.

+ +

Ознайомившись з основами JavaScript, ви повинні бути в курсі більш досконалих тем, наприклад:

+ + + +

Модулі

+ +

Ця тема містить наступні модулі в запропонованому порядку для роботи з ними.

+ +
+
Перші кроки JavaScript
+
У нашому першому модулі JavaScript ми спочатку відповімо на деякі фундаментальні питання, такі як "Що таке JavaScript?", "Як він виглядає?" Та "Що він може робити?", Потім ми перйдемо до першого практичного завданя з написання JavaScript. Після цього ми докладно розглянемо деякі ключові функції JavaScript, такі як змінні, рядки, числа та масиви.
+
Структурні блоки JavaScript
+
У цьому модулі ми продовжуємо охоплювати всі основні фундаментальні функції JavaScript, звертаючи увагу на ті типи блоків коду які нам будуть часто зустрічатися, такі як умовні вирази, цикли, функції та події. Ви вже бачили цей матеріал в курсі, тільки тут ми все це розглянемо дитально.
+
Представляємо об'єкти JavaScript
+
У JavaScript більшість речей - це об'єкти, від основних функцій, як рядки та масиви, до API браузера, побудованого на вершині JavaScript. Ви навіть можете створити свої власні об'єкти, щоб інкапсулювати пов'язані функції та змінні в ефективні пакети. Об'єктно-орієнтований характер JavaScript важливо зрозуміти, якщо ви хочете піти далі з вашими знаннями мови та написати більш ефективний код, тому ми надали цей модуль, щоб допомогти вам. Тут ми детально вивчимо теорію об'єктів та синтаксис, подивимося як створити власні об'єкти, з'ясуємо що таке дані JSON, і як працювати з ним.
+
Веб-API на стороні клієнта
+
Під час написання JavaScript-клієнта для веб-сайтів або програм ви не заходите дуже далеко, перш ніж почати використовувати API-інтерфейси для роботи з різними аспектами браузера та операційної системи, на якому працює сайт, або навіть дані з інших веб-сайтів або послуги. У цьому модулі ми вивчимо, які API існують та як використовувати деякі з найпоширеніших API, які часто зустрічаються в роботі з розробкою.
+
+ +

Вирішення загальних проблем JavaScript

+ +

Використовуйте JavaScript, щоб вирішувати поширені проблеми, це посилання на розділи, що пояснюють, як використовувати JavaScript для вирішення дуже поширених проблем при створенні веб-сторінок.

+ +

Див. також

+ +
+
JavaScript на MDN
+
Основне джерело для документації JavaScript на MDN - тут ви знайдете великі довідкові документи з усіх аспектів мови JavaScript та деякі розширені навчальні посібники, націлені на досвідчених JavaScript програмістів.
+
Кодування математики
+
Відмінна серія відео уроків з вивчення математики яку ви повинні розуміти щоб бути ефективним програмістом, від Кейта Пітерса.
+
diff --git a/files/uk/learn/javascript/objects/basics/index.html b/files/uk/learn/javascript/objects/basics/index.html new file mode 100644 index 0000000000..e7bc44b38b --- /dev/null +++ b/files/uk/learn/javascript/objects/basics/index.html @@ -0,0 +1,259 @@ +--- +title: Основи об'єктів в JavaScript +slug: Learn/JavaScript/Objects/Basics +tags: + - JavaScript + - this + - Об'єкт + - Основи об'єктів + - Синтаксис +translation_of: Learn/JavaScript/Objects/Basics +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}
+ +

В цій статті ми розглянемо основи синтаксису JavaScript об'єктів і заново вивчимо деякий функціонал JavaScript, який ми досліджували  раніше на курсі, підтверджуючи той факт, що велика частина функціоналу, з яким ми вже зіткнулись, в дійсності є об'єктами.

+ + + + + + + + + + + + +
Необхідні знання:Елементарна комп'ютерна грамотність, базове розуміння HTML та CSS, знайомство з основами JavaScript (див. First steps та Building blocks).
Мета:Розуміння основ теоріі об'єктно-орієнтованого програмування, як це пов'язано з JavaScript ("більшість речей є об'єктами'), і як почати роботу з об'єктами JavaScript.
+ +

Основи об'єктів

+ +

Об'єкт - це сукупність пов'язаних даних і/або функціональності (які зазвичай складаються з декількох змінних і функцій, які називаються властивостями та методами, якщо вони знаходяться всередині об'єктів). Давайте розберемо приклад , щоб показати, як вони виглядають.

+ +

Щоб почати, скопіюйте собі oojs.html файл. У ньому міститься дуже мало —  {{HTMLElement("script")}} елемент для написання нашого вихідного коду. Ми будемо використовувати це як основу для вивчення основ синтаксису об'єктів. Під час роботи з цим прикладом ви повинні відкрити developer tools JavaScript console, щоб вводити деякі команди.

+ +

Як і в багатьох випадках в JavaScript, створення об'єкту часто починається з визначення та ініціалізації змінної. Спробуйте ввести наступний нижче код в завантажений файл JavaScript, а потім збережіть і оновіть сторінку:

+ +
var person = {};
+ +

Якщо ви введете person в консоль JS і натиснете кнопку, то повинні отримати наступний результат:

+ +
[object Object]
+ +

Вітаємо, ви щойно створили свій перший об'єкт. Але це порожній об'єкт, тому ми не можемо з ним багато чого зробити. Давайте доповнимо наш об'єкт, щоб він виглядав так:

+ +
var 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] + '.');
+  }
+};
+
+ +

Після збереження та оновлення спробуйте ввести деякі з наведених нижче елементів у консолі JS:

+ +
person.name[0]
+person.age
+person.interests[1]
+person.bio()
+person.greeting()
+ +

Тепер всередині об'єкта є деякі дані та функціонал, і тепер до них можна отримати доступ за допомогою легкого і простого синтаксису!

+ +
+

Заувага: Якщо у вас виникли проблеми із застосуванням файлу в роботі, спробуйте порівняти свій код з нашою версією  — див. oojs-finished.html (також see it running live). Одна з найпоширеніших помилок, коли ви починаєте роботу з об'єктами, ставити кому в кінці останнього члена - це призводить до помилки.

+
+ +

Отже, що тут відбувається? Об'єкт складається з декількох елементів, кожен з яких має назву (наприклад, name та age вище), і значення (наприклад, ['Bob', 'Smith'] та 32). Кожна пара назва/значення повинна бути відокремлена комою, а назва і значення в кожному випадку розділяються між собою двокрапкою. Синтаксис завжди дотримується цього шаблону:

+ +
var objectName = {
+  member1Name: member1Value,
+  member2Name: member2Value,
+  member3Name: member3Value
+}
+ +

Значенням члена об'єкта може бути майже все — в нашому об'єкті person є рядок, число, два масиви та дві функції.  Перші чотири елементи є елементами даних, що відносяться до властивостей об'єкта. Останні два елементи - це функції, які дозволяють об'єкту щось зробити з цими елементами даних, називаються методами об'єкта.

+ +

Такі об'єкти називаються літералами об'єкта (object literal) - ми буквально вписали весь вміст об'єкта для його створення. Цей спосіб сильно відрізняється від об'єктів, реалізованих класами, які ми розглянемо пізніше.

+ +

Дуже часто створення об'єкта за допомогою літералу використовується, коли вам потрібно перенести  певним чином ряд структурованих, пов'язаних елементів даних, наприклад, надсилаючи запит на сервер для розміщення їх в базі даних. Відправка одного об'єкта набагато ефективніша, ніж відправлення кількох елементів окремо, а також з ним легше працювати, ніж з масивом, коли ви хочете ідентифікувати окремі елементи за назвою.

+ +

Крапкова нотація (Dot notation)

+ +

Вище ми отримали доступ до властивостей об'єкта та методів використовуючи крапкову нотацію (dot notation). Ім'я об'єкта (person) діє як простір імен (namespace) - його потрібно вводити першим для того, щоб ми могли отримати доступ до всього, що вкладено (encapsulated) всередині об'єкта.  Далі ви ставите крапку, після якої вказуєте елемент, який хочете отримати - це може бути іназва простої властивості,  елемент масиву або виклик одного з методів об'єкту, наприклад:

+ +
person.age
+person.interests[1]
+person.bio()
+ +

Sub-простори імен (Sub-namespaces)

+ +

Значенням елемента об'єкта можна зробити навіть інший об'єкт. Наприклад, спробуйте змінити значення властивості name з такого

+ +
name: ['Bob', 'Smith'],
+ +

на

+ +
name : {
+  first: 'Bob',
+  last: 'Smith'
+},
+ +

Тут ми ефективно створюємо sub-простір імен. Звучить складно, але насправді це не так - щоб отримати доступ до необхідних елементів, вам просто потрібно зробити ще один додатковий крок через крапку. Спробуйте це у консолі JS:

+ +
person.name.first
+person.name.last
+ +

Важливо: на цьому етапі вам також доведеться переглянути код вашого методу і змінити екземпляри з 

+ +
name[0]
+name[1]
+ +

на 

+ +
name.first
+name.last
+ +

Інакше ваші методи більше не працюватимуть.

+ +

Дужкова нотація (Bracket notation)

+ +

Існує ще один спосіб отримати доступ до властивостей об'єкту - використання дужкової нотації (bracket notation). Замість написання цього коду:

+ +
person.age
+person.name.first
+ +

Ви можете використовувати:

+ +
person['age']
+person['name']['first']
+ +

Це виглядає дуже схожим на те, як ви отримуєте доступ до елементів у масиві, і в принципі так воно і є - замість використання числових індексів для вибору елемента, ви асоціюєте ім'я для кожного значення. Не дивно, що ці об'єкти іноді називають асоціативними масивами - вони зіставляють рядки зі значеннями так само, як масиви зіставляють числові індекси зі значеннями.

+ +

Встановлення елементів об'єкта

+ +

Досі ми розглядали лише повернення (або отримання) елементів об'єктів - ви також можете встановити (оновити) значення елемента об'єкта, просто оголосивши елемент, який ви хочете встановити (використовуючи крапкову або дужкову нотацію), наприклад:

+ +
person.age = 45;
+person['name']['last'] = 'Cratchit';
+ +

Спробуйте ввести ці рядки, а потім знову поверніть елементи, щоб побачити, як вони змінилися:

+ +
person.age
+person['name']['last']
+ +

Ви можете не просто оновлювати і встановлювати значення властивостей і методів об'єкта, а так сам створювати абсолютно нові елементи. Наприклад:

+ +
person['eyes'] = 'hazel';
+person.farewell = function() { alert("Bye everybody!"); }
+ +

Тепер ви можете перевірити ваші нові елементи:

+ +
person['eyes']
+person.farewell()
+ +

Одним із корисних аспектів дужкової нотації є те, що вона може використовуватись не тільки для динамічного встановлення значень елементів, але й для їх імен. Припустимо, ми хочемо, щоб користувачі могли зберігати користувацькі типи даних, ввівши ім'я та значення елемента в два текстові поля? Ми могли б отримати такі значення:

+ +
var myDataName = nameInput.value;
+var myDataValue = nameValue.value;
+ +

Потім ми могли б додати новий елемент і його значення в об'єкт person таким чином:

+ +
person[myDataName] = myDataValue;
+ +

Щоб перевірити це, спробуйте додати наступні рядки до свого коду:

+ +
var myDataName = 'height';
+var myDataValue = '1.75m';
+person[myDataName] = myDataValue;
+ +

Тепер збережіть й оновіть, і введіть наступне:

+ +
person.height
+ +

Додавання властивості об'єкту з використанням наведеного вище методу неможливе з крапковою нотацією, яка може приймати лише літеральне ім'я елемента, а не значення змінної, що вказує на ім'я. 

+ +

Що таке "this"?

+ +

Ви могли помітити щось дивне в наших методах. Подивіться на це, наприклад:

+ +
greeting: function() {
+  alert('Hi! I\'m ' + this.name.first + '.');
+}
+ +

Ймовірно, вас цікавить, що таке "this"?  this - це ключове слово, яке посилається на поточний об'єкт, всередині якого написаний код - тому, в нашому випадку, this рівнозначний об'єкту person. Але чому б просто не написати person? Як ви побачите в статті  Об'єктно-орієнтований JavaScript для початківців, коли ми починаємо створювати конструктори, і т.д., this дуже корисний - він завжди буде гарантувати, що використовується правильне значення, коли контекст елемента змінюється (наприклад, два різні екземпляри об'єкта person можуть мати різні імена, але захочуть використовувати своє власне при вітанні). 

+ +

Давайте проілюструємо, що ми маємо на увазі з спрощеною парою об'єктів person:

+ +
var person1 = {
+  name: 'Chris',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+
+var person2 = {
+  name: 'Brian',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+ +

В цьому випадку, person1.greeting() виведе "Hi! I'm Chris."; person2.greeting() з іншого боку виведе "Hi! I'm Brian.", хоча код методу однаковий в обох випадках. Як ми вже говорили раніше, this рівнозначний об'єкту, всередині якого знаходиться код - це не дуже корисно, коли ви пишете літерали об'єктів вручну, але це дійсно допомагає, коли ви генеруєте об'єкти динамічно (наприклад, використовуючи конструктори). Пізніше це стане зрозумілішим.

+ +

Ви використовували об'єкти постійно

+ +

Поки ви проходили ці приклади, ймовірно, ви помітили, що крапкова нотація, яку ви використовували, виглядає дуже знайомо. Це тому, що ви використовували її протягом усього курсу! Кожного разу, коли ми працювали над прикладом, який використовував вбудований API-інтерфейс браузера або JavaScript об'єкт, ми використовували об'єкти, тому що такі функції побудовані з використанням тих же структур об'єктів, які ми тут розглядали, хоча і більш складні, ніж наші власні користувацькі приклади.

+ +

Тому, коли ви використовували рядкові методи, такі як:

+ +
myString.split(',');
+ +

Ви використовували метод, доступний в екземплярі класу String. Кожного разу, створюючи рядок у своєму коді, цей рядок автоматично створюється як екземпляр String, і тому має декілька загальних  методів/властивостей, доступних на ньому.

+ +

Коли ви звертались до об'єктної моделі документа (DOM), використовуючи такі рядки:

+ +
var myDiv = document.createElement('div');
+var myVideo = document.querySelector('video');
+ +

Ви використовували методи доступні в екземплярі класу Document. Для кожної завантаженої веб-сторінки створюється екземпляр Document, так званий document, який представляє структуру і зміст всієї сторінки, а також інші функції, такі як URL.

+ +

Те саме стосується і багатьох інших вбудованих об'єктів/API, які ви використовували — Array, Math, і т.д.

+ +

Зверніть увагу, що вбудовані об'єкти/API не завжди створюють екземпляри об'єктів автоматично. Наприклад, Notifications API, який дозволяє новим браузерам запускати системні повідомлення, вимагає, щоб ви створювали новий екземпляр об'єкта, за допомогою конструктора, для кожного повідомлення, яке ви хочете запустити. Спробуйте ввести наступне в консоль JavaScript:

+ +
var myNotification = new Notification('Hello!');
+ +

Ми розглянемо конструктори в наступній статті.

+ +
+

Заувага: Корисно подумати про те, як об'єкти взаємодіють шляхом передачі повідомлень - коли об'єкту потрібен інший об'єкт для виконання якої-небудь дії, він часто надсилає повідомлення іншому об'єкту, за допомогою одного з методів, і чекає відповіді, яку ми знаємо як повернене значення (return value).

+
+ +

Підсумок

+ +

Вітаємо, ви дійшли до завершення нашої першої статті про об'єкти в JS, тепер у вас має бути гарне уявлення про те, як працювати з об'єктами в JavaScript - в тому числі створювати свої власні прості об'єкти. Ви також повинні розуміти, що об'єкти дуже корисні в якості структур для зберігання пов'язаних даних і функціональності - якби ми намагались відстежувати всі властивості і методи в нашому об'єкті person як окремі змінні і функції, цу було б неефективно, і ми б ризикували зіткнутись з іншими змінними і функціями з такими ж іменами. Об'єкти дозволяють нам безпечно зберігати інформацію в своєму власному блоці, поза небезпекою.

+ +

У наступній статті ми почнемо розглядати теорію об'єктно-орієнтованого програмування (ООП), і як ці техніки можуть бути використані в JavaScript.

+ +

{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}

+ +

В цьому модулі

+ + diff --git a/files/uk/learn/javascript/objects/index.html b/files/uk/learn/javascript/objects/index.html new file mode 100644 index 0000000000..48bb0d98f1 --- /dev/null +++ b/files/uk/learn/javascript/objects/index.html @@ -0,0 +1,46 @@ +--- +title: Вступ до об'єктів JavaScript +slug: Learn/JavaScript/Objects +tags: + - JavaScript + - Об'єкти +translation_of: Learn/JavaScript/Objects +--- +
{{LearnSidebar}}
+ +

Чи не кожна річ у JavaScript є об'єктом — від самих основ, як-от рядки та масиви, до програмних інтерфейсів веб-переглядача. Ба більше, можна створювати власні об'єкти з передбаченою множиною властивостей та функцій для їх обробки. Для дальшого вивчення JavaScript важливим є розуміння об'єктно-орієнтованої природи цієї мови. Саме для того наводимо цю добірку статей. Тут ми докладно вивчатимемо теорію об'єктів та пов'язаний синтаксис, а відтак розглянемо створення власних об'єктів.

+ +

Необхідні знання

+ +

Перш ніж розпочати, вам слід принаймні ознайомитися з HTML та CSS. Радимо спершу приділити увагу розділам Вступ до HTML та Вступ до CSS, а вже тоді переходити до вивчення JavaScript.

+ +

Крім того, докладне вивчення об'єктів JavaScript потребує розуміння певних основ цієї мови. Тож варто спершу переглянути статті Перші кроки з JavaScript та Структурні елементи в JavaScript.

+ +
+

Заувага: Якщо ви працюєте за комп'ютером, планшетом тощо, де не маєте змоги створювати власні файли, можете випробувати приклади коду (більшість) в онлайн-редакторах для програмування, як-от JSFiddle, JSBin або Thimble.

+
+ +

Путівники

+ +
+
Основи об'єктів в JavaScript
+
В першій статті, що розглядає об'єкти JavaScript, ми ознайомимось з основами синтаксису об'єктів JavaScript та пересвідчимось, що велика частина функціоналу, з яким ми вже працювали, є насправді об'єктами.
+
Об'єктно-орієнтований JavaScript для початківців
+
Розібравшись з основами, ми зосередимось на об'єктно-орієнтованому JavaScript (OOJS) — у цій статті представлені основи теорії об'єктно-орієнтованого програмування (ООП), а далі дізнаємось, як за допомогою конструктора функцій JavaScript емулює класи об'єктів та як створювати екземпляри об'єктів.
+
Прототипи об'єктів
+
Прототипи — це механізм, завдяки якому об'єкти JavaScript наслідують функціонал один від одного, але при цьому вони працюють по-іншому, якщо порівнювати з механізмами наслідування в класичних об'єктно-орієнтованих мовах програмування. В цій статті ми дослідимо цю різницю, пояснимо як працюють прототипні ланцюги (prototype chains), і розглянемо як властивість прототипу може використовуватись для додавання методів до існуючих конструкторів.
+
Наслідування в JavaScript
+
Ознайомившись з значною частиною деталей OOJS, ця стаття покаже як створювати "дочірні" класи об'єктів (конструктори), які наслідують функціонал від своїх "батьківських" класів. Крім того, ми дамо декілька порад щод того, де і коли ви можете використовувати OOJS.
+
Робота з даними JSON
+
JavaScript Object Notation (JSON) — це стандартний текстовий формат для представлення структурованих даних на основі об'єктного синтаксису JavaScript, який зазвичай використовується для представлення та передачі даних на веб-сайтах (наприклад, відправлення деяких даних із сервера до клієнта, тому він може відображатись на веб-сторінці). Ви часто стикатиметесь з цим, тому в цій статті ми дамо вам все, що потрібно для роботи з JSON використовуючи JavaScript, включаючи синтаксичний аналіз (parsing) JSON, щоб ви могли отримувати доступ до елементів даних і писати свій власний JSON.
+
Практика побудови об'єктів
+
У попередніх статтях ми розглянули найголовніші моменти в теорії та деталях синтаксису об'єктів JavaScript, що дає вам тверду основу для початку. В цій статті ми перейдемо до практичних занять, отримаємо більше практичної роботи для побудови власних JavaScript об'єктів, щоб створити щось веселе та барвисте — декілька кольорових стрибучих кульок.
+
 
+
+ +

Завдання

+ +
+
Додавання функціоналу до демо зі стрибучими кульками
+
У цьому завданні, ми очікуємо, що ви, використовуючи демо з стрибаючими кульками з попередньої статті як відправну точку, додасте трохи нового та цікавого функціоналу до нього.
+
diff --git a/files/uk/learn/javascript/objects/object-oriented_js/index.html b/files/uk/learn/javascript/objects/object-oriented_js/index.html new file mode 100644 index 0000000000..67b61867ff --- /dev/null +++ b/files/uk/learn/javascript/objects/object-oriented_js/index.html @@ -0,0 +1,295 @@ +--- +title: Об'єктно-орієнтований JavaScript для початківців +slug: Learn/JavaScript/Objects/Object-oriented_JS +translation_of: Learn/JavaScript/Objects/Object-oriented_JS +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects")}}
+ +

Розібравшись з основами, зосередимось на об'єктно-орієнтованому JavaScript (OOJS) - в цій статті представлені основні позиції теорії об'єктно-орієнтованого програмування (ООП) , потім розглянемо, як в JavaScript емулювати класи об'єктів за допомогою функції конструктора, і як створити екземпляри об'єктів.

+ + + + + + + +
+ + + + + + + + + + + +
Необхідні знання:Елементарна комп'ютерна грамотність, базове розуміння HTML та CSS, знайомство з основами JavaScript (див. First steps та Building blocks) і основи OOJS (див. Основи об'єктів в JS).
Мета:Розуміння основ теоріі об'єктно-орієнтованого програмування, як це пов'язано з JavaScript ("більшість речей є об'єктами'), і як створювати конструктори та екземпляри об'єктів.
+
+ +

Об'єктно-орієнтоване програмування - основи

+ +

Давайте почнемо з спрощеного, високорівневого уявлення про об'єктно-орієнтоване програмування (ООП). Ми говоримо спрощеного, тому що ООП може швидко стати дуже складним, і якщо зараз дати повний курс, ймовірно, можна більше заплутати, ніж допомогти. Основна ідея ООП полягає в тому, що ми використовуємо об'єкти, щоб моделювати реальні речі, які ми хочемо представити всередині наших програм і/або забезпечити простий спосіб доступу до функціональних можливостей, які в іншому випадку було б важко або неможливо використати.

+ +

Об'єкти можуть містити пов'язані дані і код, які представляють інформацію про те, що ви намагаєтеся змоделювати, а також функціональні можливості або поведінку, які ви хочете мати. Дані об'єкта (і часто функції теж) можуть бути акуратно збережені (офіційне поняття інкапсульовані) всередині об'єктного пакету (якому можна дати певне ім'я для позначення, яке іноді називають простором імен),  що полегшує структуру і доступ; об'єкти також часто використовуються як сховища даних, які можна легко відправляти по мережі.

+ +

Визначення шаблону об'єкта

+ +

Давайте розглянемо просту програму, яка відображає інформацію про учнів та вчителів в школі. Тут ми розглянемо теорію ООП загалом, а не в контексті будь-якої конкретної мови програмування.

+ +

Щоб почати, повернемося до об'єкта person з нашої статті Основи об'єктів в JavaScript, який визначає загальні відомості і функціональні можливості людини. Є багато речей, які ви можете дізнатись про людину (її адресу, зріст, розмір взуття, профіль ДНК, номер паспорта, значні особистісні риси ...) , але в цьому випадку нас цікавлять лише ім'я, вік, стать та інтереси, і ми також хочемо написати коротку інформацію про неї на основі цих даних, і отримувати їх, щоб привітатись. Це відомо як абстракція (abstraction) - створення простої моделі більш складної речі, яка представляє її найважливіші аспекти таким чином, щоб було зручно працювати для виконання цілей нашої програми.

+ +

+ +

В деяких мовах ООП, це загальне визначення типу об'єкта називається класом (class) (JavaScript використовує інший механізм і термінологію, як ви побачите нижче) - це насправді не об'єкт, це швидше шаблон, який визначає, які характеристики повинен мати об'єкт.

+ +

Створення реальних об'єктів

+ +

З нашого класу ми можемо створити екземпляри об'єктів - об'єкти, що містять дані та функціональні можливості, визначені в класі. З нашого класу Person, можемо створити декілька справжніх людей:

+ +

+ +

Коли екземпляр об'єкта створюється з класу, функція конструктора класу виконується для його створення. Цей процес створення екземпляра об'єкта з класу називається instantiation - екземпляр об'єкта створюється з класу.

+ +

Specialist classes

+ +

In this case we don't want generic people — we want teachers and students, which are both more specific types of people. In OOP, we can create new classes based on other classes — these new child classes can be made to inherit the data and code features of their parent class, so you can reuse functionality common to all the object types rather than having to duplicate it.  Where functionality differs between classes, you can define specialized features directly on them as needed.

+ +

+ +

This is really useful — teachers and students share many common features such as name, gender, and age, so it is convenient to only have to define those features once. You can also define the same feature separately in different classes, as each definition of that feature will be in a different namespace. For example, a student's greeting might be of the form "Yo, I'm [firstName]" (e.g Yo, I'm Sam), whereas a teacher might use something more formal, such as "Hello, my name is [Prefix] [lastName], and I teach [Subject]." (e.g Hello, My name is Mr Griffiths, and I teach Chemistry).

+ +
+

Note: The fancy word for the ability of multiple object types to implement the same functionality is polymorphism. Just in case you were wondering.

+
+ +

You can now create object instances from your child classes. For example:

+ +

+ +

In the rest of the article, we'll start to look at how OOP theory can be put into practice in JavaScript.

+ +

Constructors and object instances

+ +

Some people argue that JavaScript is not a true object-oriented language — for example, its class statement is just syntactical sugar over existing prototypical inheritance and is not a class in a traditional sense. JavaScript, uses special functions called constructor functions to define objects and their features. They are useful because you'll often come across situations in which you don't know how many objects you will be creating; constructors provide the means to create as many objects as you need in an effective way, attaching data and functions to them as required.

+ +

When a new object instance is created from a constructor function, its core functionality (as defined by its prototype, which we'll explore in the article Object prototypes) is not all copied over to the new object like "classic" OO languages — instead the functionality is linked to via a reference chain called a prototype chain. So this is not true instantiation, strictly speaking — JavaScript uses a different mechanism to share functionality between objects.

+ +
+

Note: Not being "classic OOP" is not necessarily a bad thing; as mentioned above, OOP can get very complex very quickly, and JavaScript has some nice ways to take advantage of OO features without having to get too deep into it.

+
+ +

Let's explore creating classes via constructors and creating object instances from them in JavaScript. First of all, we'd like you to make a new local copy of the oojs.html file we saw in our first Objects article.

+ +

A simple example

+ +
    +
  1. Let's start by looking at how you could define a person with a normal function. Add this function within the script element: + +
    function createNewPerson(name) {
    +  var obj = {};
    +  obj.name = name;
    +  obj.greeting = function() {
    +    alert('Hi! I\'m ' + this.name + '.');
    +  };
    +  return obj;
    +}
    +
  2. +
  3. You can now create a new person by calling this function — try the following lines in your browser's JavaScript console: +
    var salva = createNewPerson('Salva');
    +salva.name;
    +salva.greeting();
    + This works well enough, but it is a bit long-winded; if we know we want to create an object, why do we need to explicitly create a new empty object and return it? Fortunately JavaScript provides us with a handy shortcut, in the form of constructor functions — let's make one now!
  4. +
  5. Replace your previous function with the following: +
    function Person(name) {
    +  this.name = name;
    +  this.greeting = function() {
    +    alert('Hi! I\'m ' + this.name + '.');
    +  };
    +}
    +
  6. +
+ +

The constructor function is JavaScript's version of a class. You'll notice that it has all the features you'd expect in a function, although it doesn't return anything or explicitly create an object — it basically just defines properties and methods. You'll see the this keyword being used here as well — it is basically saying that whenever one of these object instances is created, the object's name property will be equal to the name value passed to the constructor call, and the greeting() method will use the name value passed to the constructor call too.

+ +
+

Note: A constructor function name usually starts with a capital letter — this convention is used to make constructor functions easier to recognize in code.

+
+ +

So how do we call a constructor to create some objects?

+ +
    +
  1. Add the following lines below your previous code addition: +
    var person1 = new Person('Bob');
    +var person2 = new Person('Sarah');
    +
  2. +
  3. Save your code and reload it in the browser, and try entering the following lines into your JS console: +
    person1.name
    +person1.greeting()
    +person2.name
    +person2.greeting()
    +
  4. +
+ +

Cool! You'll now see that we have two new objects on the page, each of which is stored under a different namespace — when you access their properties and methods, you have to start calls with person1 or person2; they are neatly packaged away so they won't clash with other functionality. They do, however, have the same name property and greeting() method available. Note that they are using their own name value that was assigned to them when they were created; this is one reason why it is very important to use this, so they will use their own values, and not some other value.

+ +

Let's look at the constructor calls again:

+ +
var person1 = new Person('Bob');
+var person2 = new Person('Sarah');
+ +

In each case, the new keyword is used to tell the browser we want to create a new object instance, followed by the function name with its required parameters contained in parentheses, and the result is stored in a variable — very similar to how a standard function is called. Each instance is created according to this definition:

+ +
function Person(name) {
+  this.name = name;
+  this.greeting = function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  };
+}
+ +

After the new objects have been created, the person1 and person2 variables contain the following objects:

+ +
{
+  name: 'Bob',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+
+{
+  name: 'Sarah',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+ +

Note that when we are calling our constructor function, we are defining greeting() every time, which isn't ideal. To avoid this, we can define functions on the prototype instead, which we will look at later.

+ +

Creating our finished constructor

+ +

The example we looked at above was only a simple example to get us started. Let's now get on and create our final Person() constructor function.

+ +
    +
  1. Remove the code you inserted so far, and add in this replacement constructor — this is exactly the same as the simple example in principle, with just a bit more complexity: +
    function Person(first, last, age, gender, interests) {
    +  this.name = {
    +    'first': first,
    +    'last' : last
    +  };
    +  this.age = age;
    +  this.gender = gender;
    +  this.interests = interests;
    +  this.bio = function() {
    +    alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
    +  };
    +  this.greeting = function() {
    +    alert('Hi! I\'m ' + this.name.first + '.');
    +  };
    +}
    +
  2. +
  3. Now add in the following line below it, to create an object instance from it: +
    var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);
    +
  4. +
+ +

You'll now see that you can access the properties and methods just like we did previously — try these in your JS console:

+ +
person1['age']
+person1.interests[1]
+person1.bio()
+// etc.
+ +
+

Note: If you are having trouble getting this to work, try comparing your code against our version — see oojs-class-finished.html (also see it running live).

+
+ +

Further exercises

+ +

To start with, try adding a couple more object creation lines of your own, and try getting and setting the members of the resulting object instances.

+ +

In addition, there are a couple of problems with our bio() method — the output always includes the pronoun "He", even if your person is female, or some other preferred gender classification. And the bio will only include two interests, even if more are listed in the interests array. Can you work out how to fix this in the class definition (constructor)? You can put any code you like inside a constructor (you'll probably need a few conditionals and a loop). Think about how the sentences should be structured differently depending on gender, and depending on whether the number of listed interests is 1, 2, or more than 2.

+ +
+

Note: If you get stuck, we have provided an answer inside our GitHub repo (see it live) — try writing it yourself first though!

+
+ +

Other ways to create object instances

+ +

So far we've seen two different ways to create an object instance — declaring an object literal, and using a constructor function (see above).

+ +

These make sense, but there are other ways — we want to make you familiar with these in case you come across them in your travels around the Web.

+ +

The Object() constructor

+ +

First of all, you can use the Object() constructor to create a new object. Yes, even generic objects have a constructor, which generates an empty object.

+ +
    +
  1. Try entering this into your browser's JavaScript console: +
    var person1 = new Object();
    +
  2. +
  3. This stores an empty object in the person1 variable. You can then add properties and methods to this object using dot or bracket notation as desired; try these examples in your console: +
    person1.name = 'Chris';
    +person1['age'] = 38;
    +person1.greeting = function() {
    +  alert('Hi! I\'m ' + this.name + '.');
    +};
    +
  4. +
  5. You can also pass an object literal to the Object() constructor as a parameter, to prefill it with properties/methods. Try this in your JS console: +
    var person1 = new Object({
    +  name: 'Chris',
    +  age: 38,
    +  greeting: function() {
    +    alert('Hi! I\'m ' + this.name + '.');
    +  }
    +});
    +
  6. +
+ +

Using the create() method

+ +

Constructors can help you give your code order—you can create constructors in one place, then create instances as needed, and it is clear where they came from.

+ +

However, some people prefer to create object instances without first creating constructors, especially if they are creating only a few instances of an object. JavaScript has a built-in method called create() that allows you to do that. With it, you can create a new object based on any existing object.

+ +
    +
  1. With your finished exercise from the previous sections loaded in the browser, try this in your JavaScript console: +
    var person2 = Object.create(person1);
    +
  2. +
  3. Now try these: +
    person2.name
    +person2.greeting()
    +
  4. +
+ +

You'll see that person2 has been created based on person1—it has the same properties and method available to it.

+ +

One limitation of create() is that IE8 does not support it. So constructors may be more effective if you want to support older browsers.

+ +

We'll explore the effects of create() in more detail later on.

+ +

Summary

+ +

This article has provided a simplified view of object-oriented theory — this isn't the whole story, but it gives you an idea of what we are dealing with here. In addition, we have started to look at how JavaScript relates to and how it differs from "classic OOP", how to implement classes in JavaScript using constructor functions, and different ways of generating object instances.

+ +

In the next article, we'll explore JavaScript object prototypes.

+ +

{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git "a/files/uk/learn/javascript/\320\260\321\201\320\270\320\275\321\205\321\200\320\276\320\275\320\275\320\270\320\271/index.html" "b/files/uk/learn/javascript/\320\260\321\201\320\270\320\275\321\205\321\200\320\276\320\275\320\275\320\270\320\271/index.html" new file mode 100644 index 0000000000..3167a1f55a --- /dev/null +++ "b/files/uk/learn/javascript/\320\260\321\201\320\270\320\275\321\205\321\200\320\276\320\275\320\275\320\270\320\271/index.html" @@ -0,0 +1,51 @@ +--- +title: Асинхронний JavaScript +slug: Learn/JavaScript/Асинхронний +translation_of: Learn/JavaScript/Asynchronous +--- +
{{LearnSidebar}}
+ +

In this module we take a look at {{Glossary("asynchronous")}} {{Glossary("JavaScript")}}, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.

+ +
+

Looking to become a front-end web developer?

+ +

We have put together a course that includes all the essential information you need to work towards your goal.

+ +

Get started

+
+ +

Prerequisites

+ +

Asynchronous JavaScript is a fairly advanced topic, and you are advised to work through JavaScript first steps and JavaScript building blocks modules before attempting this.

+ +

If you are not familiar with the concept of asynchronous programming, you should definitely start with the General asynchronous programming concepts article in this module. If you are, then you can probably skip to the Introducing asynchronous JavaScript module.

+ +
+

Note: If you are working on a computer/tablet/other device 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

+ +
+
General asynchronous programming concepts
+
+

In this article we'll run through a number of important concepts relating to asynchronous programming, and how this looks in web browsers and JavaScript. You should understand these concepts before working through the other articles in the module.

+
+
Introducing asynchronous JavaScript
+
In this article we briefly recap the problems associated with sychronous JavaScript, and take a first look at some of the different asynchronous JavaScript techniques you'll encounter, showing how they can help us solve such problems.
+
Cooperative asynchronous JavaScript: Timeouts and intervals
+
Here we look at the traditional methods JavaScript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), talk about what they are useful for, and look at their inherent issues.
+
Handling async operations gracefully with Promises
+
Promises are a comparatively new feature of the JavaScript language that allow you to defer further actions until after the previous action has completed, or respond to its failure. This is really useful for setting up a sequence of operations to work correctly. This article shows you how promises work, where you'll see them in use in WebAPIs, and how to write your own.
+
Making asynchronous programming easier with async and await
+
Promises can be somewhat complex to set up and understand, and so modern browsers have implemented async functions and the await operator. The former allows standard functions to implicitly behave asynchronously with promises, whereas the latter can be used inside async functions to wait for promises before the function continues. This makes chaining promises simpler and easier to read.
+
Choosing the right approach
+
To finish this module off, we'll consider the different coding techniques and features we've discussed throughout, looking at which ones you should use when, with recommendations and reminders of common pitfalls where appropriate.
+
+ +

See also

+ + diff --git "a/files/uk/learn/javascript/\320\261\321\203\320\264\321\226\320\262\320\265\320\273\321\214\320\275\321\226_\320\261\320\273\320\276\320\272\320\270/index.html" "b/files/uk/learn/javascript/\320\261\321\203\320\264\321\226\320\262\320\265\320\273\321\214\320\275\321\226_\320\261\320\273\320\276\320\272\320\270/index.html" new file mode 100644 index 0000000000..d4a6238d0f --- /dev/null +++ "b/files/uk/learn/javascript/\320\261\321\203\320\264\321\226\320\262\320\265\320\273\321\214\320\275\321\226_\320\261\320\273\320\276\320\272\320\270/index.html" @@ -0,0 +1,57 @@ +--- +title: Будівельні блоки JavaScript +slug: Learn/JavaScript/Будівельні_блоки +translation_of: Learn/JavaScript/Building_blocks +--- +
{{LearnSidebar}}
+ +

In this module, we continue our coverage of all JavaScript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events. You've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly.

+ +
+

Looking to become a front-end web developer?

+ +

We have put together a course that includes all the essential information you need to work towards your goal.

+ +

Get started

+
+ +

Prerequisites

+ +

Before starting this module, you should have some familiarity with the basics of HTML and CSS, and you should have also worked through our previous module, JavaScript first steps.

+ +
+

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

+
+ +

Guides

+ +
+
Making decisions in your code — conditionals
+
In any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. In this article we'll explore how conditional structures work in JavaScript.
+
Looping code
+
Sometimes you need a task done more than once in a row. For example, looking through a list of names. In programming, loops perform this job very well. Here we will look at loop structures in JavaScript.
+
Functions — reusable blocks of code
+
Another essential concept in coding is functions. Functions allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times. In this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define functions, scope, and parameters.
+
Build your own function
+
With most of the essential theory dealt with previously, this article provides a practical experience. Here you'll get some practice with building up your own custom function. Along the way, we'll also explain some further useful details of dealing with functions.
+
Function return values
+
The last essential concept you must know about a function is return values. Some functions don't return a significant value after completion, but others do. It's important to understand what their values are, how to make use of them in your code, and how to make your own custom functions return useful values. 
+
Introduction to events
+
Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. For example if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box. In this final article we will discuss some important concepts surrounding events, and look at how they work in browsers.
+
+ +

Assessments

+ +

The following assessment will test your understanding of the JavaScript basics covered in the guides above.

+ +
+
Image gallery
+
Now that we've looked at the fundamental building blocks of JavaScript, we'll test your knowledge of loops, functions, conditionals and events by building a fairly common item you'll see on a lot of websites — a JavaScript-powered image gallery.
+
+ +

See also

+ +
+
Learn JavaScript
+
An excellent resource for aspiring web developers — Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the complete course is available for a small one-time payment.
+
diff --git a/files/uk/learn/server-side/django/index.html b/files/uk/learn/server-side/django/index.html new file mode 100644 index 0000000000..c26c8fbe6b --- /dev/null +++ b/files/uk/learn/server-side/django/index.html @@ -0,0 +1,60 @@ +--- +title: Django веб-фреймворк (Python) +slug: Learn/Server-side/Django +translation_of: Learn/Server-side/Django +--- +
{{LearnSidebar}}
+ +

Django є надзвичайно популярним і повнофункціональним серверним веб-фреймворком, що написаний на Python. Даний модуль показує вам, чому Django є одним з найпопулярніших структур веб-сервера, а також як налаштувати середовище розробки, і як приступити до роботи щоб створювати власні веб-додатки.

+ +

Передумови

+ +

Перед початком цього модуля вам не потрібно володіти будь-якими знаннями про Django. Ви повинні лише розуміти, що таке серверне веб-програмування та веб-фреймворк, для цього читайте тему в нашому модулі - Програмування веб-сайту на стороні сервера, перші кроки.

+ +

Вітається володіння загальними знаннями концепцій програмування і мови програмування Python, проте не є необхідним для розуміння основних понять.

+ +
+

Примітка: Python є однією із найпростіших мов програмування, легкою для освоєння та розуміння початківцями. Якщо ж ви прагнете зрозуміти цей модуль краще, то для цього є безліч безкоштовних книг і посібників, які є в інтернеті у вільному доступі (початківці у програмуванні можуть переглянути сторінку на wiki.python.org - Python для початківців).

+
+ +

Посібники

+ +
+
Вступ до Django
+
У цій першій статті про Django ми відповімо на питання "Що таке Django?" і дамо уявлення того що робить веб-фраймворк особливого.  We'll outline the main features, including some of the advanced functionality that we won't have time to cover in detail in this module. We'll also show you some of the main building blocks of a Django application, to give you an idea of what it can do before you then go on to set it up and start playing.
+
Налаштування середовища розробки Django
+
Now that you know what Django is for, we'll show you how to setup and test a Django development environment on Windows, Linux (Ubuntu), and Mac OS X — whatever common operating system you are using, this article should give you what you need to be able to start developing Django apps.
+
Посібник Django: "Локальна бібліотека" - приклад веб-сайту
+
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.
+
Посібник Django, частина 2: Створення скелету веб-сайту
+
This article shows how you can create a "skeleton" website project as a basis, which you can then go on to populate with site-specific settings, urls, models, views, and templates.
+
Посібник Django, частина 3: Використання моделей
+
This article shows how to define models for the LocalLibrary website — models represent the data structures we want to store our app's data in, and also allow Django to store data in a database for us (and modify it later on). It explains what a model is, how it is declared, and some of the main field types. It also briefly shows a few of the main ways you can access model data.
+
Посібник Django, частина 4: Адміністрування сайту
+
Now that we've created models for the LocalLibrary website, we'll use the Django Admin site to add some "real" book data. First we'll show you how to register the models with the admin site, then we'll show you how to login and create some data. At the end we show some of ways you can further improve the presentation of the admin site.
+
Посібник Django, частина 5: Створення домашньої сторінки
+
We're now ready to add the code to display our first full page — a home page for the LocalLibrary that shows how many records we have of each model type and provides sidebar navigation links to our other pages. Along the way we'll gain practical experience in writing basic URL maps and views, getting records from the database, and using templates.
+
Посібник Django Tutorial Part 6: Загальний список і детальний перегляд
+
This tutorial extends our LocalLibrary website, adding list and detail pages for books and authors. Here we'll learn about generic class-based views, and show how they can reduce the amount of code you have to write for common use cases. We'll also go into URL handling in greater detail, showing how to perform basic pattern matching.
+
Посібник Django, частина 7: Фреймворк сесій
+
This tutorial extends our LocalLibrary website, adding a session-based visit-counter to the home page. This is a relatively simple example, but it does shows how you can use the session framework to provide peristent behaviour for anonymous users in your own sites.
+
Посібник Django, частина 8: Аутентифікація користувачів і права доступу
+
In this tutorial we'll show you how to allow users to login to your site with their own accounts, and how to control what they can do and see based on whether or not they are logged in and their permissions. As part of this demonstration we'll extend the LocalLibrary website, adding login and logout pages, and user- and staff-specific pages for viewing books that have been borrowed.
+
Посібник Django, частина 9: Робота з формами
+
In this tutorial we'll show you how to work with HTML Forms in Django, and in particular the easiest way to write forms to create, update, and delete model instances. As part of this demonstration we'll extend the LocalLibrary website so that librarians can renew books, and create, update, and delete authors using our own forms (rather than using the admin application).
+
Посібник Django, частина 10: Тестування веб-додатку Django
+
As websites grow they become harder to test manually — not only is there more to test, but, as the interactions between components become more complex, a small change in one area can require many additional tests to verify its impact on other areas. One way to mitigate these problems is to write automated tests, which can easily and reliably be run every time you make a change. This tutorial shows how to automate unit testing of your website using Django's test framework.
+
Посібник Django, частина 11: Розгортання веб-додатку Django на веб-сервері
+
Now you've created (and tested) an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
+
Django безпека веб-додатків
+
Protecting user data is an essential part of any website design. We previously explained some of the more common security threats in the article Web security — this article provides a practical demonstration of how Django's in-built protections handle such threats.
+
+ +

Оцінювання

+ +

The following assessment will test your understanding of how to create a website using Django, as described in the guides listed above.

+ +
+
DIY Django міні блог
+
In this assessment you'll use some of the knowledge you've learned from this module to create your own blog.
+
diff --git a/files/uk/learn/server-side/django/introduction/index.html b/files/uk/learn/server-side/django/introduction/index.html new file mode 100644 index 0000000000..26ef60a53a --- /dev/null +++ b/files/uk/learn/server-side/django/introduction/index.html @@ -0,0 +1,285 @@ +--- +title: Введення в Django +slug: Learn/Server-side/Django/Introduction +tags: + - CodingScripting + - Intro + - Learn + - Python + - Server-side programming + - django + - Джанго + - Кодування + - Програмування + - Пітон + - уроки +translation_of: Learn/Server-side/Django/Introduction +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}}
+ +

У цій першій статті Django, ми відповімо на питання "Що таке Django?" і даємо вам обзор того, що робить цей веб-фреймворк особливим. Ми розглянемо основні характеристики, включаючи деякі додаткові функціональні можливості модуля, які ми не встигли ще обговорити. Ми також покажемо вам деякі з основних блоків програми Django (хоча на даний момент у вас ще немає середовища розробки, в якій можна було б її протестувати).

+ + + + + + + + + + + + +
Передумови::Basic computer literacy. A general understanding of server-side website programming, and in particular the mechanics of client-server interactions in websites.
Завдання:To gain familiarity with what Django is, what functionality it provides, and the main building blocks of a Django application.
+ +

Що таке Django?

+ +

Django - це високорівневий веб-фреймворк Python, що дозволяє швидко розвивати безпечні та підтримувані сайти. Побудований досвідченими розробниками, Django піклується про більшу частину турбот про веб-розробку, тому ви можете зосередитися на написанні програми без необхідності винаходити колесо.Це вільний і відкритий код, має процвітаюче і активне співтовариство, велику документацію, і безліч варіантів для безкоштовної і платної підтримки.

+ +

Django допоможе вам написати програмне забезпечення, яке:

+ +
+
Complete
+
Django слідує філософії "Батарейки включені" і забезпечує майже все, що розробники можуть захотіти зробити "з коробки". Оскільки все, що вам потрібно, є частиною одного "продукту", все працює безперешкодно, слідує послідовним принципам дизайну і має велику й найновішу документацію.
+
Універсальний
+
Django використовується для створення майже будь-якого типу веб-сайту — fвід систем управління контентом та вікі, через соціальні мережі та сайти новин. Він може працювати з будь-якою стороною клієнта, і може надавати вміст практично в будь-якому форматі (у тому числі HTML, RSS feeds, JSON, XML, etc). Сайт, який ви зараз читаєте, заснований на Django!                                                                                                
+ Internally, while it provides choices for almost any functionality you might want (e.g. several popular databases, templating engines, etc.), it can also be extended to use other components if needed.
+
Безпечний
+
Django helps developers avoid many common security mistakes by providing a framework that has been engineered to "do the right things" to protect the website automatically. For example, Django provides a secure way to manage user accounts and passwords, avoiding common mistakes like putting session information in cookies where it is vulnerable (instead cookies just contain a key, and the actual data is stored in the database) or directly storing passwords rather than a password hash.
+
+ A password hash is a fixed-length value created by sending the password through a cryptographic hash function. Django can check if an entered password is correct by running it through the hash function and comparing the output to the stored hash value. However due to the "one-way" nature of the function, even if a stored hash value is compromised it is hard for an attacker to work out the original password.
+
+ Django enables protection against many vulnerabilities by default, including SQL injection, cross-site scripting, cross-site request forgery and clickjacking (see Website security for more details of such attacks).
+
Масштабованість
+
Django uses a component-based “shared-nothing” architecture (each part of the architecture is independent of the others, and can hence be replaced or changed if needed). Having a clear separation between the different parts means that it can scale for increased traffic by adding hardware at any level: caching servers, database servers, or application servers. Some of the busiest sites have successfully scaled Django to meet their demands (e.g. Instagram and Disqus, to name just two).
+
Підтримується
+
Django code is written using design principles and patterns that encourage the creation of maintainable and reusable code. In particular, it makes use of the Don't Repeat Yourself (DRY) principle so there is no unnecessary duplication, reducing the amount of code. Django also promotes the grouping of related functionality into reusable "applications" and, at a lower level, groups related code into modules (along the lines of the Model View Controller (MVC) pattern).
+
Портативний
+
Django is written in Python, which runs on many platforms. That means that you are not tied to any particular server platform, and can run your applications on many flavours of Linux, Windows, and Mac OS X. Furthermore, Django is well-supported by many web hosting providers, who often provide specific infrastructure and documentation for hosting Django sites.
+
+ +

Звідки він?

+ +

Django was initially developed between 2003 and 2005 by a web team who were responsible for creating and maintaining newspaper websites. After creating a number of sites, the team began to factor out and reuse lots of common code and design patterns. This common code evolved into a generic web development framework, which was open-sourced as the "Django" project in July 2005. 

+ +

Django has continued to grow and improve, from its first milestone release (1.0) in September 2008 through to the recently-released version 2.0 (2017). Each release has added new functionality and bug fixes, ranging from support for new types of databases, template engines, and caching, through to the addition of "generic" view functions and classes (which reduce the amount of code that developers have to write for a number of programming tasks). 

+ +
+

Note: Check out the release notes on the Django website to see what has changed in recent versions, and how much work is going into making Django better.

+
+ +

Django is now a thriving, collaborative open source project, with many thousands of users and contributors. While it does still have some features that reflect its origin, Django has evolved into a versatile framework that is capable of developing any type of website. 

+ +

Наскільки популярним є Django?

+ +

There isn't any readily-available and definitive measurement of popularity of server-side frameworks (although sites like Hot Frameworks attempt to assess popularity using mechanisms like counting the number of GitHub projects and StackOverflow questions for each platform). A better question is whether Django is "popular enough" to avoid the problems of unpopular platforms. Is it continuing to evolve? Can you get help if you need it? Is there an opportunity for you to get paid work if you learn Django? 

+ +

Based on the number of high profile sites that use Django, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, Django is a popular framework!

+ +

High-profile sites that use Django include: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic, Open Knowledge Foundation, Pinterest, and Open Stack (source: Django home page).

+ +

Is Django opinionated?

+ +

Web frameworks often refer to themselves as "opinionated" or "unopinionated".

+ +

Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They often support rapid development in a particular domain (solving problems of a particular type) because the right way to do anything is usually well-understood and well-documented. However they can be less flexible at solving problems outside their main domain, and tend to offer fewer choices for what components and approaches they can use.

+ +

Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components together to achieve a goal, or even what components should be used. They make it easier for developers to use the most suitable tools to complete a particular task, albeit at the cost that you need to find those components yourself.
+
+ Django is "somewhat opinionated", and hence delivers the "best of both worlds". It provides a set of components to handle most web development tasks and one (or two) preferred ways to use them. However, Django's decoupled architecture means that you can usually pick and choose from a number of different options, or add support for completely new ones if desired.

+ +

Як виглядає код Django?

+ +

In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what is needed based on the URL and possibly information in POST data or GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.

+ +

Django web applications typically group the code that handles each of these steps into separate files:

+ +

+ + + +
+

Note: Django refers to this organisation as the "Model View Template (MVT)" architecture. It has many similarities to the more familiar Model View Controller architecture. 

+
+ + + +

The sections below will give you an idea of what these main parts of a Django app look like (we'll go into more detail later on in the course, once we've set up a development environment).

+ +

Sending the request to the right view (urls.py)

+ +

A URL mapper is typically stored in a file named urls.py. In the example below, the mapper  (urlpatterns) defines a list of mappings between routes (specific URL patterns) and corresponding view functions. If an HTTP Request is received that has a URL matching a specified pattern then the associated view function will be called and passed the request.

+ +
urlpatterns = [
+    path('admin/', admin.site.urls),
+    path('book/<int:id>/', views.book_detail, name='book_detail'),
+    path('catalog/', include('catalog.urls')),
+    re_path(r'^([0-9]+)/$', views.best),
+]
+
+ +

The urlpatterns object is a list of path() and/or re_path() functions (Python lists are defined using square brackets, where items are separated by commas and may have an optional trailing comma. For example: [item1, item2, item3,]).

+ +

The first argument to both methods is a route (pattern) that will be matched. The path() method uses angle brackets to define parts of a URL that will be captured and passed through to the view function as named arguments. The re_path() function uses a flexible pattern matching approach known as a regular expression. We'll talk about these in a later article!

+ +

The second argument is another function that will be called when the pattern is matched. The notation views.book_detail indicates that the function is called book_detail() and can be found in a module called views (i.e. inside a file named views.py)

+ +

Handling the request (views.py)

+ +

Views are the heart of the web application, receiving HTTP requests from web clients and returning HTTP responses. In between, they marshall the other resources of the framework to access databases, render templates, etc. 

+ +

The example below shows a minimal view function index(), which could have been called by our URL mapper in the previous section.  Like all view functions it receives an HttpRequest object as a parameter (request) and returns an HttpResponse object. In this case we don't do anything with the request, and our response simply returns a hard-coded string. We'll show you a request that does something more interesting in a later section.

+ +
# filename: views.py (Django view functions)
+
+from django.http import HttpResponse
+
+def index(request):
+    # Get an HttpRequest - the request parameter
+    # perform operations using information from the request.
+    # Return HttpResponse
+    return HttpResponse('Hello from Django!')
+
+ +
+

Note: A little bit of Python:

+ + +
+ + + +

Views are usually stored in a file called views.py.

+ +

Defining data models (models.py)

+ +

Django web applications manage and query data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc. The definition of the model is independent of the underlying database — you can choose one of several as part of your project settings. Once you've chosen what database you want to use, you don't need to talk to it directly at all — you just write your model structure and other code, and Django handles all the dirty work of communicating with the database for you.

+ +

The code snippet below shows a very simple Django model for a Team object. The Team class is derived from the django class models.Model. It defines the team name and team level as character fields and specifies a maximum number of characters to be stored for each record. The team_level can be one of several values, so we define it as a choice field and provide a mapping between choices to be displayed and data to be stored, along with a default value. 

+ +
# filename: models.py
+
+from django.db import models
+
+class Team(models.Model):
+    team_name = models.CharField(max_length=40)
+
+    TEAM_LEVELS = (
+        ('U09', 'Under 09s'),
+        ('U10', 'Under 10s'),
+        ('U11', 'Under 11s'),
+        ...  #list other team levels
+    )
+    team_level = models.CharField(max_length=3, choices=TEAM_LEVELS, default='U11')
+
+ +
+

Note: A little bit of Python:

+ + +
+ +

Querying data (views.py)

+ +

The Django model provides a simple query API for searching the database. This can match against a number of fields at a time using different criteria (e.g. exact, case-insensitive, greater than, etc.), and can support complex statements (for example, you can specify a search on U11 teams that have a team name that starts with "Fr" or ends with "al"). 

+ +

The code snippet shows a view function (resource handler) for displaying all of our U09 teams. The line in bold shows how we can use the model query API to filter for all records where the team_level field has exactly the text 'U09' (note how this criteria is passed to the filter() function as an argument with the field name and match type separated by a double underscore: team_level__exact).

+ +
## filename: views.py
+
+from django.shortcuts import render
+from .models import Team
+
+def index(request):
+    list_teams = Team.objects.filter(team_level__exact="U09")
+    context = {'youngest_teams': list_teams}
+    return render(request, '/best/index.html', context)
+
+ +
+
+ +

This function uses the render() function to create the HttpResponse that is sent back to the browser. This function is a shortcut; it creates an HTML file by combining a specified HTML template and some data to insert in the template (provided in the variable named "context"). In the next section we show how the template has the data inserted in it to create the HTML.

+ +

Rendering data (HTML templates)

+ +

Template systems allow you to specify the structure of an output document, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of document. Django supports both its native templating system and another popular Python library called Jinja2 out of the box (it can also be made to support other systems if needed). 

+ +

The code snippet shows what the HTML template called by the render() function in the previous section might look like. This template has been written under the assumption that it will have access to a list variable called youngest_teams when it is rendered (contained in the context variable inside the render() function above). Inside the HTML skeleton we have an expression that first checks if the youngest_teams variable exists, and then iterates it in a for loop. On each iteration the template displays each team's team_name value in an {{htmlelement("li")}} element.

+ +
## filename: best/templates/best/index.html
+
+<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="utf-8">
+  <title>Home page</title>
+</head>
+<body>
+  {% if youngest_teams %}
+    <ul>
+      {% for team in youngest_teams %}
+        <li>\{\{ team.team_name \}\}</li>
+      {% endfor %}
+    </ul>
+  {% else %}
+    <p>No teams are available.</p>
+  {% endif %}
+</body>
+</html>
+ +

What else can you do?

+ +

The preceding sections show the main features that you'll use in almost every web application: URL mapping, views, models and templates. Just a few of the other things provided by Django include:

+ + + +

Summary

+ +

Congratulations, you've completed the first step in your Django journey! You should now understand Django's main benefits, a little about its history, and roughly what each of the main parts of a Django app might look like. You should have also learned a few things about the Python programming language, including the syntax for lists, functions, and classes.

+ +

You've already seen some real Django code above, but unlike with client-side code, you need to set up a development environment to run it. That's our next step.

+ +
{{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}}
+ +

У цьому модулі

+ + diff --git a/files/uk/learn/server-side/express_nodejs/index.html b/files/uk/learn/server-side/express_nodejs/index.html new file mode 100644 index 0000000000..968f3e40e2 --- /dev/null +++ b/files/uk/learn/server-side/express_nodejs/index.html @@ -0,0 +1,77 @@ +--- +title: Express web framework (Node.js/JavaScript) +slug: Learn/Server-side/Express_Nodejs +tags: + - Beginner + - CodingScripting + - Express + - Express.js + - Intro + - JavaScript + - Learn + - NeedsTranslation + - Node + - Server-side programming + - TopicStub + - node.js +translation_of: Learn/Server-side/Express_Nodejs +--- +
{{LearnSidebar}}
+ +

Express is a popular unopinionated 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.

+ +

Prerequisites

+ +

Before starting this module you will need to understand what server-side web programming and web frameworks are, ideally by reading the topics in our Server-side website programming first steps module. A general knowledge of programming concepts and JavaScript is highly recommended, but not essential to understanding the core concepts.

+ +
+

Note: This website has many useful resources for learning JavaScript in the context of client-side development: JavaScriptJavaScript Guide, JavaScript BasicsJavaScript (learning). The core JavaScript language and concepts are the same for server-side development on Node.js and this material will be relevant. Node.js offers additional APIs for supporting functionality that is useful in browserless environments, e.g. to create HTTP servers and access the file system, but does not support JavaScript APIs for working with the browser and DOM.

+ +

This guide will provide some information about working with Node.js and Express, and there are numerous other excellent resources on the Internet and in books — some of these linked from How do I get started with Node.js (StackOverflow) and What are the best resources for learning Node.js? (Quora).

+
+ +

Guides

+ +
+
Express/Node introduction
+
In this first Express article we answer the questions "What is Node?" and "What is Express?" and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).
+
Setting up a Node (Express) development environment
+
Now that you know what Express is for, we'll show you how to set up and test a Node/Express development environment on Windows, Linux (Ubuntu), and Mac OS X. Whatever common operating system you are using, this article should give you what you need to be able to start developing Express apps.
+
Express Tutorial: The Local Library website
+
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.
+
Express Tutorial Part 2: Creating a skeleton website
+
This article shows how you can create a "skeleton" website project, which you can then go on to populate with site-specific routes, templates/views, and databases.
+
Express Tutorial Part 3: Using a Database (with Mongoose)
+
This article briefly introduces databases for Node/Express. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways you can access model data.
+
Express Tutorial Part 4: Routes and controllers
+
In this tutorial we'll set up routes (URL handling code) with "dummy" handler functions for all the resource endpoints that we'll eventually need in the LocalLibrary website. On completion, we'll have a modular structure for our route handling code, that we can extend with real handler functions in the following articles. We'll also have a really good understanding of how to create modular routes using Express.
+
Express Tutorial Part 5: Displaying library data
+
We're now ready to add the pages that display the LocalLibrary website books and other data. The pages will include a home page that shows how many records we have of each model type, and list and detail pages for all of our models. Along the way we'll gain practical experience in getting records from the database, and using templates.
+
Express Tutorial Part 6: Working with forms
+
In this tutorial we'll show you how to work with HTML Forms in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.
+
Express Tutorial Part 7: Deploying to production
+
Now you've created an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
+
+ +

See also

+ +
+
Installing LocalLibrary on PWS/Cloud Foundry
+
This article provides a practical demonstration of how to install LocalLibrary on the Pivotal Web Services PaaS cloud — this is a full-featured, open source alternative to Heroku, the PaaS cloud service used in Part 7 of the tutorial, listed above. PWS/Cloud Foundry is definitely worth checking out if you are looking for an alternative to Heroku (or another PaaS cloud service), or simply feel like trying something different.
+
+ +

Adding more tutorials

+ +
+

That's the end of the tutorial articles (for now). If you would like to extend it, other interesting topics to cover are:

+ + + +

And of course it would be excellent to have an assessment task!

+
diff --git a/files/uk/learn/server-side/express_nodejs/routes/index.html b/files/uk/learn/server-side/express_nodejs/routes/index.html new file mode 100644 index 0000000000..9f9e704565 --- /dev/null +++ b/files/uk/learn/server-side/express_nodejs/routes/index.html @@ -0,0 +1,644 @@ +--- +title: 'Express Tutorial Part 4: Routes and controllers' +slug: Learn/Server-side/Express_Nodejs/routes +translation_of: Learn/Server-side/Express_Nodejs/routes +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs")}}
+ +

У цій статті ми настроїмо (URL handling code) з "штучною" функцією обробки всіх можливих шляхів (endpoints) які потрібні у LocalLibrary сайті. У підсумку ми матимемо модульну структуру відладки для всіх шляхів, яку ми зможемо використати у наступній статті.  Ми матимемо хороше розуміння, як створювати модульну структуру для шляхів які використовує Express!

+ + + + + + + + + + + + +
Передумови:Прочитайте Express/Node introduction. Закінчіть попередні частини (включаючи Express Tutorial Part 3: Using a Database (with Mongoose)).
Мета:Вміти створити простий шляхи. Настроїти обробку всі URL шляхів.
+ +

Overview

+ +

In the last tutorial article we defined Mongoose models to interact with the database, and used a (standalone) script to create some initial library records. We can now write the code to present that information to users. The first thing we need to do is determine what information we want to be able to display in our pages, and then define appropriate URLs for returning those resources. Then we're going to need to create the routes (URL handlers) and views (templates) to display those pages.

+ +

The diagram below is provided as a reminder of the main flow of data and things that need to be implemented when handling an HTTP request/response. In addition to the views and routes the diagram shows "controllers" — functions that separate out the code to route requests from the code that actually processes requests.

+ +

As we've already created the models, the main things we'll need to create are:

+ + + +

+ +

Ultimately we might have pages to show lists and detail information for books, genres, authors and bookinstances, along with pages to create, update, and delete records. That's a lot to document in one article. Therefore most of this article will concentrate on setting up our routes and controllers to return "dummy" content. We'll extend the controller methods in our subsequent articles to work with model data.

+ +

The first section below provides a brief "primer" on how to use the Express Router middleware. We'll then use that knowledge in the following sections when we set up the LocalLibrary routes.

+ +

Routes primer

+ +

A route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), an URL path/pattern, and a function that is called to handle that pattern.

+ +

There are several ways to create routes. For this tutorial we're going to use the express.Router middleware as it allows us to group the route handlers for a particular part of a site together and access them using a common route-prefix. We'll keep all our library-related routes in a "catalog" module, and, if we add routes for handling user accounts or other functions, we can keep them grouped separately.

+ +
+

Note: We discussed Express application routes briefly in our Express Introduction > Creating route handlers. Other than providing better support for modularization (as discussed in the first subsection below), using Router is very similar to defining routes directly on the Express application object.

+
+ +

The rest of this section provides an overview of how the Router can be used to define the routes.

+ +

Defining and using separate route modules

+ +

The code below provides a concrete example of how we can create a route module and then use it in an Express application.

+ +

First we create routes for a wiki in a module named wiki.js. The code first imports the Express application object, uses it to get a Router object and then adds a couple of routes to it using the get() method. Last of all the module exports the Router object.

+ +
// wiki.js - Wiki route module.
+
+var express = require('express');
+var router = express.Router();
+
+// Home page route.
+router.get('/', function (req, res) {
+  res.send('Wiki home page');
+})
+
+// About page route.
+router.get('/about', function (req, res) {
+  res.send('About this wiki');
+})
+
+module.exports = router;
+
+
+ +
+

Note: Above we are defining our route handler callbacks directly in the router functions. In the LocalLibrary we'll define these callbacks in a separate controller module.

+
+ +

To use the router module in our main app file we first require() the route module (wiki.js). We then call use() on the Express application to add the Router to the middleware handling path, specifying an URL path of 'wiki'.

+ +
var wiki = require('./wiki.js');
+// ...
+app.use('/wiki', wiki);
+ +

The two routes defined in our wiki route module are then accessible from /wiki/ and /wiki/about/.

+ +

Route functions

+ +

Our module above defines a couple of typical route functions. The "about" route (reproduced below) is defined using the Router.get() method, which responds only to HTTP GET requests. The first argument to this method is the URL path while the second is a callback function that will be invoked if an HTTP GET request with the path is received.

+ +
router.get('/about', function (req, res) {
+  res.send('About this wiki');
+})
+
+ +

The callback takes three arguments (usually named as shown: req, res, next), that will contain the HTTP Request object, HTTP response, and the next function in the middleware chain.

+ +
+

Note: Router functions are Express middleware, which means that they must either complete (respond to) the request or call the next function in the chain. In the case above we complete the request using send(), so the next argument is not used (and we choose not to specify it).

+ +

The  router function above takes a single callback, but you can specify as many callback arguments as you want, or an array of callback functions. Each function is part of the middleware chain, and will be called in the order it is added to the chain (unless a preceding function completes the request).

+
+ +

The callback function here calls send() on the response to return the string "About this wiki" when we receive a GET request with the path ('/about'). There are a number of other response methods for ending the request/response cycle. For example, you could call res.json() to send a JSON response or res.sendFile() to send a file. The response method that we'll be using most often as we build up the library is render(), which creates and returns HTML files using templates and data—we'll talk a lot more about that in a later article!

+ +

HTTP verbs

+ +

The example routes above use the Router.get() method to respond to HTTP GET requests with a certain path.

+ +

The Router also provides route methods for all the other HTTP verbs, that are mostly used in exactly the same way: post(), put(), delete(), options(), trace(), copy(), lock(), mkcol(), move(), purge(), propfind(), proppatch(), unlock(), report(), ​​​​​​ mkactivity(), checkout(), merge(), m-search(), notify(), subscribe(), unsubscribe(), patch(), search(), and connect().

+ +

For example, the code below behaves just like the previous /about route, but only responds to HTTP POST requests.

+ +
router.post('/about', function (req, res) {
+  res.send('About this wiki');
+})
+ +

Route paths

+ +

The route paths define the endpoints at which requests can be made. The examples we've seen so far have just been strings, and are used exactly as written: '/', '/about', '/book', '/any-random.path'.

+ +

Route paths can also be string patterns. String patterns use a subset of regular expression syntax to define patterns of endpoints that will be matched. The subset is listed below (note that the hyphen (-) and the dot (.) are interpreted literally by string-based paths):

+ + + +

The route paths can also be JavaScript regular expressions. For example, the route path below will match catfish and dogfish, but not catflap, catfishhead, and so on. Note that the path for a regular expression uses regular expression syntax (it is not a quoted string as in the previous cases).

+ +
app.get(/.*fish$/, function (req, res) {
+  ...
+})
+ +
+

Note: Most of our routes for the LocalLibrary will simply use strings and not string patterns and regular expressions. We'll also use route parameters as discussed in the next section.

+
+ +

Route parameters

+ +

Route parameters are named URL segments used to capture the values specified at their position in the URL. The named segments are prefixed with a colon and then the name (e.g. /:your_parameter_name/. The captured values are stored in the req.params object using the parameter names as keys (e.g. req.params.your_parameter_name).

+ +

So for example, consider a URL encoded to contain information about users and books: http://localhost:3000/users/34/books/8989. We can extract this information as shown below, with the userId and bookId path parameters:

+ +
app.get('/users/:userId/books/:bookId', function (req, res) {
+  // Access userId via: req.params.userId
+  // Access bookId via: req.params.bookId
+  res.send(req.params);
+})
+
+ +

The names of route parameters must be made up of “word characters” (A-Z, a-z, 0-9, and _).

+ +
+

Note: The URL /book/create will be matched by a route like /book/:bookId (which will extract a "bookId" value of 'create'). The first route that matches an incoming URL will be used, so if you want to process /book/create URLs separately, their route handler must be defined before your /book/:bookId route.

+
+ +

That's all you need to get started with routes - if needed you can find more information in the Express docs: Basic routing and Routing guide. The following sections show how we'll set up our routes and controllers for the LocalLibrary.

+ +

Routes needed for the LocalLibrary

+ +

The URLs that we're ultimately going to need for our pages are listed below, where object is replaced by the name of each of our models (book, bookinstance, genre, author), objects is the plural of object, and id is the unique instance field (_id) that is given to each Mongoose model instance by default.

+ + + +

The first home page and list pages don't encode any additional information. While the results returned will depend on the model type and the content in the database, the queries run to get the information will always be the same (similarly the code run for object creation will always be similar).

+ +

By contrast the other URLs are used to act on a specific document/model instance—these encode the identity of the item in the URL (shown as <id> above). We'll use path parameters to extract the encoded information and pass it to the route handler (and in a later article we'll use this to dynamically determine what information to get from the database). By encoding the information in our URL we only need one route for every resource of a particular type (e.g. one route to handle the display of every single book item).

+ +
+

Note: Express allows you to construct your URLs any way you like — you can encode information in the body of the URL as shown above or use URL GET parameters (e.g. /book/?id=6). Whichever approach you use, the URLs should be kept clean, logical and readable (check out the W3C advice here).

+
+ +

Next we create our route handler callback functions and route code for all the above URLs.

+ +

Create the route-handler callback functions

+ +

Before we define our routes, we'll first create all the dummy/skeleton callback functions that they will invoke. The callbacks will be stored in separate "controller" modules for Books, BookInstances, Genres, and Authors (you can use any file/module structure, but this seems an appropriate granularity for this project).

+ +

Start by creating a folder for our controllers in the project root (/controllers) and then create separate controller files/modules for handling each of the models:

+ +
/express-locallibrary-tutorial  //the project root
+  /controllers
+    authorController.js
+    bookController.js
+    bookinstanceController.js
+    genreController.js
+ +

Author controller

+ +

Open the /controllers/authorController.js file and copy in the following code:

+ +
var Author = require('../models/author');
+
+// Display list of all Authors.
+exports.author_list = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author list');
+};
+
+// Display detail page for a specific Author.
+exports.author_detail = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author detail: ' + req.params.id);
+};
+
+// Display Author create form on GET.
+exports.author_create_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author create GET');
+};
+
+// Handle Author create on POST.
+exports.author_create_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author create POST');
+};
+
+// Display Author delete form on GET.
+exports.author_delete_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author delete GET');
+};
+
+// Handle Author delete on POST.
+exports.author_delete_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author delete POST');
+};
+
+// Display Author update form on GET.
+exports.author_update_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author update GET');
+};
+
+// Handle Author update on POST.
+exports.author_update_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Author update POST');
+};
+
+ +

The module first requires the model that we'll later be using to access and update our data. It then exports functions for each of the URLs we wish to handle (the create, update and delete operations use forms, and hence also have additional methods for handling form post requests — we'll discuss those methods in the "forms article" later on).

+ +

All the functions have the standard form of an Express middleware function, with arguments for the request, response, and the next function to be called if the method does not complete the request cycle (in all these cases it does!). The methods simply return a string indicating that the associated page has not yet been created. If a controller function is expected to receive path parameters, these are output in the message string (see req.params.id above).

+ +

BookInstance controller

+ +

Open the /controllers/bookinstanceController.js file and copy in the following code (this follows an identical pattern to the Author controller module):

+ +
var BookInstance = require('../models/bookinstance');
+
+// Display list of all BookInstances.
+exports.bookinstance_list = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance list');
+};
+
+// Display detail page for a specific BookInstance.
+exports.bookinstance_detail = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance detail: ' + req.params.id);
+};
+
+// Display BookInstance create form on GET.
+exports.bookinstance_create_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance create GET');
+};
+
+// Handle BookInstance create on POST.
+exports.bookinstance_create_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance create POST');
+};
+
+// Display BookInstance delete form on GET.
+exports.bookinstance_delete_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance delete GET');
+};
+
+// Handle BookInstance delete on POST.
+exports.bookinstance_delete_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance delete POST');
+};
+
+// Display BookInstance update form on GET.
+exports.bookinstance_update_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance update GET');
+};
+
+// Handle bookinstance update on POST.
+exports.bookinstance_update_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: BookInstance update POST');
+};
+
+ +

Genre controller

+ +

Open the /controllers/genreController.js file and copy in the following text (this follows an identical pattern to the Author and BookInstance files):

+ +
var Genre = require('../models/genre');
+
+// Display list of all Genre.
+exports.genre_list = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre list');
+};
+
+// Display detail page for a specific Genre.
+exports.genre_detail = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre detail: ' + req.params.id);
+};
+
+// Display Genre create form on GET.
+exports.genre_create_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre create GET');
+};
+
+// Handle Genre create on POST.
+exports.genre_create_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre create POST');
+};
+
+// Display Genre delete form on GET.
+exports.genre_delete_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre delete GET');
+};
+
+// Handle Genre delete on POST.
+exports.genre_delete_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre delete POST');
+};
+
+// Display Genre update form on GET.
+exports.genre_update_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre update GET');
+};
+
+// Handle Genre update on POST.
+exports.genre_update_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Genre update POST');
+};
+
+ +

Book controller

+ +

Open the /controllers/bookController.js file and copy in the following code. This follows the same pattern as the other controller modules, but additionally has an index() function for displaying the site welcome page:

+ +
var Book = require('../models/book');
+
+exports.index = function(req, res) {
+    res.send('NOT IMPLEMENTED: Site Home Page');
+};
+
+// Display list of all books.
+exports.book_list = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book list');
+};
+
+// Display detail page for a specific book.
+exports.book_detail = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book detail: ' + req.params.id);
+};
+
+// Display book create form on GET.
+exports.book_create_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book create GET');
+};
+
+// Handle book create on POST.
+exports.book_create_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book create POST');
+};
+
+// Display book delete form on GET.
+exports.book_delete_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book delete GET');
+};
+
+// Handle book delete on POST.
+exports.book_delete_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book delete POST');
+};
+
+// Display book update form on GET.
+exports.book_update_get = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book update GET');
+};
+
+// Handle book update on POST.
+exports.book_update_post = function(req, res) {
+    res.send('NOT IMPLEMENTED: Book update POST');
+};
+
+ +

Create the catalog route module

+ +

Next we create routes for all the URLs needed by the LocalLibrary website, which will call the controller functions we defined in the previous section.

+ +

The skeleton already has a ./routes folder containing routes for the index and users. Create another route file — catalog.js — inside this folder, as shown.

+ +
/express-locallibrary-tutorial //the project root
+  /routes
+    index.js
+    users.js
+    catalog.js
+ +

Open /routes/catalog.js and copy in the code below:

+ +
var express = require('express');
+var router = express.Router();
+
+// Require controller modules.
+var book_controller = require('../controllers/bookController');
+var author_controller = require('../controllers/authorController');
+var genre_controller = require('../controllers/genreController');
+var book_instance_controller = require('../controllers/bookinstanceController');
+
+/// BOOK ROUTES ///
+
+// GET catalog home page.
+router.get('/', book_controller.index);
+
+// GET request for creating a Book. NOTE This must come before routes that display Book (uses id).
+router.get('/book/create', book_controller.book_create_get);
+
+// POST request for creating Book.
+router.post('/book/create', book_controller.book_create_post);
+
+// GET request to delete Book.
+router.get('/book/:id/delete', book_controller.book_delete_get);
+
+// POST request to delete Book.
+router.post('/book/:id/delete', book_controller.book_delete_post);
+
+// GET request to update Book.
+router.get('/book/:id/update', book_controller.book_update_get);
+
+// POST request to update Book.
+router.post('/book/:id/update', book_controller.book_update_post);
+
+// GET request for one Book.
+router.get('/book/:id', book_controller.book_detail);
+
+// GET request for list of all Book items.
+router.get('/books', book_controller.book_list);
+
+/// AUTHOR ROUTES ///
+
+// GET request for creating Author. NOTE This must come before route for id (i.e. display author).
+router.get('/author/create', author_controller.author_create_get);
+
+// POST request for creating Author.
+router.post('/author/create', author_controller.author_create_post);
+
+// GET request to delete Author.
+router.get('/author/:id/delete', author_controller.author_delete_get);
+
+// POST request to delete Author.
+router.post('/author/:id/delete', author_controller.author_delete_post);
+
+// GET request to update Author.
+router.get('/author/:id/update', author_controller.author_update_get);
+
+// POST request to update Author.
+router.post('/author/:id/update', author_controller.author_update_post);
+
+// GET request for one Author.
+router.get('/author/:id', author_controller.author_detail);
+
+// GET request for list of all Authors.
+router.get('/authors', author_controller.author_list);
+
+/// GENRE ROUTES ///
+
+// GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id).
+router.get('/genre/create', genre_controller.genre_create_get);
+
+//POST request for creating Genre.
+router.post('/genre/create', genre_controller.genre_create_post);
+
+// GET request to delete Genre.
+router.get('/genre/:id/delete', genre_controller.genre_delete_get);
+
+// POST request to delete Genre.
+router.post('/genre/:id/delete', genre_controller.genre_delete_post);
+
+// GET request to update Genre.
+router.get('/genre/:id/update', genre_controller.genre_update_get);
+
+// POST request to update Genre.
+router.post('/genre/:id/update', genre_controller.genre_update_post);
+
+// GET request for one Genre.
+router.get('/genre/:id', genre_controller.genre_detail);
+
+// GET request for list of all Genre.
+router.get('/genres', genre_controller.genre_list);
+
+/// BOOKINSTANCE ROUTES ///
+
+// GET request for creating a BookInstance. NOTE This must come before route that displays BookInstance (uses id).
+router.get('/bookinstance/create', book_instance_controller.bookinstance_create_get);
+
+// POST request for creating BookInstance.
+router.post('/bookinstance/create', book_instance_controller.bookinstance_create_post);
+
+// GET request to delete BookInstance.
+router.get('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_get);
+
+// POST request to delete BookInstance.
+router.post('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_post);
+
+// GET request to update BookInstance.
+router.get('/bookinstance/:id/update', book_instance_controller.bookinstance_update_get);
+
+// POST request to update BookInstance.
+router.post('/bookinstance/:id/update', book_instance_controller.bookinstance_update_post);
+
+// GET request for one BookInstance.
+router.get('/bookinstance/:id', book_instance_controller.bookinstance_detail);
+
+// GET request for list of all BookInstance.
+router.get('/bookinstances', book_instance_controller.bookinstance_list);
+
+module.exports = router;
+
+ +

The module requires Express and then uses it to create a Router object. The routes are all set up on the router, which is then exported.

+ +

The routes are defined either using .get() or .post() methods on the router object. All the paths are defined using strings (we don't use string patterns or regular expressions). Routes that act on some specific resource (e.g. book) use path parameters to get the object id from the URL.

+ +

The handler functions are all imported from the controller modules we created in the previous section.

+ +

Update the index route module

+ +

We've set up all our new routes, but we still have a route to the original page. Let's instead redirect this to the new index page that we've created at the path '/catalog'.

+ +

Open /routes/index.js and replace the existing route with the function below.

+ +
// GET home page.
+router.get('/', function(req, res) {
+  res.redirect('/catalog');
+});
+ +
+

Note: This is our first use of the redirect() response method. This redirects to the specified page, by default sending HTTP status code "302 Found". You can change the status code returned if needed, and supply either absolute or relative paths.

+
+ +

Update app.js

+ +

The last step is to add the routes to the middleware chain. We do this in app.js.

+ +

Open app.js and require the catalog route below the other routes (add the third line shown below, underneath the other two):

+ +
var index = require('./routes/index');
+var users = require('./routes/users');
+var catalog = require('./routes/catalog');  //Import routes for "catalog" area of site
+ +

Next, add the catalog route to the middleware stack below the other routes (add the third line shown below, underneath the other two):

+ +
app.use('/', index);
+app.use('/users', users);
+app.use('/catalog', catalog);  // Add catalog routes to middleware chain.
+ +
+

Note: We have added our catalog module at a path '/catalog'. This is prepended to all of the paths defined in the catalog module. So for example, to access a list of books, the URL will be: /catalog/books/.

+
+ +

That's it. We should now have routes and skeleton functions enabled for all the URLs that we will eventually support on the LocalLibrary website.

+ +

Testing the routes

+ +

To test the routes, first start the website using your usual approach

+ + + +

Then navigate to a number of LocalLibrary URLs, and verify that you don't get an error page (HTTP 404). A small set of URLs are listed below for your convenience:

+ + + +

Summary

+ +

We've now created all the routes for our site, along with dummy controller functions that we can populate with a full implementation in later articles. Along the way we've learned a lot of fundamental information about Express routes, and some approaches for structuring our routes and controllers.

+ +

In our next article we'll create a proper welcome page for the site, using views (templates) and information stored in our models.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/uk/learn/server-side/index.html b/files/uk/learn/server-side/index.html new file mode 100644 index 0000000000..c79d8ea81e --- /dev/null +++ b/files/uk/learn/server-side/index.html @@ -0,0 +1,52 @@ +--- +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. Simlarly, 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 framwork, 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.
+
diff --git "a/files/uk/learn/tools_and_testing/git_\321\202\320\260_github/index.html" "b/files/uk/learn/tools_and_testing/git_\321\202\320\260_github/index.html" new file mode 100644 index 0000000000..6797857c6e --- /dev/null +++ "b/files/uk/learn/tools_and_testing/git_\321\202\320\260_github/index.html" @@ -0,0 +1,86 @@ +--- +title: Git та GitHub +slug: Learn/Tools_and_testing/Git_та_GitHub +translation_of: Learn/Tools_and_testing/GitHub +--- +
{{LearnSidebar}}
+ +

All developers will use some kind of version control system (VCS), a tool to allow them to collaborate with other developers on a project without danger of them overwriting each other's work, and roll back to previous versions of the code base if a problem is discovered later on. The most popular VCS (at least among web developers) is Git, along with GitHub, a site that provides hosting for your repositories and several tools for working with them. This module aims to teach you what you need to know about both of them.

+ +

Overview

+ +

VCSes are essential for software development:

+ + + +

VCSes provide tools to meet the above needs. Git is an example of a VCS, and GitHub is a web site + infrastructure that provides a Git server plus a number of really useful tools for working with git repositories individually or in teams, such as reporting issues with the code, reviewing tools, project management features such as assigning tasks and task statuses, and more.

+ +
+

Note: Git is actually a distributed version control system, meaning that a complete copy of the repository containing the codebase is made on your computer (and everyone else's). You make changes to your own copy, and then push those changes back up to the server, where an administrator will decide whether to merge your changes with the master copy.

+
+ +
+

Looking to become a front-end web developer?

+ +

We have put together a course that includes all the essential information you need to work towards your goal.

+ +

Get started

+
+ +

Prerequisites

+ +

To use Git and GitHub, you need:

+ + + +

In terms of prerequisite knowledge, you don't need to know anything about web development, Git/GitHub or VCSes to start this module. However, it is recommended that you know some coding so that you have reasonable computer literacy, and some code to store in your repositories!

+ +

It is also preferrable that you have some basic terminal knowledge, so for example moving between directories, creating files, and modifying the system PATH.

+ +
+

Note: Github is not the only site/toolset you can use with Git. There are other alternatives such as GitLab that you could try, and you could also try setting your own Git server up and using it instead of GitHub. We've only stuck with GitHub in this course to provide a single way that works.

+
+ +

Guides

+ +

Note that the links below take you to resources on external sites. Eventually we will are aiming to have our own dedicated Git/GitHub course, but for now, these will help you get to grips with the subject in hand.

+ +
+
Hello World (from GitHub)
+
This is a good place to start — this practical guide gets you to jump right into using GitHub, learning the basics of Git such as creating repositories and branches, making commits, and opening and merging pull requests.
+
Git Handbook (from GitHub)
+
This Git Handbook goes into a little more depth, explaining what a VCS is, what a repository is, how the basic GitHub model works, Git commands and examples, and more.
+
Forking Projects (from GitHub)
+
Forking projects is essential when you want to contribute to someone else's code. This guide explains how.
+
About Pull Requests (from GitHub)
+
A useful guide to managing pull requests, the way that your suggested code changes are delivered to people's repositories for consideration.
+
Mastering issues (from GitHub)
+
Issues are like a forum for your GitHub project, where people can ask questions and report problems, and you can manage updates (for example assigning people to fix issues, clarifying the issue, letting people know things are fixed). This articles gives you what you need to know about issues.
+
+ +
+

Note: There is a lot more that you can do with Git and GitHub, but we feel that the above represents the minimum you need to know to start using Git effectively. As you get deeper into Git, you'll start to realise that it is easy to go wrong when you start using more complicated commands. Don't worry, even professional web developers find Git confusing sometimes, and often solve problems by searching for solutions on the web, or consulting sites like Flight rules for Git and Dangit, git!

+
+ +

See also

+ + diff --git a/files/uk/learn/tools_and_testing/index.html b/files/uk/learn/tools_and_testing/index.html new file mode 100644 index 0000000000..721a0ef87f --- /dev/null +++ b/files/uk/learn/tools_and_testing/index.html @@ -0,0 +1,61 @@ +--- +title: Tools and testing +slug: Learn/Tools_and_testing +tags: + - Accessibility + - Automation + - Beginner + - CSS + - CodingScripting + - HTML + - JavaScript + - Landing + - Learn + - NeedsTranslation + - Testing + - Tools + - Topic + - TopicStub + - cross browser + - user testing +translation_of: Learn/Tools_and_testing +--- +
{{LearnSidebar}}
+ +

Once you've started to become comfortable programming with core web technologies (like HTML, CSS, and JavaScript), and you start to get more experience, read more resources, and learn more tips and tricks, you'll start to come across all kind of tools, from JavaScript frameworks, to testing and automation tools, and more besides. As your web projects become larger and more complex, you'll want to start taking advantage of some of these tools, working out a reliable toolchain to give your development process superpowers.

+ +

On top of that, we still need to keep cross-browser support in the forefront of our minds, and make sure that our code follows best practices that allow our projects to work across different browsers and devices that our users are using to browse the Web, and be usable by people with disabilities.

+ +

Working out what tools you should be using can be a difficult process, so we have written this set of articles to inform you of what types of tool are available, what they can do for you, and how to make use of the current industry favourites.

+ +
+

Note: We have referenced a number of tools in this topic, not because we endorse them or think they are the best, but because we know they work and have good industry support. In most cases there are other tools available, old ones will go out of fashion, and new ones will no doubt appear.

+
+ + +
+

Looking to become a front-end web developer?

+ +

We have put together a course that includes all the essential information you need to work towards your goal.

+ +

Get started

+
+ +

Prerequisites

+ +

You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use many the tools detailed here. For example, you'll need to know the fundamentals of these languages before you start debugging problems in complex web code, making effective use of JavaScript frameworks, or writing tests and running them against your code using test runners.

+ +

In addition, you should start with the first module in this topic, which gives a useful overview of the general area.

+ +

Modules

+ +
+
Understanding client-side web development tools
+
Client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. We finish up by providing a complete toolchain example showing you how to get productive.
+
Understanding client-side JavaScript frameworks
+
JavaScript frameworks are an essential part of modern front-end web development, providing developers with tried and tested tools for building scalable, interactive web applications. Many modern companies use frameworks as a standard part of their tooling, so many front-end development jobs now require framework experience. This module gives you some fundamental background knowledge about how client-side frameworks work and how they fit into your toolset, before moving on to tutorial series covering some of today's most popular ones.
+
Git and GitHub
+
All developers will use some kind of version control system (VCS), a tool to allow them to collaborate with other developers on a project without danger of them overwriting each other's work, and roll back to previous versions of the code base if a problem is discovered later on. The most popular VCS (at least among web developers) is Git, along with GitHub, a site that provides hosting for your repositories and several tools for working with them. This module aims to teach you what you need to know about both of them.
+
Cross browser testing
+
This module looks specifically at the area of testing web projects across different browsers. Here we look at identifying your target audience (e.g. what users, browsers and devices do you most need to worry about?), how to go about testing, the main issues that you'll face with different types of code and how to fix/mitigate those, what tools are most useful in helping you test and fix problems, and how to use automation to speed up testing.
+
diff --git "a/files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_javascript-\321\204\321\200\320\265\320\271\320\274\320\262\320\276\321\200\320\272\321\226\320\262_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/index.html" "b/files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_javascript-\321\204\321\200\320\265\320\271\320\274\320\262\320\276\321\200\320\272\321\226\320\262_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/index.html" new file mode 100644 index 0000000000..4380250538 --- /dev/null +++ "b/files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_javascript-\321\204\321\200\320\265\320\271\320\274\320\262\320\276\321\200\320\272\321\226\320\262_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/index.html" @@ -0,0 +1,138 @@ +--- +title: Розуміння JavaScript-фреймворків на стороні клієнта +slug: Learn/Tools_and_testing/Розуміння_JavaScript-фреймворків_на_стороні_клієнта +translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks +--- +
{{LearnSidebar}}
+ +

JavaScript frameworks are an essential part of modern front-end web development, providing developers with tried and tested tools for building scalable, interactive web applications. Many modern companies use frameworks as a standard part of their tooling, so many front-end development jobs now require framework experience.

+ +

As an aspiring front-end developer, it can be hard to work out where to begin when learning frameworks — there are so many different frameworks to choose from, new ones appear all the time, they mostly work in a similar way but do some things differently, and there are some specific things to be careful about when using frameworks.

+ +

In this set of articles, we are aiming to give you a comfortable starting point to help you begin learning frameworks. We are not aiming to exhaustively teach you everything you need to know about React/ReactDOM, or Vue, or some other specific framework; the framework teams' own docs do that job already. Instead, we want to back up and first answer more fundamental questions such as:

+ + + +

After that, we'll provide some tutorials covering the essentials of some of the major frameworks, to provide you with enough context and familiarity to start going into greater depth yourself. We want you to go forward and learn about frameworks in a pragmatic way that doesn't forget about web platform fundamental best practices such as accessibility.

+ +

Get started now, with "Introduction to client-side frameworks"

+ +

Prerequisites

+ +

You should really learn the basics of the core web languages first before attempting to move on to learning client-side frameworks — HTML, CSS, and especially JavaScript.

+ +

Your code will be richer and more professional as a result, and you'll be able to troubleshoot problems with more confidence if you understand the fundamental web platform features that the frameworks are building on top of.

+ +
+

Looking to become a front-end web developer?

+ +

We have put together a course that includes all the essential information you need to work towards your goal.

+ +

Get started

+
+ +

Introductory guides

+ +
+
1. Introduction to client-side frameworks
+
We begin our look at frameworks with a general overview of the area, looking at a brief history of JavaScript and frameworks, why frameworks exist and what they give us, how to start thinking about choosing a framework to learn, and what alternatives there are to client-side frameworks.
+
2. Framework main features
+
Each major JavaScript framework has a different approach to updating the DOM, handling browser events, and providing an enjoyable developer experience. This article will explore the main features of “the big 4” frameworks, looking at how frameworks tend to work from a high level and the differences between them.
+
+ +

React tutorials

+ +
+

Note: React tutorials last tested in May 2020, with React/ReactDOM 16.13.1 and create-react-app 3.4.1.

+ +

If you need to check your code against our version, you can find a finished version of the sample React app code in our todo-react repository. For a running live version, see https://mdn.github.io/todo-react-build/.

+
+ +
+
1. Getting started with React
+
In this article we will say hello to React. We'll discover a little bit of detail about its background and use cases, set up a basic React toolchain on our local computer, and create and play with a simple starter app, learning a bit about how React works in the process.
+
2. Beginning our React todo list
+
Let's say that we’ve been tasked with creating a proof-of-concept in React – an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as complete without deleting them. This article will walk you through putting the basic App component structure and styling in place, ready for individual component definition and interactivity, which we'll add later.
+
3. Componentizing our React app
+
At this point, our app is a monolith. Before we can make it do things, we need to break it apart into manageable, descriptive components. React doesn’t have any hard rules for what is and isn’t a component – that’s up to you! In this article, we will show you a sensible way to break our app up into components.
+
4. React interactivity: Events and state
+
With our component plan worked out, it's now time to start updating our app from a completely static UI to one that actually allows us to interact and change things. In this article we'll do this, digging into events and state along the way.
+
5. React interactivity: Editing, filtering, conditional rendering
+
As we near the end of our React journey (for now at least), we'll add the finishing touches to the main areas of functionality in our Todo list app. This includes allowing you to edit existing tasks and filtering the list of tasks between all, completed, and incomplete tasks. We'll look at conditional UI rendering along the way.
+
6. Accessibility in React
+
In our final tutorial article, we'll focus on (pun intended) accessibility, including focus management in React, which can improve usability and reduce confusion for both keyboard-only and screen reader users.
+
7. React resources
+
Our final article provides you with a list of React resources that you can use to go further in your learning.
+
+ +

Ember tutorials

+ +
+

Note: Ember tutorials last tested in May 2020, with Ember/Ember CLI version 3.18.0.

+ +

If you need to check your code against our version, you can find a finished version of the sample Ember app code in the ember-todomvc-tutorial repository. For a running live version, see https://nullvoxpopuli.github.io/ember-todomvc-tutorial/ (this also includes a few additional features not covered in the tutorial).

+
+ +
+
1. Getting started with Ember
+
In our first Ember article we will look at how Ember works and what it's useful for, install the Ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development.
+
2. Ember app structure and componentization
+
In this article we'll get right on with planning out the structure of our TodoMVC Ember app, adding in the HTML for it, and then breaking that HTML structure into components.
+
3. Ember interactivity: Events, classes and state
+
At this point we'll start adding some interactivity to our app, providing the ability to add and display new todo items. Along the way, we'll look at using events in Ember, creating component classes to contain JavaScript code to control interactive features, and setting up a service to keep track of the data state of our app.
+
4. Ember Interactivity: Footer functionality, conditional rendering
+
Now it's time to start tackling the footer functionality in our app. Here we'll get the todo counter to update to show the correct number of todos still to complete, and correctly apply styling to completed todos (i.e. where the checkbox has been checked). We'll also wire up our "Clear completed" button. Along the way, we'll learn about using conditional rendering in our templates.
+
5. Routing in Ember
+
In this article we learn about routing or URL-based filtering as it is sometimes referred to. We'll use it to provide a unique URL for each of the three todo views — "All", "Active", and "Completed".
+
6. Ember resources and troubleshooting
+
Our final Ember article provides you with a list of resources that you can use to go further in your learning, plus some useful troubleshooting and other information.
+
+ +

Vue tutorials

+ +
+

Note: Vue tutorials last tested in May 2020, with Vue 2.6.11.

+ +

If you need to check your code against our version, you can find a finished version of the sample Vue app code in our todo-vue repository. For a running live version, see https://mdn.github.io/todo-vue/dist/.

+
+ +
+
1. Getting started with Vue
+
Now let's introduce Vue, the third of our frameworks. In this article, we'll look at a little bit of Vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example.
+
2. Creating our first Vue component
+
Now it's time to dive deeper into Vue, and create our own custom component — we'll start by creating a component to represent each item in the todo list. Along the way, we'll learn about a few important concepts such as calling components inside other components, passing data to them via props and saving data state.
+
3. Rendering a list of Vue components
+
At this point we've got a fully working component; we're now ready to add multiple ToDoItem components to our App. In this article we'll look at adding a set of todo item data to our App.vue component, which we'll then loop through and display inside ToDoItem components using the v-for directive.
+
4. Adding a new todo form: Vue events, methods, and models
+
We now have sample data in place and a loop that takes each bit of data and renders it inside a ToDoItem in our app. What we really need next is the ability to allow our users to enter their own todo items into the app, and for that, we'll need a text <input>, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. This is what we'll cover in this article.
+
5. Styling Vue components with CSS
+
The time has finally come to make our app look a bit nicer. In this article, we'll explore the different ways of styling Vue components with CSS.
+
6. Using Vue computed properties
+
In this article we'll add a counter that displays the number of completed todo items, using a feature of Vue called computed properties. These work similarly to methods but only re-run when one of their dependencies changes.
+
7. Vue conditional rendering: editing existing todos
+
Now it is time to add one of the major parts of functionality that we're still missing — the ability to edit existing todo items. To do this, we will take advantage of Vue's conditional rendering capabilities — namely v-if and v-else — to allow us to toggle between the existing todo item view and an edit view where you can update todo item labels. We'll also look at adding functionality to delete todo items.
+
8. Focus management with Vue refs
+
We are nearly done with Vue. The last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility. We'll look at using Vue refs to handle this — an advanced feature that allows you to have direct access to the underlying DOM nodes below the virtual DOM, or direct access from one component to the internal DOM structure of a child component.
+
9. Vue resources
+
Now we'll round off our study of Vue by giving you a list of resources that you can use to go further in your learning, plus some other useful tips.
+
+ +

Which frameworks did we choose?

+ +

We are publishing our initial set of articles with guides focusing on three of the major frameworks out there — React/ReactDOM, Ember, and Vue. There is a variety of reasons for this:

+ + + +

We want to say this upfront — we've not chosen the frameworks we are focusing on because we think they are the best, or because we endorse them in any way. We just think they score highly on the above criteria.

+ +

Note that we were hoping to have more frameworks included upon initial publication, but we decided to release the content and then add more framework guides later, rather than delay it longer. If your favourite framework is not represented in this content and you'd like to help change that, feel free to discuss it with us! Get in touch with us via Matrix, or Discourse, or drop us a mail on the mdn-admins list.

diff --git "a/files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_javascript-\321\204\321\200\320\265\320\271\320\274\320\262\320\276\321\200\320\272\321\226\320\262_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/znayomymos_zi_svelte/index.html" "b/files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_javascript-\321\204\321\200\320\265\320\271\320\274\320\262\320\276\321\200\320\272\321\226\320\262_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/znayomymos_zi_svelte/index.html" new file mode 100644 index 0000000000..ba73b81f2b --- /dev/null +++ "b/files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_javascript-\321\204\321\200\320\265\320\271\320\274\320\262\320\276\321\200\320\272\321\226\320\262_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/znayomymos_zi_svelte/index.html" @@ -0,0 +1,536 @@ +--- +title: Знайомимось зі Свелт +slug: >- + Learn/Tools_and_testing/Розуміння_JavaScript-фреймворків_на_стороні_клієнта/znayomymos_zi_svelte +translation_of: >- + Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started +--- +
{{LearnSidebar}}
+{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
+ +

У цій статті ми коротко ознайомимося з фреймворком Свелт. Ми побачимо як Свелт працює і що виокремлює його від інших фреймворків та інструментів, які ми вже бачили. Далі ми навчимося налаштовувати наше середовище розробки, створимо простий додаток, зрозуміємо структуру проекту, та побачимо як його запускати локально і збирати для продакшна.

+ + + + + + + + + + + + +
Передумови:Для початку, рекомендуємо ознайомитись з основними мовами – HTML, CSS та JavaScript, та володіти терміналом/командним рядком. +


+ Свелт – компілятор, який генерує маленький та високооптимізований JavaScript код з нашого; вам знадобиться термінал з Нодою та NPM – для компіляції та збирання вашої програми.

+
Мета: +

Налаштувати локальне середовище розробки Svelte, створити та зібрати перший додаток, зрозуміти основи того, як це працює.

+
+ +

Свелт: новий підхід до створення складних інтерфейсів

+ +

Светл пропонує інший підхід до створення веб-додатків, ніж деякі інші фреймворки у цьому модулі. Тоді як Реакт або В'ю виконують основну частину своєї роботи в браузері користувача, під час роботи програми, Свелт зміщує цю роботу на етап компіляції, який відбувається лише під час збирання програми, створюючи високооптимізований ванільний JavaScript.
+
+ Результатом такого підходу є не тільки менші бандли та краща швидкість додатків, але й приємнішний досвід розробки – більш доступний для людей, які мають обмежений досвід роботи з екосистемою сучасних інструментів.
+
+ Свелт тісно притримується класичної моделі веб-розробки HTML, CSS та JS, лише додаючи кілька розширень до HTML та JavaScript. Напевно, в ньому є менше понять та інструментів для вивчення, ніж в деякі інших фреймворках.
+
+ Головними нинішніми недоліками є те, що це молодий фреймворк – тому його екосистема є більш обмеженою щодо інструментарію, підтримки, плагінів, чітких моделей використання тощо, ніж у більш зрілих фреймворків, а також є менше вакансій. Але його переваг повинно бути достатньо, щоб зацікавити вас дослідити його.

+ +
+

Примітка: нещодавно Свелт додав офіційну підтримку TypeScript, одну з найочікуваніших можливостей. Ми розглянемо її згодом у цій серії уроків.

+
+ +

Перед тим, як повернутися до цієї серії уроків, ми рекомендуємо вам прочитати навчальний посібник Свелт, щоб по-справжньому швидко познайомитися з основними поняттями, а потім навчитися будувати щось більш глибоке. Це займе близько 30 хвилин.

+ +

Use cases

+ +

Svelte can be used to develop small pieces of an interface or whole applications. You can either start from scratch letting Svelte drive your UI or you can incrementally integrate it into an existing application.

+ +

Nevertheless, Svelte is particularly appropriate to tackle the following situations:

+ + + +

Moreover, with the help of Sapper (a framework based on Svelte), you can also develop applications with advanced features like server-side rendering, code splitting, file-based routing and offline support. And then there's also Svelte Native, which lets you build native mobile applications.

+ +

How does Svelte work?

+ +

Being a compiler, Svelte can extend HTML, CSS, and JavaScript, generating optimal JavaScript code without any runtime overhead. To achieve this, Svelte extends vanilla web technologies in the following ways:

+ + + +

The compiler only intervenes in very specific situations and only in the context of Svelte components. Extensions to the JavaScript language are minimal and carefully picked in order to not break JavaScript syntax nor alienate developers. In fact, you will be mostly working with vanilla JavaScript.

+ +

First steps with Svelte

+ +

Being a compiler, you can't just add a <script src="svelte.js"> tag to your page and import it into your app. You'll have to set up your development environment in order to let the compiler do its job.

+ +

Requirements

+ +

In order to work with Svelte you need to have Node.js installed. It's recommended that you use the long-term support (LTS) version. Node includes npm (the node package manager), and npx (the node package runner). Note that you can also use the Yarn package manager in place of npm, but we'll assume you are using npm in this set of tutorials. See Package management basics for more information on npm and yarn.

+ +

If you're using Windows, you will need to install some software to give you parity with Unix/macOS terminal in order to use the terminal commands mentioned in this tutorial. Gitbash (which comes as part of the git for Windows toolset) or Windows Subsystem for Linux (WSL) are both suitable. Cmder is another very good and complete alternative. See Command line crash course for more information on these, and on terminal commands in general.

+ +

Also see the following for more information:

+ + + +

Creating your first Svelte app

+ +

The easiest way to create a starter app template is to just download the starter template application. You can do that by visiting sveltejs/template on GitHub or you can avoid having to download and unzip it and just use degit.

+ +

To create your starter app template, run the following terminal commands:

+ +
npx degit sveltejs/template moz-todo-svelte
+cd moz-todo-svelte
+npm install
+npm run dev
+ +
+

Note: degit doesn't do any kind of magic — it just lets you download and unzip the latest version of a git repo's contents. This is much quicker than using git clone because it will not download all the history of the repo, or create a complete local clone.

+
+ +

After running npm run dev, Svelte will compile and build your application. It will start a local server at localhost:5000. Svelte will watch for file updates, and automatically recompile and refresh the app for you when changes are made to the source files. Your browser will display something like this:

+ +

A simple start page that says hello world, and gives a link to the official svelte tutorials

+ +

Application structure

+ +

The starter template comes with the following structure:

+ +
moz-todo-svelte
+├── readme.md
+├── package.json
+├── package-lock.json
+├── rollup.config.js
+├── .gitignore
+├── node_modules
+├── public
+│   ├── favicon.ico
+│   ├── index.html
+│   ├── global.css
+│   └── build
+│       ├── bundle.css
+│       ├── bundle.css.map
+│       ├── bundle.js
+│       └── bundle.js.map
+└── src
+    ├── App.svelte
+    └── main.js
+ +

The contents are as follows:

+ + + +

Having a look at our first Svelte component

+ +

Components are the building blocks of Svelte applications. They are written into .svelte files using a superset of HTML.

+ +

All three sections — <script>, <styles>, and markup — are optional, and can appear in any order you like.

+ +
<script>
+  // logic goes here
+</script>
+
+<style>
+  /* styles go here */
+</style>
+
+<!-- markup (zero or more HTML elements) goes here -->
+ +
+

Note: For more information on the component format, have a look at the svelte documentation.

+
+ +

With this in mind, let's have a look at the src/App.svelte file that came with the starter template. You should see something like the following:

+ +
<script>
+  export let name;
+</script>
+
+<main>
+  <h1>Hello {name}!</h1>
+  <p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
+</main>
+
+<style>
+  main {
+    text-align: center;
+    padding: 1em;
+    max-width: 240px;
+    margin: 0 auto;
+  }
+
+  h1 {
+    color: #ff3e00;
+    text-transform: uppercase;
+    font-size: 4em;
+    font-weight: 100;
+  }
+
+  @media (min-width: 640px) {
+    main {
+      max-width: none;
+    }
+  }
+</style>
+ +

The <script> section

+ +

The <script> block contains JavaScript that runs when a component instance is created. Variables declared (or imported) at the top level are 'visible' from the component's markup. Top-level variables is the way Svelte handles the component state, and they are reactive by default. We will explain in detail what this means later on.

+ +
<script>
+  export let name;
+</script>
+ +

Svelte uses the export keyword to mark a variable declaration as a property (or prop), which means it becomes accessible to consumers of the component (e.g. other components). This is one example of Svelte extending JavaScript syntax to make it more useful, while keeping it familiar.

+ +

The markup section

+ +

In the markup section you can insert any HTML you like, and in addition you can insert valid JavaScript expression inside single curly brackets ({}). In this case we are embedding the value of the name prop right after the Hello text.

+ +
<main>
+  <h1>Hello {name}!</h1>
+  <p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
+</main>
+ +

Svelte also supports tags like {#if...}, {#each...}, and {#await...} — these examples allow you to conditionally render a portion of the markup, iterate through a list of elements, and work with async values, respectively.

+ +

The <style> section

+ +

If you have experience working with CSS, the following snippet should make sense:

+ +
<style>
+  main {
+    text-align: center;
+    padding: 1em;
+    max-width: 240px;
+    margin: 0 auto;
+  }
+
+  h1 {
+    color: #ff3e00;
+    text-transform: uppercase;
+    font-size: 4em;
+    font-weight: 100;
+  }
+
+  @media (min-width: 640px) {
+    main {
+      max-width: none;
+    }
+  }
+</style>
+ +

We are applying a style to our <h1> element. What will happen other components with <h1> elements in them?

+ +

In Svelte, CSS inside a component's <style> block will be scoped only to that component. This works by adding a class to selected elements, which is based on a hash of the component styles.

+ +

You can see this in action by opening localhost:5000 in a new browser tab, right/Ctrl-clicking on the HELLO WORLD! label, and choosing Inspect:

+ +

Svelte starter app with devtools open, showing classes for scoped styles

+ +

When compiling the app, Svelte changes our h1 styles definition to h1.svelte-1tky8bj, and then modifies every <h1> element in our component to <h1 class="svelte-1tky8bj">, so that it picks up the styles as required.

+ +
+

Note: You can override this behavior and apply styles to a selector globally using the :global(...) modifier (see the Svelte <style> docs for more information).

+
+ +

Making a couple of changes

+ +

Now that we have a general idea of how it all fits together, we can start making a few changes.
+ At this point you can try updating your App.svelte component — for example change the <h1> element on line 6 of App.svelte so that it reads like this:

+ +
<h1>Hello {name} from MDN!</h1>
+ +

Just save your changes and the app running at localhost:5000 will be automatically updated.

+ +

A first look at Svelte reactivity

+ +

In the context of a UI framework, reactivity means that the framework can automatically update the DOM when the state of any component is changed.

+ +

In Svelte, reactivity is triggered simply by assigning a new value to any top level variable in a component. For example, we could include a toggleName() function in our App component, and a button to run it.

+ +

Try updating your <script> and markup sections like so:

+ +
<script>
+  export let name;
+
+  function toggleName() {
+    if (name === 'world') {
+      name = 'svelte'
+    } else {
+      name = 'world'
+    }
+  }
+</script>
+
+<main>
+  <h1>Hello {name}!</h1>
+  <button on:click={toggleName}>Toggle name</button>
+  <p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
+</main>
+ +

Whenever the button is clicked, Svelte executes the toggleName() function, which in turn updates the value of the name variable.

+ +

As you can see, the <h1> label is automatically updated. Behind the scenes, Svelte created the JavaScript code to update the DOM whenever the value of the name variable changes, without using any virtual DOM or other complex reconciliation mechanism.

+ +

Note the use of : in on:click. That's Svelte's syntax for listening to DOM events.

+ +

Inspecting main.js: the entry point of our app

+ +

Let’s open src/main.js, which is where the App component is being imported and used. This file is the entry point for our app, and it initially looks like this:

+ +
import App from './App.svelte';
+
+const app = new App({
+  target: document.body,
+  props: {
+    name: 'world'
+  }
+});
+
+export default app;
+ +

main.js starts by importing the Svelte component that we are going to use. Then in line 3 it instantiates it, passing an option object with the following properties:

+ + + +

A look under the hood

+ +

How does Svelte manage to make all these files work together nicely?

+ +

The Svelte compiler processes the <style> section of every component and compiles them into the public/build/bundle.css file.

+ +

It also compiles the markup and <script> section of every component and stores the result in public/build/bundle.js. It also adds the code in src/main.js to reference the features of each component.

+ +

Finally the file public/index.html includes the generated bundle.css and bundle.js files:

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset='utf-8'>
+  <meta name='viewport' content='width=device-width,initial-scale=1'>
+
+  <title>Svelte app</title>
+
+  <link rel='icon' type='image/png' href='/favicon.png'>
+  <link rel='stylesheet' href='/global.css'>
+  <link rel='stylesheet' href='/build/bundle.css'>
+
+  <script defer src='/build/bundle.js'></script>
+</head>
+
+<body>
+</body>
+</html>
+ +

The minified version of bundle.js weighs a little more than 3KB, which includes the "Svelte runtime" (just 300 lines of JavaScript code) and the App.svelte compiled component. As you can see, bundle.js is the only JavaScript file referenced by index.html. There are no other libraries loaded into the web page.

+ +

This is a much smaller footprint than compiled bundles from other frameworks. Take into account that, in the case of code bundles, it's not just the size of the files you have to download that matter. This is executable code that needs to be parsed, executed, and kept in memory. So this really makes a difference, especially in low-powered devices or CPU-intensive applications.

+ +

Following this tutorial

+ +

In this tutorial series you will be building a complete web application. We'll learn all the basics about Svelte and also quite a few advanced topics.

+ +

You can just read the content to get a good understanding of Svelte features, but you'll get the most out of this tutorial if you follow along coding the app with us as you go. To make it easier for you to follow each article, we provide a GitHub repository with a folder containing the source for the app as it is at the start of each tutorial.

+ +

Svelte also provides an online repl, which is a playground for live-coding Svelte apps on the web without having to install anything on your machine. We provide a repl for each article so you can start coding along right away. Let's talk a bit more about how to use these tools.

+ +

Using Git

+ +

The most popular version control system is Git, along with GitHub, a site that provides hosting for your repositories and several tools for working with them.

+ +

We'll be using GitHub so that you can easily download the source code for each article. You will also be able to get the code as it should be after completing the article, just in case you get lost.

+ +

After installing git, to clone the repository you should execute:

+ +
git clone https://github.com/opensas/mdn-svelte-tutorial.git
+ +

Then at the beginning of each article, you can just cd into the corresponding folder and start the app in dev mode to see what its current state should be, like this:

+ +
cd 02-starting-our-todo-app
+npm install
+npm run dev
+ +

If you want lo learn more about git and GitHub, we've compiled a list of links to useful guides — see Git and GitHub.

+ +
+

Note: If you just want to download the files without cloning the git repo, you can use the degit tool like this — npx degit opensas/mdn-svelte-tutorial. You can also download a specific folder with npx degit opensas/mdn-svelte-tutorial/01-getting-started. Degit won't create a local git repo, it will just download the files of the specified folder.

+
+ +

Using the Svelte REPL

+ +

A REPL (read–eval–print loop) is an interactive environment that allows you to enter commands and immediately see the results — many programming languages provide a REPL.

+ +

Svelte's REPL is much more than that. It's an online tool that allows you to create complete apps, save them online, and share with others.

+ +

It's the easiest way to start playing with Svelte from any machine, without having to install anything. It is also widely used by Svelte community. If you want to share an idea, ask for help, or report an issue, it's always extremely useful to create a REPL instance demomstrating the issue.

+ +

Let's have a quick look at the Svelte REPL and how you'd use it. It looks like so:

+ +

the svelte repl in action, showing component code on the left, and output on the right

+ +

To start a REPL, open your browser and navigate to https://svelte.dev/repl.

+ + + +

Whenever you change any file on the REPL, Svelte will recompile the app and update the Result tab. To share your app simply share the url. For example, here's the link for a REPL running our complete app: https://svelte.dev/repl/378dd79e0dfe4486a8f10823f3813190?version=3.23.2.

+ +
+

Note: Notice how you can specify Svelte's version in the URL. This is useful when reporting issues related to a specific version of Svelte.

+
+ +

We will provide a REPL at the beginning and end of each article so that you can start coding with us right away.

+ +
+

Note: at the moment the REPL can't handle folder names properly. If you are following the tutorial on the REPL, just create all your components inside the root folder. Then when you see a path in the code, for example import Todos from './components/Todos.svelte', just replace it with a flat URL, e.g. import Todos from './Todos.svelte'.

+
+ +

The code so far

+ +

Git

+ +

Clone the github repo (if you haven't already done it) with:

+ +
git clone https://github.com/opensas/mdn-svelte-tutorial.git
+ +

Then to get to the current app state, run

+ +
cd mdn-svelte-tutorial/01-getting-started
+ +

Or directly download the folder's content:

+ +
npx degit opensas/mdn-svelte-tutorial/01-getting-started
+ +

Remember to run npm install && npm run dev to start your app in development mode.

+ +

REPL

+ +

To code along with us using the REPL, start at

+ +

https://svelte.dev/repl/fc68b4f059d34b9c84fa042d1cce586c?version=3.23.2

+ +

Summary

+ +

This brings us to the end of our initial look at Svelte, including how to install it locally, create a starter app, and how the basics work. In the next article we'll start building our first proper application — a todo list. Before we do that, however, let's recap some of the things we’ve learned.

+ +

In Svelte:

+ + + +

{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}

+ +

In this module

+ + diff --git "a/files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_\321\226\320\275\321\201\321\202\321\200\321\203\320\274\320\265\320\275\321\202\321\226\320\262_\320\262\320\265\320\261-\321\200\320\276\320\267\321\200\320\276\320\261\320\272\320\270_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/index.html" "b/files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_\321\226\320\275\321\201\321\202\321\200\321\203\320\274\320\265\320\275\321\202\321\226\320\262_\320\262\320\265\320\261-\321\200\320\276\320\267\321\200\320\276\320\261\320\272\320\270_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/index.html" new file mode 100644 index 0000000000..faa5717122 --- /dev/null +++ "b/files/uk/learn/tools_and_testing/\321\200\320\276\320\267\321\203\320\274\321\226\320\275\320\275\321\217_\321\226\320\275\321\201\321\202\321\200\321\203\320\274\320\265\320\275\321\202\321\226\320\262_\320\262\320\265\320\261-\321\200\320\276\320\267\321\200\320\276\320\261\320\272\320\270_\320\275\320\260_\321\201\321\202\320\276\321\200\320\276\320\275\321\226_\320\272\320\273\321\226\321\224\320\275\321\202\320\260/index.html" @@ -0,0 +1,37 @@ +--- +title: Розуміння інструментів веб-розробки на стороні клієнта +slug: Learn/Tools_and_testing/Розуміння_інструментів_веб-розробки_на_стороні_клієнта +translation_of: Learn/Tools_and_testing/Understanding_client-side_tools +--- +
{{LearnSidebar}}
+ +

Client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. We finish up by providing a complete toolchain example showing you how to get productive.

+ +

Get started now, with our "Client-side tooling overview"

+ +

Prerequisites

+ +

You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here.

+ +
+

Looking to become a front-end web developer?

+ +

We have put together a course that includes all the essential information you need to work towards your goal.

+ +

Get started

+
+ +

Guides

+ +
+
1. Client-side tooling overview
+
In this article we provide an overview of modern web tooling, what kinds of tools are available and where you’ll meet them in the lifecycle of web app development, and how to find help with individual tools.
+
2. Command line crash course
+
In your development process you'll undoubtedly be required to run some command in the terminal (or on the "command line" — these are effectively the same thing). This article provides an introduction to the terminal, the essential commands you'll need to enter into it, how to chain commands together, and how to add your own command line interface (CLI) tools.
+
3. Package management basics
+
In this article we'll look at package managers in some detail to understand how we can use them in our own projects — to install project tool dependencies, keep them up-to-date, and more.
+
4. Introducing a complete toolchain
+
In the final couple of articles in the series we will solidify your tooling knowledge by walking you through the process of building up a sample case study toolchain. We'll go all the way from setting up a sensible development environment and putting transformation tools in place to actually deploying your app on Netlify. In this article we'll introduce the case study, set up our development environment, and set up our code transformation tools.
+
5. Deploying our app
+
In the final article in our series, we take the example toolchain we built up in the previous article and add to it so that we can deploy our sample app. We push the code to GitHub, deploy it using Netlify, and even show you how to add a simple test into the process.
+
diff --git "a/files/uk/learn/tools_and_testing/\321\202\320\265\321\201\321\202\321\203\320\262\320\260\320\275\320\275\321\217_\320\272\321\200\320\276\321\201\320\261\321\200\320\260\321\203\320\267\320\265\321\200\320\275\320\276\321\201\321\202\321\226/index.html" "b/files/uk/learn/tools_and_testing/\321\202\320\265\321\201\321\202\321\203\320\262\320\260\320\275\320\275\321\217_\320\272\321\200\320\276\321\201\320\261\321\200\320\260\321\203\320\267\320\265\321\200\320\275\320\276\321\201\321\202\321\226/index.html" new file mode 100644 index 0000000000..e13df10951 --- /dev/null +++ "b/files/uk/learn/tools_and_testing/\321\202\320\265\321\201\321\202\321\203\320\262\320\260\320\275\320\275\321\217_\320\272\321\200\320\276\321\201\320\261\321\200\320\260\321\203\320\267\320\265\321\200\320\275\320\276\321\201\321\202\321\226/index.html" @@ -0,0 +1,41 @@ +--- +title: Тестування кросбраузерності +slug: Learn/Tools_and_testing/Тестування_кросбраузерності +translation_of: Learn/Tools_and_testing/Cross_browser_testing +--- +
{{LearnSidebar}}
+ +

This module focuses on testing web projects across different browsers. We look at identifying your target audience (e.g. what users, browsers, and devices do you most need to worry about?), how to go about doing testing, the main issues that you'll face with different types of code and how to mitigate them, what tools are most useful in helping you test and fix problems, and how to use automation to speed up testing.

+ +
+

Looking to become a front-end web developer?

+ +

We have put together a course that includes all the essential information you need to work towards your goal.

+ +

Get started

+
+ +

Prerequisites

+ +

You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here.

+ +

Guides

+ +
+
Introduction to cross browser testing
+
This article starts the module off by providing an overview of the topic of cross browser testing, answering questions such as "what is cross browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying, and fixing problems?"
+
Strategies for carrying out testing
+
Next, we drill down into carrying out testing, looking at identifying a target audience (e.g. what browsers, devices, and other segments should you make sure are tested), lo-fi testing strategies (get yourself a range of devices and some virtual machines and do ad-hoc tests when needed), higher tech strategies (automation, using dedicated testing apps), and testing with user groups.
+
Handling common HTML and CSS problems
+
With the scene set, we'll now look specifically at the common cross-browser problems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handing CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
+
Handling common JavaScript problems
+
Now we'll look at common cross-browser JavaScript problems and how to fix them. This includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern JavaScript features working in older browsers, and more.
+
Handling common accessibility problems
+
Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues.
+
Implementing feature detection
+
Feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser can always provide a working experience rather than crashing/erroring in some browsers. This article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as @supports.
+
Introduction to automated testing
+
Manually running tests on several browsers and devices, several times per day, can get tedious and time-consuming. To handle this efficiently, you should become familiar with automation tools. In this article, we look at what is available, how to use task runners, and the basics of how to use commercial browser test automation apps such as Sauce Labs and Browser Stack.
+
Setting up your own test automation environment
+
In this article, we will teach you how to install your own automation environment and run your own tests using Selenium/WebDriver and a testing library such as selenium-webdriver for Node. We will also look at how to integrate your local testing environment with commercial apps like the ones discussed in the previous article.
+
diff --git "a/files/uk/learn/\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" "b/files/uk/learn/\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" new file mode 100644 index 0000000000..465926f459 --- /dev/null +++ "b/files/uk/learn/\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" @@ -0,0 +1,75 @@ +--- +title: Доступність +slug: Learn/Доступність +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.

+ +

The Firefox Accessibility Inspector is a very useful tool for checking out accessibility issues on web pages. The following video provides a nice introduction to it:

+ +

{{EmbedYouTube("7mqqgIxX_NU")}}

+ +
+

Looking to become a front-end web developer?

+ +

We have put together a course that includes all the essential information you need to work towards your goal.

+ +

Get started

+
+ +

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/uk/learn/\320\275\320\260\320\262\321\207\320\260\320\275\320\275\321\217_\321\202\320\260_\320\276\321\202\321\200\320\270\320\274\320\260\320\275\320\275\321\217_\320\264\320\276\320\277\320\276\320\274\320\276\320\263\320\270/index.html" "b/files/uk/learn/\320\275\320\260\320\262\321\207\320\260\320\275\320\275\321\217_\321\202\320\260_\320\276\321\202\321\200\320\270\320\274\320\260\320\275\320\275\321\217_\320\264\320\276\320\277\320\276\320\274\320\276\320\263\320\270/index.html" new file mode 100644 index 0000000000..c1dad68ac9 --- /dev/null +++ "b/files/uk/learn/\320\275\320\260\320\262\321\207\320\260\320\275\320\275\321\217_\321\202\320\260_\320\276\321\202\321\200\320\270\320\274\320\260\320\275\320\275\321\217_\320\264\320\276\320\277\320\276\320\274\320\276\320\263\320\270/index.html" @@ -0,0 +1,315 @@ +--- +title: Навчання та отримання допомоги +slug: Learn/Навчання_та_отримання_допомоги +translation_of: Learn/Learning_and_getting_help +--- +

{{learnsidebar}}

+ +

It is great that you are putting some time into learning a new set of skills, but there are good practices to employ that will make your learning more effective. There are also are times when you'll get stuck and feel frustrated — even professional web developers feel like this regularly — and it pays to know about the most effective ways to try and get help so you can progress in your work. This article provides some hints and tips in both of these areas that will help you get more out of learning web development, as well as further reading so you can find out more information about each sub-topic should you wish..

+ +

Effective learning

+ +

Let's move straight on and think about effective learning.

+ +

Different learning methods

+ +

It is interesting to consider that there are two main ways in which your brain learns things — focused and diffuse learning:

+ + + +

From the studies that neuroscientists have done on brain activity, we have found out that you can't really engage in both ways of learning — or thinking — at once. So which one should you choose? You might think that focused learning is better for studying, but in reality, both are very important.

+ +

Focused thinking is great for concentrating hard on specific subjects, getting into deep problem solving, and improving your mastery of the techniques required — strengthening the neural pathways in your brain where that information is stored. It isn't however very good at getting an understanding of "the big picture", and unlocking new neural pathways when you are trying to understand new subjects or solve new problems that you haven't come across before. 

+ +

For that, you need diffuse thinking. This is the opposite of focus — you let your brain wander around the wider landscape, searching around for connections you didn't have before, touching on new things (or new combinations of things) that you can then focus on later, to strengthen them and start to really understand what they mean.

+ +

This is why it is usually good to read some introductory material first to get a high-level understanding of an area before you leap into the specific details.

+ +

It is also why you can sometimes get really stuck on a problem, but then figure out the answer when you go for a coffee break (or a walk). You might:

+ +
    +
  1. Know how to fix problem A with tool A.
  2. +
  3. Know how to fix problem B with tool B.
  4. +
  5. Not know how to fix problem C.
  6. +
+ +

Let's say you focus on problem C for a while and get frustrated because you can't think how to solve it. But then after going on a walk to get some fresh air, you may well find that as your mind wanders, you suddenly make a connection between tool A and tool B, and realize that you can use them together to fix problem C! It isn't always this simple, but it is also surprising how many times this does happen. This also highlights the importance of taking regular breaks when you are studying in front of the computer.

+ +

Different learning materials

+ +

It is also worth looking at the different types of learning materials that are available, to see which ones are most effective for you to learn with.

+ +

Textual articles

+ +

You'll find a lot of written articles on the web to teach you about web design. Like most of this course, for example. Some of the articles will be tutorials, to teach you a certain technique or important concept (such as "learn how to create a video player" or "Learn the CSS box model"), and some of the articles will be reference material, to allow you to look up details you may have forgotten (such as "what is the syntax of the CSS background property"?)

+ +

MDN Web Docs is very good for both types — the area you are currently in is great for learning techniques and concepts, and we also have several giant reference sections allowing you to look up any syntax you can't remember.

+ +

There are also several other great resources on the web, some of which we'll mention below.

+ +
+

Note: The above text should have given you an important fact — you aren't expected to remember everything! Professional web developers use tools like MDN Web Docs to look up things they have forgotten all the time. As you'll discover, learning web development is more about problem-solving and learning patterns than it is about learning lots of syntaxes.

+
+ +

Videos

+ +

There are also a number of sites that have video learning content on them. YouTube is an obvious one, with channels such as Mozilla Layout Land, MozillaDeveloper, and Google ChromeDevelopers providing many useful videos. Many people prefer textual articles for more in-depth learning and reference material, and videos for quick explanations of concepts and new features, but it is really up to you what you prefer to learn from. There is no right and wrong answer here.

+ +

Interactive code playgrounds

+ +

You might be the kind of person that prefers minimal instructions and would prefer to jump straight in and start playing with code. This is also a reasonable approach, and some learning sites tend to favor it. Codecademy for example is a learning site where the tutorials mainly consist of interactive code editors where you have to directly write code and see if the desired result was achieved.

+ +

Many MDN Web docs reference pages provide interactive examples too, where you can alter the code and see how the live result changes. And there is also nothing wrong with creating your own code examples on your computer, or in an online code editor like JSBin, Codepen, or Glitch. In fact, you'll be called to do so as part of this course when you are learning!

+ +
+

Note: Online code editors are also really useful for sharing code you've written, for example, if you are collaborating on learning with someone else who isn't in the same location, or are sending it someone to ask for help with it. You can share the web address of the example with them so they can see it.

+
+ +
+

Note: You might favor one learning method over the others, but realistically a hybrid approach is probably what you will end up with. And you'll probably come up with other methods than the three we covered above.

+
+ +

Making a plan

+ +

It is a good idea to create a plan to help you achieve what you want to achieve through your learning.

+ +

A goal statement

+ +

It sounds silly, but why not start with a single sentence that says what you want to achieve? The following have different scopes, but are all realistic and achievable:

+ + + +

The following are not quite as reasonable:

+ + + +

What do you need to get there?

+ +

Once you've worked out your goal, it is a good idea to research what you'll need to achieve the goal. For example:

+ +

Materials I need:

+ + + +

Knowledge I need:

+ + + +

How much time and money will it take?

+ +

Estimate the time and cost of getting these things. If you'll need to work to earn money to buy the materials required, then the time to do that will have to be factored in. Once you have a time estimate, you can start to build a plan around your life.

+ +

How many hours per week do I need to do?

+ +

Once you know what you need to do, and how long you think it'll take you, you can start writing out a plan to follow, to achieve your goal. It can be as simple as:

+ +

"It'll take me 500 hours to learn what I need to know, and I have a year to do it, so if I assume 2 weeks' holiday I'll need to do work on this for 10 hours per week. I am free on evenings and weekends, so I'll plan my time around those."

+ +

How much time you can spend on this of course depends on what your circumstances are. If you are at school, then you've got way more free time than if you have a job and children to provide for. It is still possible to achieve your goals, but you have to be realistic about how quickly you can do it.

+ +

If you are doing a university or college course to learn web development, then most of this planning is done for you — lucky you!

+ +

When you have worked out a weekly schedule, then you should keep a record of what you manage to do each week in a simple spreadsheet or even in a notebook!

+ +

Also, it might be a good idea to have some sub-goals worked out to allow you to keep track of where you are more easily, for example:

+ + + +

Keep thinking about how much progress you are making, and adjust your plan if needs be.

+ +

Staying motivated

+ +

It is hard to stay motivated, especially if you are trying to learn a complex skill like programming or web development. What follows are some tips to stay motivated and keep working:

+ + + +

Effective problem solving

+ +

There is no one effective way to solve all problems (and learn all things) associated with web design and development, but there are some general bits of advice that will serve you well in most cases.

+ +

Break things down into chunks

+ +

For a start, when you are trying to implement something specific and it seems really hard to get your head around, you should try to break it down into multiple smaller problems, or chunks.

+ +

For example, if you are looking at a task of "Build a simple two-column website", you could break it down as follows:

+ + + +

Then you could break it down further, for example, "Implement horizontal navigation menu" could be written out as:

+ + + +

Each of these problems doesn't seem nearly as difficult to solve as the one big problem you had initially. Now you've just got to go through and solve them all!

+ +

Learn and recognise the patterns

+ +

As we said before, web design/programming is mostly about problem solving and patterns. Once you have written out what you'll need to do to solve a specific problem, you can start to figure out what technology features to use to solve it. For example, professional web developers have created lots of horizontal navigation menus, so they'll immediately start thinking of a solution like this:

+ +

A nav menu is usually created from a list of links, something like:

+ +
<ul>
+  <li>First menu item</li>
+  <li>Second menu item</li>
+  <li>Third menu item</li>
+  <li>etc.</li>
+</ul>
+
+ +

To make all the items sit horizontally on a line, the easiest modern way is to use flexbox:

+ +
ul {
+  display: flex;
+}
+ +

To remove unneeded spacing and bullet points, we can do this:

+ +
ul {
+  list-style-type: none;
+  padding: 0;
+}
+ +

etc.

+ +

If you are a complete beginner to web development, you'll have to do some study and web searches and lookup solutions to such problems. If you are a professional web developer you'll probably remember the last time you solved a similar problem, and only have to look up a few bits of the syntax that you forgot since then.

+ +

When you find solutions to such problems, it is worth writing down notes on what you did, and keeping some minimal code examples in a directory somewhere so you can look back on previous work.

+ +

In addition, the web has developer tools that allow you to look at the code used to build any site on the web — if you don't have a solution to hand, one good research method is to find websites with similar features in the wild, and find out how they did it.

+ +
+

Note: Notice how above we talked about the problem we are trying to solve first, and the technology used to solve it second. This is pretty much always the best way round to do it — don't start with a cool new technology that you want to use, and try to shoehorn it into the use case.

+
+ +
+

Note: The simplest solution is often the best.

+
+ +

Getting practice

+ +

The more you practice solving a problem, the stronger your brain's neural pathways are in that area, and the easier it becomes to recall the details and the logic of that particular problem.

+ +

Keep tinkering with code, and getting more practice. If you run out of problems to solve, look up some tests online, do some more courses, or ask your friends and family (or local school or church) if there is anything they'd like you to build for them.

+ +

Getting help

+ +

Web development requires you to learn a complex set of skills — you are bound to get stuck sometimes and need help. As we said before, even professional developers need regular help working out issues.

+ +

There are a variety of ways to get help, and what follows are some tips for doing so more effectively.

+ +

Effective web searches

+ +

One important skill to learn is the art of effective web searches — what search terms do you need to use in your favorite search engine to find the articles you need? 

+ +

It is often fairly obvious what to search for. For example:

+ + + +

If you want to search for something that has less obvious buzzwords, you need to think about what is most likely to return what you want.

+ + + +

Error messages

+ +

If you are having a problem with some code and a specific error message is coming up, it is often a good idea to just copy the error message into your search engine and use it as the search term. If other people have had the same problem, there'll likely be some articles or blog posts about it in places like MDN or Stack Overflow.

+ +
+

Note: Stack Overflow is a really useful website — it is basically a huge database of curated questions and answers on various technologies and related techniques. You'll probably find an answer that answers your question. If not, you can ask a question and see if anyone can help you.

+
+ +

Browser testing

+ +

It is often a good idea to see if your problem is affecting all browsers, or whether it only occurs in one or a small number of browsers. If it is only affecting one browser, for example, you can use that browser to narrow down the search. Example searches might look like:

+ + + +

Using MDN

+ +

The site you are already on has a wealth of information available to you — both reference material for looking up code syntax, and guides/tutorials for learning techniques.

+ +

We've provided most of the answers to the questions you'll have about web development fundamentals in this part of MDN. If you are stuck, then it is good to re-read the associated articles to see if you missed anything.

+ +

If you are not sure which article to read, then try searching MDN for some related keywords (as indicated above), or try a general web search. To search on MDN, you can either use the site's in-built search functionality or better still, use your favorite search engine and put "mdn" in front of the search term, for example, "mdn responsive web design" or "mdn background-color".

+ +

Other online resources

+ +

We already mentioned Stack Overflow, but there are other online resources that can help.

+ +

It is good to find a community to be part of, and you'll get a lot of respect if you try to help others answer their questions as well as asking your own. Other good examples include:

+ + + +

However, it also makes sense to find useful groups on social networking sites such as Twitter or Facebook. Look for groups that discuss web development subjects you are interested in, and join up. Follow people on twitter you know are influential, smart, or just plain seem to share lots of useful tips.

+ +

Physical meetups

+ +

Lastly, you should try attending some physical meetups to meet other like-minded people, especially ones that cater to beginners. meetup.com is a good place to find local physical meetups, and you could also try your local press/what's on sites.

+ +

You could also try attending full-fledged web conferences. While these can be expensive, you could try volunteering at them, and many conferences offer reduced rate tickets, for example, student or diversity tickets.

+ +

See also

+ + diff --git "a/files/uk/learn/\321\204\321\200\320\276\320\275\321\202-\320\265\320\275\320\264_\320\262\320\265\320\261-\321\200\320\276\320\267\321\200\320\276\320\261\320\275\320\270\320\272/index.html" "b/files/uk/learn/\321\204\321\200\320\276\320\275\321\202-\320\265\320\275\320\264_\320\262\320\265\320\261-\321\200\320\276\320\267\321\200\320\276\320\261\320\275\320\270\320\272/index.html" new file mode 100644 index 0000000000..c90cae476e --- /dev/null +++ "b/files/uk/learn/\321\204\321\200\320\276\320\275\321\202-\320\265\320\275\320\264_\320\262\320\265\320\261-\321\200\320\276\320\267\321\200\320\276\320\261\320\275\320\270\320\272/index.html" @@ -0,0 +1,202 @@ +--- +title: Фронтенд веб-розробник +slug: Learn/Фронт-енд_веб-розробник +tags: + - CSS + - Front-end + - HTML + - JavaScript + - Web Standarts + - Інструментарій + - Навчання + - Початківець + - Стандарти + - Фронт-енд + - Фронтенд + - інструменти +translation_of: Learn/Front-end_web_developer +--- +

{{learnsidebar}}

+ +

Ласкаво просимо до нашого навчального шляху веб-розробника!

+ +

Ми представяємо вам структурований курс, який навчить вас усьому, що вам потрібно знати, аби стати передовим веб-розробником. Просто працюйте над кожним розділом, опановуючи нові або вдосконалюючи існуючі навички, рухаючись далі. Кожен розділ містить практичні завдання та оцінювання, щоб перевірити своє розуміння, перш ніж рухатися вперед.

+ +

Охоплена тематика

+ +

Досліджувані теми:

+ + + +

Ви можете працювати з розділами по порядку, проте кожен з них також є самостійним. Наприклад, якщо ви вже знаєте HTML, ви можете перейти до розділу CSS.

+ +

Передумови

+ +

Щоб почати цей курс, вам не потрібні попередні знання. Все, що вам потрібно, це комп’ютер, що може працювати із сучасними веб-браузерами, підключення до Інтернету та готовність вчитися.

+ +

Якщо ви не впевнені, що фронтенд веб-розробка вам підходить та/чи ви хочете більш поступове ознайомлення перед початком довгого та повного курсу, спершу опрацюйте наш модуль Початок роботи з Інтернетом.

+ +

Отримання допомоги

+ +

Ми намагалися зробити навчання фронт-енд веб-розробці якомога комфортним, але ви, ймовірно, все ж таки десь застрягнете, тому що чогось не розумієте або якийсь код просто не працює.

+ +

Не панікуйте. Ми всі застрягаємо, не зважаючи на те - ми початківці чи ми професійні веб-розробники. Стаття Навчання та отримання допомоги пропонує вам низку порад щодо пошуку інформації та надання допомоги самому собі. Якщо ви все ще не зрушили з мертвої точки, сміливо розміщуйте питання на нашому Дискурсному форумі.

+ +

Нумо починати. Щасти!

+ +

Шлях навчання

+ +

Початок

+ +

Час на виконання: 1,5–2 години

+ +

Передумови

+ +

Нічого, крім базової комп'ютерної грамотності.

+ +

Як мені дізнатися, що я можу рухатися далі?

+ +

В цій частині курсу немає оцінювання, проте не пропускайте її. Важливо, щоб ви налаштувались і були готові виконувати практичні завдання пізніше в процесі.

+ +

Посібники

+ + + +

Семантика та структура за допомогою HTML

+ +

Час на виконання: 35–50 годин

+ +

Передумови

+ +

Нічого, крім базової комп'ютерної грамотності та базового середовища для веб-розробки.

+ +

Як мені дізнатися, що я можу рухатися далі?

+ +

Оцінювання в кожному модулі розроблено для перевірки вашого знання теми. Вдалий результат оцінювання підтверджує, що ви готові перейти до наступного модуля.

+ +

Модулі

+ + + +

Стилізація та розмітка за допомогою CSS

+ +

Час на виконання: 90–120 гоодин

+ +

Передумови

+ +

Перед початком вивчення CSS рекомендується мати базові знання з HTML. Спершу слід вивчити Вступ до HTML.

+ +

Як мені дізнатися, що я можу рухатися далі?

+ +

Оцінювання в кожному модулі розроблено для перевірки вашого знання теми. Вдалий результат оцінювання підтверджує, що ви готові перейти до наступного модуля.

+ +

Модулі

+ + + +

Додаткові ресурси

+ + + +

Інтерактивність за допомогою JavaScript

+ +

Час на виконання: 135–185 годин

+ +

Передумови

+ +

Перед початком вивчення JavaScript рекомендується мати базові знання з HTML. Спершу слід вивчити Вступ до HTML.

+ +

Як мені дізнатися, що я можу рухатися далі?

+ +

Оцінювання в кожному модулі розроблено для перевірки вашого знання теми. Вдалий результат оцінювання підтверджує, що ви готові перейти до наступного модуля.

+ +

Модулі

+ + + +

Веб-форми — Робота з даними користувача

+ +

Час на виконання: 40–50 годин

+ +

Передумови

+ +

Вивчення форм вимагає знання з HTML, CSS та JavaScript. Враховуючи складність роботи з формами, це спеціальна тема.

+ +

Як мені дізнатися, що я можу рухатися далі?

+ +

Оцінювання в кожному модулі розроблено для перевірки вашого знання теми. Вдалий результат оцінювання підтверджує, що ви готові перейти до наступного модуля.

+ +

Модулі

+ + + +

Роблячи Інтернет доступним для кожного

+ +

Час на виконання: 60–75 годин

+ +

Передумови

+ +

Перед роботою з цим розділом було б незайвим знати HTML, CSS та JavaScript. Багато методів та найкращих практик стосуються декількох технологій.

+ +

Як мені дізнатися, що я можу рухатися далі?

+ +

Оцінювання в кожному модулі розроблено для перевірки вашого знання теми. Вдалий результат оцінювання підтверджує, що ви готові перейти до наступного модуля.

+ +

Модулі

+ + + +

Сучасний інструментарій

+ +

Час на виконання: 55–90 годин

+ +

Передумови

+ +

Перед роботою з цим розділом було б незайвим знати HTML, CSS та JavaScript, оскільки інструменти, що тут обговорюються, працюють вкупі із багатьма з цих технологій.

+ +

Як мені дізнатися, що я можу рухатися далі?

+ +

У цьому наборі модулів немає конкретних статей з оцінюванням. Навчальні посібники з прикладами в кінці другого та третього модулів готують вас до розуміння основ сучасного інструментарію.

+ +

Модулі

+ + -- cgit v1.2.3-54-g00ecf