chore(i18n,curriculum): processed translations - new ukrainian (#44447)

This commit is contained in:
camperbot
2021-12-10 11:14:24 +05:30
committed by GitHub
parent 8651ee1797
commit 0473dedf47
1663 changed files with 156692 additions and 1 deletions

View File

@ -0,0 +1,167 @@
---
id: 587d7fae367417b2b2512be4
title: Доступ до даних JSON із API
challengeType: 6
forumTopicId: 301499
dashedName: access-the-json-data-from-an-api
---
# --description--
У попередньому завданні ви дізнались як отримати дані JSON з freeCodeCamp Cat Photo API.
Тепер зверніть увагу на отримані дані, щоб краще зрозуміти формат JSON. Згадайте деякі позначення в JavaScript:
<blockquote>[ ] -> Квадрантні дужки позначають масив<br>{ } -> Фігурні дужки позначають об'єкт<br>" " -> Подвійні лапки позначають рядок. Їх також використовують для назв ключів у форматі JSON</blockquote>
Розуміти структуру даних з API важливо, адже це впливає на спосіб отримання бажаних значень.
Справа натисніть кнопку `Get Message`, щоб перетворити формат freeCodeCamp Cat Photo API JSON у HTML.
Першим та останнім символом у даних формату JSON ставляться квадратні дужки `[ ]`. Це означає, що отримані дані - масив. Фігурна дужка `{` у даних JSON стоїть другою та починає опис об'єкта. Зверніть увагу, що тут три окремі об'єкти. Дані JSON - це масив з трьох об'єктів, кожен із яких містить інформацію про фото котів.
Ви вже вивчили, що об'єкти мають пари "ключ-значення", розділені комами. Наприклад, перший об'єкт Cat Photo`"id":0` має ключ `id` та відповідне значення `0`. Аналогічні ключі використовують для `imageLink`, `altText` та `codeNames`. Кожне фото - об'єкт з однаковими ключами, але з різними значеннями.
Інша цікава пара '"ключ-значення" в першому об'єкті - це `"codeNames":["Juggernaut","Mrs. Wallace","ButterCup"]`. `codeNames` - це ключ, значення якого - масив із трьох рядків. Можна мати не лише масив об'єктів, а й ключ з масивом як значення.
Пам'ятайте як отримувати доступ до даних у масивах та об'єктах. Для доступу до певного індексу елемента масиви використовують дужкову нотацію. Об'єкти використовують дужку або крапкову нотацію, щоб отримати доступ до змінних властивостей. Ось приклад, що показує властивість `altText` першого фото кота. Зверніть увагу, що аналізовані дані JSON в редакторі зберігаються змінною з назвою `json`:
```js
console.log(json[0].altText);
```
Консоль буде відображати рядок `A біла кішка в зеленому шоломі у формі дині на голові. `.
# --instructions--
Вивести на консоль друге значення в масиві `codeNames` для кішки з `id` 2. Щоб отримати доступ до масиву, використайте дужкову та крапкову нотацію об'єкта (що зберігається у змінній `json`).
# --hints--
У коді має бути використана дужкова та крапкова нотація для правильного імені та виведення `Loki` на консоль.
```js
assert(
code.match(
/console\s*\.\s*log\s*\(\s*json\s*\[2\]\s*(\.\s*codeNames|\[\s*('|`|")codeNames\2\s*\])\s*\[\s*1\s*\]\s*\)/g
)
);
```
# --seed--
## --seed-contents--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('getMessage').onclick = function(){
const req = new XMLHttpRequest();
req.open("GET",'/json/cats.json', true);
req.send();
req.onload=function(){
const json = JSON.parse(req.responseText);
document.getElementsByClassName('message')[0].innerHTML = JSON.stringify(json);
// Add your code below this line
// Add your code above this line
};
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```
# --solutions--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('getMessage').onclick = function(){
const req = new XMLHttpRequest();
req.open("GET",'/json/cats.json', true);
req.send();
req.onload=function(){
const json = JSON.parse(req.responseText);
document.getElementsByClassName('message')[0].innerHTML = JSON.stringify(json);
// Add your code below this line
console.log(json[2].codeNames[1]);
// Add your code above this line
};
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```

View File

@ -0,0 +1,140 @@
---
id: 587d7fad367417b2b2512be2
title: Зміна тексту кліком "Events"
challengeType: 6
forumTopicId: 301500
dashedName: change-text-with-click-events
---
# --description--
Кліком ви можете оновити елемент HTML за допомогою JavaScript.
Наприклад, коли користувач натискає кнопку `Get Message`, текст елемента класу `message` змінюється на `Here is the message`.
Так кліком можна змінити код:
```js
document.getElementsByClassName('message')[0].textContent="Here is the message";
```
# --instructions--
Додайте код `onclick` обробника подій, щоб змінити текст в елементі `message` на `Here is the message`.
# --hints--
Використайте у коді метод `document.getElementsByClassName`, щоб вибрати елемент класу `message` та додати `textContent` у заданий рядок.
```js
assert(
code.match(
/document\s*\.getElementsByClassName\(\s*?('|")message\1\s*?\)\[0\]\s*\.textContent\s*?=\s*?('|")Here is the message\2/g
)
);
```
# --seed--
## --seed-contents--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('getMessage').onclick = function(){
// Add your code below this line
// Add your code above this line
}
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```
# --solutions--
```html
<script>
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick = function(){
// Add your code below this line
document.getElementsByClassName('message')[0].textContent = "Here is the message";
// Add your code above this line
}
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```

View File

@ -0,0 +1,199 @@
---
id: 587d7fae367417b2b2512be5
title: Перетворення даних JSON у HTML
challengeType: 6
forumTopicId: 16807
dashedName: convert-json-data-to-html
---
# --description--
Дані, отримані з JSON API, ви можете відобразити у форматі HTML.
Використайте метод `forEach` для повторного перегляду даних, оскільки фото котів зберігаються в масиві. Ви можете змінити елементи HTML кожного об'єкта.
Спершу, створіть змінну html `let html = "";`.
Потім додайте HTML до змінної, яку повинні обрамляти ключові назви у `strong` теґах, а далі має йти значення. Так буде задано цикл даним JSON. Після завершення циклу - відтворіть його.
Ось приклад такого коду:
```js
let html = "";
json.forEach(function(val) {
const keys = Object.keys(val);
html += "<div class = 'cat'>";
keys.forEach(function(key) {
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
});
html += "</div><br>";
});
```
**Примітка:** Для цього завдання вам потрібно додати на сторінку новий елемент HTML, але не використовуйте `textContent`. Натомість використайте `innerHTML`. Проте сайт може стати вразливим до атак міжсайтового скриптингу.
# --instructions--
Методом `forEach` додайте цикл даних JSON та створіть елементи HTML для їх відображення.
Ось декілька прикладів JSON:
```json
[
{
"id":0,
"imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
"altText":"A white cat wearing a green helmet shaped melon on its head. ",
"codeNames":[ "Juggernaut", "Mrs. Wallace", "Buttercup"
]
}
]
```
# --hints--
Ваш код повинен зберігати дані змінної `html`
```js
assert(__helpers.removeWhiteSpace(code).match(/html(\+=|=html\+)/g))
```
У коді потрібно використати метод `forEach` для додавання циклу даних JSON з API.
```js
assert(code.match(/json\.forEach/g));
```
У вашому коді назви ключів мають бути обрамлені у `strong` теґи.
```js
assert(code.match(/<strong>.+<\/strong>/g));
```
# --seed--
## --seed-contents--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('getMessage').onclick = function(){
const req = new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload = function(){
const json = JSON.parse(req.responseText);
let html = "";
// Add your code below this line
// Add your code above this line
document.getElementsByClassName('message')[0].innerHTML = html;
};
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```
# --solutions--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('getMessage').onclick = function(){
const req = new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload = function(){
const json = JSON.parse(req.responseText);
let html = "";
// Add your code below this line
json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'cat'>";
keys.forEach(function(key) {
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
});
html += "</div><br>";
});
// Add your code above this line
document.getElementsByClassName('message')[0].innerHTML = html;
};
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```

View File

@ -0,0 +1,98 @@
---
id: 587d7faf367417b2b2512be8
title: Отримання даних геолокації для знаходження GPS-координат користувача
challengeType: 6
forumTopicId: 18188
dashedName: get-geolocation-data-to-find-a-users-gps-coordinates
---
# --description--
Інша зручна річ - доступ до поточної локації користувача. У кожен браузер вбудовано навігацію, яка надасть цю інформацію.
Навігація надає доступ до актуальної широти та довготи користувача.
Вам надійде запит на дозвіл або блокування доступу сайту до вашої локації. Завдання можна завершити будь-яким способом, якщо код буде правильним.
Якщо ви надасте доступ, побачите текст на телефоні виводу для зміни широти та довготи.
Ось такий код:
```js
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById('data').innerHTML="latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude;
});
}
```
Спочатку перевіряється чи існує об'єкт `navigator.geolocation`. Якщо так, то для об'єкта методом `getCurrentPosition` буде асинхронно надіслано запит на локацію користувача. Якщо запит успішний, функція зворотного виклику під час роботи методу спрацює. Ця функція передає значення `position` об'єкта для широти і довготи за допомогою крапкової нотації і оновлює HTML.
# --instructions--
Додайте приклад коду у теґи `script`, щоб дізнатись поточне розташування користувача і вставити його у HTML.
# --hints--
Щоб дізнатись поточне місце розташування користувача, використайте `navigator.geolocation`.
```js
assert(code.match(/navigator\.geolocation\.getCurrentPosition/g));
```
Щоб відобразити координату широти місця знаходження користувача, використайте `position.coords.latitude`.
```js
assert(code.match(/position\.coords\.latitude/g));
```
Щоб відобразити координату довготи місця знаходження користувача, використайте `position.coords.longitude`.
```js
assert(code.match(/position\.coords\.longitude/g));
```
Положення користувача покажіть елементом `id="data"` всередині `div`.
```js
assert(
code.match(/document\.getElementById\(\s*?('|")data\1\s*?\)\.innerHTML/g)
);
```
# --seed--
## --seed-contents--
```html
<script>
// Add your code below this line
// Add your code above this line
</script>
<h4>You are here:</h4>
<div id="data">
</div>
```
# --solutions--
```html
<script>
// Add your code below this line
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById('data').innerHTML = "latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude;
});
}
// Add your code above this line
</script>
<h4>You are here:</h4>
<div id="data">
</div>
</section>
```

View File

@ -0,0 +1,174 @@
---
id: 5ccfad82bb2dc6c965a848e5
title: Отримання JSON fetch-методом JavaScript
challengeType: 6
forumTopicId: 301501
dashedName: get-json-with-the-javascript-fetch-method
---
# --description--
Щоб зробити запит зовнішніх даних використовуйте метод `fetch()`. Він еквівалентний методу `XMLHttpRequest`, проте синтаксис вважається простішим.
Ось код для створення запиту GET для `/json/cats.json`
```js
fetch('/json/cats.json')
.then(response => response.json())
.then(data => {
document.getElementById('message').innerHTML = JSON.stringify(data);
})
```
Зверніть увагу на кожен фрагмент коду.
Запит надсилає саме перший рядок. Так `fetch(URL)` робить запит `GET` на конкретну URL-адресу. Так створюється Promise.
Після створення Promise та успішного запиту, методом `then` код адаптується та перетворюється у формат JSON.
Метод `then` також створює Promise, що так само проходить обробку наступним `then` методом. Аргумент у другому `then` і є об'єктом JSON, який вам потрібен!
Тепер цим методом обирається елемент, який отримає дані за допомогою `document.getElementById()`. Далі код HTML елемента змінюється через додавання рядка з об'єктом JSON, поверненим за запитом.
# --instructions--
Щоб створити та надіслати запит `GET` до freeCodeCamp Cat Photo API, оновіть код. Використайте цього разу метод `fetch` замість `XMLHttpRequest`.
# --hints--
Щоб надіслати запит `GET`, використовуйте метод `fetch`.
```js
assert(code.match(/fetch\s*\(\s*('|")\/json\/cats\.json\1\s*\)/g));
```
Щоб конвертувати вхідні дані в JSON, використовуйте метод `then`.
```js
assert(
code.match(
/\.then\s*\(\s*\(?(?<var>\w+)\)?\s*=>\s*\k<var>\s*\.json\s*\(\s*\)\s*\)/g
)
);
```
Щоб обробити конвертовані дані JSON методом `then`, використайте `then` у коді двічі.
```js
assert(__helpers.removeWhiteSpace(code).match(/\.then\(\(?\w+\)?=>{[^}]*}\)/g));
```
Щоб змінити внутрішній HTML на рядок з даними JSON, використовуйте у коді елемент з id `message`.
```js
assert(
__helpers.removeWhiteSpace(code).match(
/document\.getElementById\(('|")message\1\)\.innerHTML=JSON\.stringify\(?\w+\)/g
)
);
```
# --seed--
## --seed-contents--
```html
<script>
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick= () => {
// Add your code below this line
// Add your code above this line
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p id="message" class="box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```
# --solutions--
```html
<script>
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick= () => {
fetch('/json/cats.json')
.then(response => response.json())
.then(data => {
document.getElementById('message').innerHTML=JSON.stringify(data);
})
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p id="message" class="box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```

View File

@ -0,0 +1,196 @@
---
id: 587d7fae367417b2b2512be3
title: Отримання JSON методом JavaScript XMLHttpRequest
challengeType: 6
forumTopicId: 301502
dashedName: get-json-with-the-javascript-xmlhttprequest-method
---
# --description--
Ви можете надсилати запит на дані із зовнішніх джерел. Саме тут використовуються API.
Пам'ятайте, що API (або ППІ - прикладний програмний інтерфейс) - це інструменти, що дозволяють комп'ютерам обмінюватись інформацією один з одним. Ви дізнаєтесь, як оновити HTML та дані з API за допомогою технології AJAX.
Більшість веб-API передають дані у форматі JSON. JSON - це JavaScript Object Notation.
Синтаксис JSON схожий на літеральну нотацію об'єкта в JavaScript. У JSON властивості об'єкта та їх поточні значення обрамлені `{` та `}`.
Ці властивості разом зі значеннями часто називаються парами "ключ-значення".
Ваша програма отримає дані JSON через API як `string`, хоча вони надіслані у форматі `bytes`. За замовчуванням дані надсилаються не у форматі JavaScript, проте їх можна конвертувати. Методом `JSON.parse` аналізується рядок та створюється потрібний об'єкт JavaScript.
Запросіть JSON через freeCodeCamp's Cat Photo API. Додайте цей код до кліку для виконання запиту:
```js
const req = new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload = function(){
const json = JSON.parse(req.responseText);
document.getElementsByClassName('message')[0].innerHTML = JSON.stringify(json);
};
```
Зверніть увагу на кожний елемент коду. Об'єкт JavaScript `XMLHttpRequest` має певні властивості та методи для передачі даних. Спочатку створюють об'єкт `XMLHttpRequest` та зберігають у змінній `req`. Потім методом `open` надсилають запит `GET`, адже йде отримання даних з API. URL-адреса API, з якого ви зробили запит даних, є другим аргументом для `open`. Третій аргумент - логічне значення, яке надсилає асинхронний запит за допомогою `true`. Сам запит надсилають методом `send`. Врешті-решт, обробник події `onload` аналізує отримані дані та перетворює об'єкт JavaScript методом `JSON.stringify` у рядок. Далі цей рядок буде вставлено як текст повідомлення.
# --instructions--
Щоб створити та надіслати запит `GET` до freeCodeCamp Cat Photo API, оновіть код. Далі натисніть кнопку `Get Message`. Тест `The message will go here` буде замінено даними з API формату raw JSON за допомогою функції AJAX.
# --hints--
Створіть новий `XMLHttpRequest` у коді.
```js
assert(code.match(/new\s+?XMLHttpRequest\(\s*?\)/g));
```
Щоб створити запит `GET` для freeCodeCamp Cat Photo API, використайте метод `open`.
```js
assert(
code.match(
/\.open\(\s*?('|")GET\1\s*?,\s*?('|")\/json\/cats\.json\2\s*?,\s*?true\s*?\)/g
)
);
```
Щоб відправити запит, використайте метод `send`.
```js
assert(code.match(/\.send\(\s*\)/g));
```
Для того, щоб код працював, вам потрібен сет обробника подій `onload`.
```js
assert(
code.match(/\.onload\s*=\s*(function|\(\s*?\))\s*?(\(\s*?\)|\=\>)\s*?{/g)
);
```
Щоб зробити аналіз `responseText`, використайте метод `JSON.parse`.
```js
assert(code.match(/JSON\s*\.parse\(\s*.*\.responseText\s*\)/g));
```
Щоб змінити внутрішній HTML на рядок з даними JSON, використайте у коді елемент класу `message`.
```js
assert(
code.match(
/document\s*\.getElementsByClassName\(\s*?('|")message\1\s*?\)\[0\]\s*\.innerHTML\s*?=\s*?JSON\.stringify\(.+?\)/g
)
);
```
# --seed--
## --seed-contents--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('getMessage').onclick = function(){
// Add your code below this line
// Add your code above this line
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```
# --solutions--
```html
<script>
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick = function(){
const req = new XMLHttpRequest();
req.open('GET', '/json/cats.json', true);
req.send();
req.onload = () => {
const json = JSON.parse(req.responseText);
document.getElementsByClassName('message')[0].innerHTML = JSON.stringify(json);
};
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```

View File

@ -0,0 +1,140 @@
---
id: 587d7fad367417b2b2512be1
title: Обробка кліків за допомогою JavaScript функцією onclick
challengeType: 6
forumTopicId: 301503
dashedName: handle-click-events-with-javascript-using-the-onclick-property
---
# --description--
Вам потрібно, щоб код виконувався лише після завантаження сторінки. Для цього прикріпіть event JavaScript до `DOMContentLoaded` документу. Ось приклад такого коду:
```js
document.addEventListener('DOMContentLoaded', function() {
});
```
Ви можете вставити обробники подій у функцію `DOMContentLoaded`. За допомогою такого коду використайте обробник подій `onclick`, що запускається під час кліку користувача на елемент з id `getMessage`:
```js
document.getElementById('getMessage').onclick = function(){};
```
# --instructions--
Додайте обробник подій кліку до функції `DOMContentLoaded` для елементу з id `getMessage`.
# --hints--
Щоб обрати елемент `getMessage`, використайте у коді метод `document.getElementById`.
```js
assert(code.match(/document\s*\.getElementById\(\s*?('|")getMessage\1\s*?\)/g));
```
Додайте до коду обробник подій `onclick`.
```js
assert(typeof document.getElementById('getMessage').onclick === 'function');
```
# --seed--
## --seed-contents--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
// Add your code below this line
// Add your code above this line
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```
# --solutions--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
// Add your code below this line
document.getElementById('getMessage').onclick = function(){ };
// Add your code above this line
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```

View File

@ -0,0 +1,206 @@
---
id: 587d7faf367417b2b2512be9
title: Надсилання даних методом JavaScript XMLHttpRequest
challengeType: 6
forumTopicId: 301504
dashedName: post-data-with-the-javascript-xmlhttprequest-method
---
# --description--
У попередніх прикладах, ви отримували дані із зовнішнього ресурсу. Проте ви також можете надсилати дані на зовнішній ресурс, допоки він підтримує запити AJAX та вам відома URL-адреса.
Метод JavaScript's `XMLHttpRequest` використовують для надсилання даних на сервер. Наприклад:
```js
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 201){
const serverResponse = JSON.parse(xhr.response);
document.getElementsByClassName('message')[0].textContent = serverResponse.userName + serverResponse.suffix;
}
};
const body = JSON.stringify({ userName: userName, suffix: ' loves cats!' });
xhr.send(body);
```
Вам вже зустрічались ці методи. Ось метод `open`, який надсилає запит `POST` на URL-адресу зовнішнього ресурсу та робить його асинхронним за допомогою булевого `true`. Метод `setRequestHeader` встановлює значення заголовка запиту HTTP, в якому присутня інформація про відправника та сам запит. Використовуйте цей метод після `open`, але перед `send`. Два параметри - це назва заголовка і значення, що задається як тіло цього заголовка. Далі, за допомогою слухача подій `onreadystatechange`, змінюється стан запиту. `readyState` з `4` означає завершення операції, а `status` з `201` - успішно виконаний запит. HTML документа можна оновити. І нарешті, метод `send` надсилає запит для значення `body`. Ключ `userName` надає користувач у полі `input`.
# --instructions--
Оновіть код, щоб надіслати запит `POST` до кінцевої точки API. Потім напишіть своє ім'я у полі вводу та натисніть кнопку `Send Message`. Функція AJAX замінить `Reply from Server will be here.` даними із сервера. Додайте до вашого імені у полі вводу текст `loves cats`.
# --hints--
Створіть новий `XMLHttpRequest` у коді.
```js
assert(code.match(/new\s+?XMLHttpRequest\(\s*?\)/g));
```
Щоб створити запит `POST` на сервер, використайте метод `open`.
```js
assert(code.match(/\.open\(\s*?('|")POST\1\s*?,\s*?url\s*?,\s*?true\s*?\)/g));
```
Використовуйте метод `setRequestHeader` у коді.
```js
assert(
code.match(
/\.setRequestHeader\(\s*?('|")Content-Type\1\s*?,\s*?('|")application\/json;\s*charset=UTF-8\2\s*?\)/g
)
);
```
Для того, щоб код працював, вам потрібен сет обробника подій `onreadystatechange`.
```js
assert(code.match(/\.onreadystatechange\s*?=/g));
```
У коді має бути елемент `message`, текст якого зміниться з `textContent` на `userName loves cats`
```js
assert(
code.match(
/document\.getElementsByClassName\(\s*?('|")message\1\s*?\)\[0\]\.textContent\s*?=\s*?.+?\.userName\s*?\+\s*?.+?\.suffix/g
)
);
```
Використовуйте метод `send` у вашому коді.
```js
assert(code.match(/\.send\(\s*?body\s*?\)/g));
```
# --seed--
## --seed-contents--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('sendMessage').onclick = function(){
const userName = document.getElementById('name').value;
const url = 'https://jsonplaceholder.typicode.com/posts';
// Add your code below this line
// Add your code above this line
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Friends</h1>
<p class="message box">
Reply from Server will be here
</p>
<p>
<label for="name">Your name:
<input type="text" id="name"/>
</label>
<button id="sendMessage">
Send Message
</button>
</p>
```
# --solutions--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('sendMessage').onclick = function(){
const userName = document.getElementById('name').value;
const url = 'https://jsonplaceholder.typicode.com/posts';
// Add your code below this line
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 201){
const serverResponse = JSON.parse(xhr.response);
document.getElementsByClassName('message')[0].textContent = serverResponse.userName + serverResponse.suffix;
}
};
const body = JSON.stringify({ userName: userName, suffix: ' loves cats!' });
xhr.send(body);
// Add your code above this line
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Friends</h1>
<p class="message">
Reply from Server will be here
</p>
<p>
<label for="name">Your name:
<input type="text" id="name"/>
</label>
<button id="sendMessage">
Send Message
</button>
</p>
```

View File

@ -0,0 +1,171 @@
---
id: 587d7fae367417b2b2512be7
title: Попередній фільтр JSON для отримання потрібних даних
challengeType: 6
forumTopicId: 18257
dashedName: pre-filter-json-to-get-the-data-you-need
---
# --description--
Щоб не відображати кожне фото кота з freeCodeCamp Cat Photo API, використайте попередній фільтр перед створенням циклу.
Так як дані JSON зберігаються в масиві, використайте метод `filter`, щоб знайти фото кота зі значенням ключа `id` - `1`.
Ось приклад такого коду:
```js
json = json.filter(function(val) {
return (val.id !== 1);
});
```
# --instructions--
Видаліть фото кота зі значенням `id` `1`, за допомогою метода `filter` у даних JSON.
# --hints--
Використовуйте метод `filter` у коді.
```js
assert(code.match(/json\.filter/g));
```
# --seed--
## --seed-contents--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('getMessage').onclick = function(){
const req = new XMLHttpRequest();
req.open("GET",'/json/cats.json', true);
req.send();
req.onload=function(){
let json = JSON.parse(req.responseText);
let html = "";
// Add your code below this line
// Add your code above this line
json.forEach(function(val) {
html += "<div class = 'cat'>"
html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>"
html += "</div>"
});
document.getElementsByClassName('message')[0].innerHTML = html;
};
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```
# --solutions--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('getMessage').onclick = function(){
const req = new XMLHttpRequest();
req.open("GET",'/json/cats.json', true);
req.send();
req.onload = function(){
let json = JSON.parse(req.responseText);
let html = "";
// Add your code below this line
json = json.filter(function(val) {
return (val.id !== 1);
});
// Add your code above this line
json.forEach(function(val) {
html += "<div class = 'cat'>"
html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>"
html += "</div>"
});
document.getElementsByClassName('message')[0].innerHTML = html;
};
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```

View File

@ -0,0 +1,163 @@
---
id: 587d7fae367417b2b2512be6
title: Відображення зображень із джерел даних
challengeType: 6
forumTopicId: 18265
dashedName: render-images-from-data-sources
---
# --description--
Під час виконання останніх завдань, ви дізнались, що кожен об'єкт масиву JSON має ключ `imageLink` зі значенням URL-адреси зображення кота.
Під час запуску циклу для цих об'єктів, скористайтесь властивістю `imageLink` для відображення фото в елементі `img`.
Ось приклад такого коду:
```js
html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>";
```
# --instructions--
Додайте код у теґ `img`, щоб використати властивості `imageLink` та `altText`.
# --hints--
Щоб відобразити зображення, використайте властивість `imageLink`.
```js
assert(code.match(/val\.imageLink/g));
```
Використайте у коді `altText` для значень атрибута зображення `alt`.
```js
assert(code.match(/val\.altText/g));
```
# --seed--
## --seed-contents--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('getMessage').onclick = function(){
const req=new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload = function(){
const json = JSON.parse(req.responseText);
let html = "";
json.forEach(function(val) {
html += "<div class = 'cat'>";
// Add your code below this line
// Add your code above this line
html += "</div><br>";
});
document.getElementsByClassName('message')[0].innerHTML=html;
};
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```
# --solutions--
```html
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('getMessage').onclick = function(){
const req = new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload = function(){
const json = JSON.parse(req.responseText);
let html = "";
json.forEach(function(val) {
html += "<div class = 'cat'>";
// Add your code below this line
html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>";
// Add your code above this line
html += "</div><br>";
});
document.getElementsByClassName('message')[0].innerHTML = html;
};
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```