PHP beží na serveri a končí odoslaním HTML. JavaScript beží v prehliadači nad hotovým HTML a mení stránku bez nového requestu. Na tejto stránke vznikne po častiach file js/app.js. Príklady sú všeobecné: odsek, button, formulár s input. V úlohách sa to isté doplní do vlastnej aplikácie. Pojmy sú v tabuľke v týždni 1.
PHP runs on the server and ends by sending HTML. JavaScript runs in the browser over the finished HTML and changes the page without a new request. On this page the file js/app.js is built part by part. The examples are general: a paragraph, a button, a form with an input. In the tasks the same is added to your own application. Terms are in the table in week 1.
TeóriaTheory
Kedy JavaScript na web patrí
| Patrí | Nepatrí |
|---|---|
| ušetrí request: filter zoznamu pri písaní | okná, ktoré vyskakujú bez príčiny |
| pomôže pri vypĺňaní formulára: počítadlo znakov, časť formulára len vtedy, keď je potrebná | texty a obrázky, ktoré sa hýbu bez zásahu používateľa |
| pýta sa pred krokom, ktorý sa nedá vrátiť | zmena vzhľadu pri prejdení myšou |
Zmena farby alebo podčiarknutie pri prejdení myšou sa kedysi robili v JavaScripte. Dnes je to zastarané, robí to CSS cez :hover z cv02.
JavaScript je pohodlie, nie ochrana. V prehliadači sa dá vypnúť a request sa dá poslať aj bez formulára. Kontroly v PHP z cv05 až cv08 preto zostávajú.
Kde JavaScript je a ako sa dostane na stránku
JavaScript je text v samostatnom file, tak ako CSS je v css/style.css. V aplikácii je to jeden file web/js/app.js. Prehliadač o ňom nevie, kým ho HTML nepripojí. Pripája ho tag <script> s attribute src, v ktorom je adresa file:
<script src="js/app.js"></script>
Funguje to ako <link href="css/style.css"> pre CSS alebo <img src="..."> pre obrázok. Prehliadač číta HTML zhora nadol. Keď príde k tagu <script>, vypýta si zo servera file z adresy v src a vykoná ho riadok po riadku. Adresa js/app.js je relatívna: stránky sú vo web/, file je vo web/js/.
Tag sa píše raz, do web/template.php, ako posledný riadok pred </body>. template.php je súčasťou každej stránky, preto je app.js pripojený na každej. Na konci je preto, aby v čase vykonania už celé HTML nad ním existovalo.
Kde sa čo umiestni
| Čo | V ktorom file | Ako to vyzerá |
|---|---|---|
| kód JavaScriptu | web/js/app.js |
riadky ako const info = ...; |
pripojenie app.js k stránke |
web/template.php, posledný riadok pred </body> |
<script src="js/app.js"></script> |
| elementy, s ktorými JavaScript pracuje | content file stránky, napr. web/content/contact.php |
HTML tag s id, class alebo data-..., napr. <p id="info"> |
| čo sa má stať po kliknutí alebo pri písaní | web/js/app.js |
addEventListener z ukážky 3. Do HTML tagu sa onclick="..." nepíše. |
Console: kde vidno, čo JavaScript robí
Console je karta v nástrojoch pre vývojárov. Otvára sa klávesom F12 alebo pravým tlačidlom na stránke a voľbou Preskúmať. Panel má hore rad kariet (Elements, Console, Sources, Network), Console je druhá. Sú v nej dve veci: výpisy príkazu console.log(...) a chyby JavaScriptu červenou. Vpravo pri každom riadku je názov file a číslo riadku, z ktorého výpis je. Používateľ na stránke z toho nevidí nič.
Ako sa JavaScript píše
// komentár do konca riadku, ako v PHP
console.log('Ahoj'); // príkaz končí bodkočiarkou; text je v apostrofoch; v Console bude Ahoj
const limit = 50; // premenná: slovo const, názov, =, hodnota; názov je bez $
let count = 0; // let: premenná, ktorej hodnota sa neskôr zmení
count = count + 1; // zmena hodnoty; pri const by tento riadok skončil chybou
console.log(count); // v Console bude 1
Premenná je na to, aby sa hodnota alebo nájdený element dal použiť na ďalších riadkoch pod krátkym názvom.
Selector: ako JavaScript nájde element
Selector je text, ktorý hovorí, ktorý element sa hľadá. Píše sa rovnako ako v style.css pred {.
| Selector | Čo nájde | HTML, ktoré mu zodpovedá |
|---|---|---|
'#info' |
element s týmto id |
<p id="info"> |
'.item' |
element s touto class | <li class="item"> |
'button' |
element s týmto tagom | <button> |
'input[name="email"]' |
tag s týmto attribute a hodnotou | <input name="email"> |
'button[data-confirm]' |
tag, ktorý tento attribute má | <button data-confirm="..."> |
'#list .item' |
element s class item vnútri elementu s id="list" |
<ul id="list"><li class="item"> |
Pre jeden konkrétny element sa používa id, pre viac rovnakých elementov class.
Objekty a bodka
JavaScript vidí stránku ako objekty. Objekt je vec, ktorá má vlastnosti (property) a vie niečo spraviť (method). K vlastnosti alebo method sa ide cez bodku. Každá bodka znamená krok hlbšie.
document // celá stránka, ktorú prehliadač zobrazuje
document.title // o krok hlbšie: titulok stránky (to, čo je v <title>)
document.querySelector('#info') // method: nájdi na stránke element s id="info"
document.querySelector('#info').textContent // o krok hlbšie: text toho elementu
document.querySelector('#info').textContent.length // ešte hlbšie: počet znakov toho textu
| Zápis | Čo to je | Ako sa pozná |
|---|---|---|
document |
objekt | názov bez bodky pred ním |
.title, .textContent, .value, .length |
property (vlastnosť): hodnota, ktorá sa dá čítať alebo meniť | bez zátvoriek |
.querySelector(...), .addEventListener(...) |
method: objekt niečo spraví | so zátvorkami, v nich je to, čo method potrebuje |
Dlhý zápis sa skracuje premennou. Element sa nájde raz a ďalej sa používa jej názov:
const info = document.querySelector('#info'); // premenná info ukazuje na element s id="info"
info.textContent // to isté ako document.querySelector('#info').textContent
Event (udalosť)
Event je to, čo sa na stránke stane, najčastejšie zásahom používateľa. JavaScript vie na event reagovať: k elementu sa pripojí kód, ktorý sa spustí, keď event na tom elemente nastane.
| Event | Kedy nastane | Na akom elemente |
|---|---|---|
click |
kliknutie | každý element, najčastejšie button a a |
input |
zmena textu pri písaní, po každom znaku | input, textarea |
change |
zmena hodnoty: zaškrtnutie, výber | input type="checkbox", radio, select |
submit |
odoslanie formulára | form |
mouseenter, mouseleave |
myš vošla nad element, odišla z neho | každý element; na zmenu vzhľadu sa používa CSS |
Kód sa k eventu pripája vždy tým istým zápisom:
ELEMENT.addEventListener('EVENT', function () {
// riadky, ktoré sa vykonajú, keď event nastane
});
ELEMENT je premenná s nájdeným elementom, 'EVENT' je názov z tabuľky. Riadky medzi { a } sa pri načítaní stránky nevykonajú. Prehliadač si ich zapamätá a vykoná zakaždým, keď event nastane. Taký zapamätaný blok príkazov sa volá function.
Viac: MDN: úvod do udalostí
When JavaScript belongs on a web page
| Belongs | Does not belong |
|---|---|
| saves a request: filtering a list while typing | windows that pop up for no reason |
| helps when filling in a form: a character counter, a part of the form shown only when needed | texts and images that move without the user doing anything |
| asks before a step that cannot be undone | changing the look when the mouse passes over |
Changing a colour or underlining on mouse-over used to be done in JavaScript. Today that is outdated; CSS does it with :hover from cv02.
JavaScript is a convenience, not protection. It can be switched off in the browser and a request can be sent without the form. The checks in PHP from cv05 to cv08 therefore stay.
Where JavaScript is and how it gets to the page
JavaScript is text in a separate file, just as CSS is in css/style.css. In the application it is one file, web/js/app.js. The browser does not know about it until the HTML includes it. It is included by the tag <script> with the attribute src, which holds the address of the file:
<script src="js/app.js"></script>
It works like <link href="css/style.css"> for CSS or <img src="..."> for an image. The browser reads the HTML from top to bottom. When it reaches the <script> tag, it asks the server for the file at the address in src and executes it line by line. The address js/app.js is relative: the pages are in web/, the file is in web/js/.
The tag is written once, in web/template.php, as the last line before </body>. template.php is part of every page, so app.js is included on every page. It is at the end so that the whole HTML above it already exists when it is executed.
What is placed where
| What | In which file | What it looks like |
|---|---|---|
| JavaScript code | web/js/app.js |
lines like const info = ...; |
including app.js in the page |
web/template.php, the last line before </body> |
<script src="js/app.js"></script> |
| the elements JavaScript works with | the content file of the page, e.g. web/content/contact.php |
an HTML tag with id, class or data-..., e.g. <p id="info"> |
| what should happen after a click or while typing | web/js/app.js |
addEventListener from example 3. onclick="..." is not written into the HTML tag. |
The Console: where to see what JavaScript does
The Console is a tab in the developer tools. It opens with the F12 key or with a right click on the page and the option Inspect. The panel has a row of tabs at the top (Elements, Console, Sources, Network); Console is the second one. It holds two things: the output of console.log(...) and JavaScript errors in red. On the right of every line is the name of the file and the number of the line the output comes from. The user sees none of it on the page.
How JavaScript is written
// komentár do konca riadku, ako v PHP
console.log('Ahoj'); // príkaz končí bodkočiarkou; text je v apostrofoch; v Console bude Ahoj
const limit = 50; // premenná: slovo const, názov, =, hodnota; názov je bez $
let count = 0; // let: premenná, ktorej hodnota sa neskôr zmení
count = count + 1; // zmena hodnoty; pri const by tento riadok skončil chybou
console.log(count); // v Console bude 1
A variable exists so that a value or a found element can be used on the following lines under a short name. Comments in the code are in Slovak.
The selector: how JavaScript finds an element
A selector is a text that says which element is searched for. It is written the same way as in style.css before {.
| Selector | What it finds | The HTML that matches it |
|---|---|---|
'#info' |
the element with this id |
<p id="info"> |
'.item' |
an element with this class | <li class="item"> |
'button' |
an element with this tag | <button> |
'input[name="email"]' |
a tag with this attribute and value | <input name="email"> |
'button[data-confirm]' |
a tag that has this attribute | <button data-confirm="..."> |
'#list .item' |
an element with the class item inside the element with id="list" |
<ul id="list"><li class="item"> |
For one particular element use an id, for several elements of the same kind a class.
Objects and the dot
JavaScript sees the page as objects. An object is a thing that has properties and can do something (methods). A property or a method is reached with a dot. Every dot is one step deeper.
document // celá stránka, ktorú prehliadač zobrazuje
document.title // o krok hlbšie: titulok stránky (to, čo je v <title>)
document.querySelector('#info') // method: nájdi na stránke element s id="info"
document.querySelector('#info').textContent // o krok hlbšie: text toho elementu
document.querySelector('#info').textContent.length // ešte hlbšie: počet znakov toho textu
| Notation | What it is | How to recognise it |
|---|---|---|
document |
an object | a name with no dot before it |
.title, .textContent, .value, .length |
a property: a value that can be read or changed | no parentheses |
.querySelector(...), .addEventListener(...) |
a method: the object does something | with parentheses holding what the method needs |
A long notation is shortened with a variable. The element is found once and then its name is used:
const info = document.querySelector('#info'); // premenná info ukazuje na element s id="info"
info.textContent // to isté ako document.querySelector('#info').textContent
Event
An event is something that happens on the page, most often caused by the user. JavaScript can react to an event: code is attached to an element and runs when the event happens on that element.
| Event | When it happens | On which element |
|---|---|---|
click |
a click | every element, most often button and a |
input |
the text changes while typing, after every character | input, textarea |
change |
the value changes: checking, selecting | input type="checkbox", radio, select |
submit |
the form is submitted | form |
mouseenter, mouseleave |
the mouse moved over the element, left it | every element; CSS is used for changing the look |
Code is always attached to an event with the same notation:
ELEMENT.addEventListener('EVENT', function () {
// riadky, ktoré sa vykonajú, keď event nastane
});
ELEMENT is the variable holding the found element, 'EVENT' is a name from the table. The lines between { and } are not executed when the page loads. The browser remembers them and executes them every time the event happens. Such a remembered block of statements is called a function.
UkážkyExamples
HTML z ukážok patrí do content file stránky, na ktorej to má byť. Kód JavaScriptu sa pridáva na koniec web/js/app.js. Živé náhľady sa dajú vyskúšať priamo tu.
Ukážka 1: file js/app.js a jeho pripojenie
Nový file web/js/app.js:
// ROLA: JavaScript aplikácie, spoločný file. Pripája ho template.php, platí pre každú stránku.
console.log('app.js je pripojený'); // vypíše text do Console (F12); používateľ ho na stránke nevidí
V web/template.php, posledný riadok pred </body>:
<script src="js/app.js"></script> <!-- prehliadač si vypýta file js/app.js a vykoná ho -->
</body>
Script je na konci stránky, aby v čase jeho spustenia už celé HTML existovalo.
Stránka vyzerá rovnako. V Console je riadok app.js je pripojený:
Pravidlo: console.log(HODNOTA); vypíše hodnotu do Console. Je to miesto na skúšanie, ako echo v PHP.
Ukážka 2: nájsť element
V content file stránky:
<p id="info">Text pred kliknutím.</p>
const info = document.querySelector('#info'); // na stránke (document) nájdi element so selectorom #info a ulož ho do premennej info
console.log(info); // do Console (F12) vypíš ten element
console.log(info.textContent); // do Console vypíš text medzi jeho tagmi
Na stránke je odsek „Text pred kliknutím.” V Console pribudli dva riadky, element a jeho text:
Pravidlo: const NÁZOV = document.querySelector('SELECTOR'); nájde prvý element, ktorému selector zodpovedá, a uloží ho do premennej. Ďalšie riadky s ním pracujú cez NÁZOV. Keď taký element na stránke nie je, v premennej je null.
Varianty: selectory z tabuľky v teórii.
Ukážka 3: zmena textu po kliknutí
V content file stránky, pod odsekom:
<button type="button" class="btn btn-outline-primary" id="change">Zmeň text</button> <!-- type="button": button nič neodosiela -->
const change = document.querySelector('#change'); // nájdi button s id="change"
change.addEventListener('click', function () { // keď používateľ klikne na button, vykonaj riadky v { }
info.textContent = 'Text po kliknutí.'; // text odseku sa zmení
}); // koniec function a koniec addEventListener
Premenná info je z ukážky 2.
Odsek „Text pred kliknutím.” a pod ním button Zmeň text. Po kliknutí je v odseku „Text po kliknutí.” Stránka sa neobnovila, adresa je rovnaká. Po F5 je tam znova pôvodný text, lebo HTML zo servera sa nezmenilo.
Text pred kliknutím.
Pravidlo: ELEMENT.addEventListener('EVENT', function () { ČO SA MÁ STAŤ }); Riadky v { } sa pri načítaní stránky nevykonajú. Prehliadač si ich zapamätá a vykoná zakaždým, keď event nastane. Taký blok príkazov sa volá function.
Varianty: namiesto 'click' iný event z tabuľky. Meniť sa dá textContent (text elementu), value (hodnota v input), classList (classes).
Ukážka 4: skryť a zobraziť text
V content file stránky:
<button type="button" class="btn btn-outline-secondary" id="toggle">Zobraz alebo skry</button>
<p id="more-text" class="d-none">Tento text je na začiatku skrytý.</p> <!-- d-none: Bootstrap class, element sa nezobrazuje -->
const toggle = document.querySelector('#toggle'); // button
const moreText = document.querySelector('#more-text'); // odsek, ktorý sa skrýva
toggle.addEventListener('click', function () { // po kliknutí na button
moreText.classList.toggle('d-none'); // ak class d-none má, odober ju; ak ju nemá, pridaj ju
});
Class d-none je z Bootstrap, ktorý je pripojený v template.php.
Na stránke je len button. Po kliknutí je pod ním odsek. Po ďalšom kliknutí odsek zmizne. V HTML odsek stále je, mení sa len jeho class.
Tento text je na začiatku skrytý.
Pravidlo: ELEMENT.classList je zoznam classes elementu.
Varianty: .add('d-none') pridá class, .remove('d-none') odoberie, .toggle('d-none') prepne, .contains('d-none') vráti true alebo false. Class môže byť hocijaká, aj vlastná zo style.css.
Ukážka 5: počítadlo znakov pri písaní
V content file stránky, vo formulári:
<label class="form-label" for="name">Názov</label>
<input class="form-control" type="text" id="name" name="name" maxlength="50"> <!-- maxlength: prehliadač nepustí viac znakov -->
<div class="form-text" id="name-count">0 / 50</div> <!-- sem JavaScript píše počet -->
const nameInput = document.querySelector('#name'); // input
const nameCount = document.querySelector('#name-count'); // text pod ním
nameInput.addEventListener('input', function () { // po každej zmene textu v input
nameCount.textContent = nameInput.value.length + ' / 50'; // value: text v input; length: počet znakov; + spája texty
});
PHP, ktoré formulár spracúva, sa nemení. name="name" zostáva, hodnota príde v $_POST['name'] ako predtým.
Prázdny input a pod ním 0 / 50. Po napísaní „Ahoj” je tam 4 / 50. Číslo sa mení po každom znaku.
Pravidlo: INPUT.value je to, čo je práve v input napísané. Texty sa v JavaScripte spájajú cez +, v PHP cez bodku.
Varianty: to isté funguje pre textarea. .value.length je počet znakov, .value.trim() text bez medzier na krajoch, .value.toLowerCase() text malými písmenami.
Ukážka 6: časť formulára po zaškrtnutí checkboxu
V content file stránky, vo formulári:
<div class="form-check">
<input class="form-check-input" type="checkbox" id="more" name="more" value="yes">
<label class="form-check-label" for="more">Chcem napísať poznámku</label>
</div>
<div id="more-part" class="d-none"> <!-- táto časť je na začiatku skrytá -->
<label class="form-label" for="message">Poznámka</label>
<textarea class="form-control" id="message" name="message" rows="2"></textarea>
</div>
const more = document.querySelector('#more'); // checkbox
const morePart = document.querySelector('#more-part'); // časť formulára
more.addEventListener('change', function () { // keď sa checkbox zaškrtne alebo odškrtne
if (more.checked) { // checked: true, keď je zaškrtnutý
morePart.classList.remove('d-none'); // zobraz časť formulára
} else {
morePart.classList.add('d-none'); // skry ju
}
});
Skrytá textarea sa odošle tiež, len prázdna. PHP preto berie message ako nepovinnú hodnotu.
Vo formulári je len checkbox. Po zaškrtnutí sa pod ním objaví Poznámka s textarea. Po odškrtnutí zmizne.
Pravidlo: CHECKBOX.checked je true alebo false. Podmienka if ... else sa píše ako v PHP.
Varianty: pre select sa číta SELECT.value (hodnota vybraného option). Len zobrazenie a skrytie vie aj CSS cez :has(#more:checked).
Ukážka 7: filter zoznamu pri písaní
V content file stránky:
<input class="form-control mb-3" type="text" id="search" placeholder="Hľadať">
<ul class="list-group">
<li class="list-group-item item">Jablko</li> <!-- class item: podľa nej JavaScript nájde každú položku -->
<li class="list-group-item item">Hruška</li>
<li class="list-group-item item">Jahoda</li>
</ul>
const search = document.querySelector('#search'); // input na hľadanie
const items = document.querySelectorAll('.item'); // každý element s class item, nie len prvý
search.addEventListener('input', function () { // po každej zmene textu v input
const text = search.value.toLowerCase(); // napísaný text malými písmenami
for (const item of items) { // prejdi položky po jednej, ako foreach v PHP
if (item.textContent.toLowerCase().includes(text)) { // obsahuje text položky napísaný text?
item.classList.remove('d-none'); // áno: zobraz ju
} else {
item.classList.add('d-none'); // nie: skry ju
}
}
});
Filter nepíše do databázy ani neposiela request, len skrýva to, čo na stránke už je.
Input a pod ním Jablko, Hruška, Jahoda. Po napísaní „ja” zostanú Jablko a Jahoda. Po zmazaní textu sú tam znova všetky. Adresa v prehliadači sa nemení.
- Jablko
- Hruška
- Jahoda
Pravidlo: document.querySelectorAll('SELECTOR') vráti zoznam elementov. for (const X of ZOZNAM) { ... } ho prejde. TEXT.includes(INÝ_TEXT) vráti true, keď ho obsahuje.
Varianty: položkou môže byť riadok tabuľky (tr) alebo card (div). Keď sa má hľadať len v časti položky, dá sa jej attribute data-name="jablko" a číta sa cez item.dataset.name.
Ukážka 8: otázka pred odoslaním formulára
Kliknutie na button vo formulári formulár odošle. Cieľ: prvé kliknutie ho neodošle, len zmení text buttonu na otázku. Až druhé kliknutie ho odošle.
V content file stránky, button vo formulári má attribute data-confirm:
<form method="post" action="delete-item.php">
<input type="hidden" name="id" value="3">
<button class="btn btn-outline-danger btn-sm" data-confirm="Naozaj zmazať?">Zmazať</button> <!-- data-confirm: text otázky -->
</form>
const confirmButtons = document.querySelectorAll('button[data-confirm]'); // každý button, ktorý má attribute data-confirm
for (const button of confirmButtons) { // pre každý taký button
button.addEventListener('click', function (event) { // event: údaje o tomto kliknutí, dodá ich prehliadač
if (button.dataset.asked !== 'yes') { // !== znamená nie je rovné: button ešte nemá data-asked="yes", je to prvé kliknutie
event.preventDefault(); // prehliadač po tomto kliknutí formulár neodošle
button.dataset.asked = 'yes'; // zapíš buttonu data-asked="yes", ďalšie kliknutie bude druhé
button.textContent = button.dataset.confirm; // text buttonu sa zmení na text z data-confirm
} // pri druhom kliknutí podmienka neplatí a formulár sa odošle
});
}
File, ktorý formulár spracúva, sa nemení. Bez JavaScriptu button zmaže hneď, ako doteraz.
Button s textom Zmazať. Po prvom kliknutí má text „Naozaj zmazať?” a nič sa neodoslalo. Po druhom kliknutí sa formulár odošle.
Druhé kliknutie: formulár by sa teraz odoslal na delete-item.php. Skúsiť znova
Pravidlo: event.preventDefault() zruší to, čo by prehliadač po evente spravil. Pri click na button vo formulári je to odoslanie formulára, pri click na odkaz prechod na inú stránku. ELEMENT.dataset.NÁZOV číta a zapisuje attribute data-NÁZOV.
Varianty: attribute data-confirm sa dá dať na hociktorý button. Text otázky môže byť pri každom iný a app.js sa nemení.
Ukážka 9: element, ktorý na stránke nie je
js/app.js je pripojený na každej stránke, ale input #name je len na jednej. Na ostatných vráti document.querySelector('#name') hodnotu null, riadok nameInput.addEventListener(...) skončí chybou Cannot read properties of null a zvyšok app.js sa nevykoná.
V js/app.js sa preto každá časť s jedným elementom obalí podmienkou:
if (nameInput) { // vykonaj len vtedy, keď element na stránke je
nameInput.addEventListener('input', function () {
nameCount.textContent = nameInput.value.length + ' / 50';
});
}
Pri for (const button of confirmButtons) podmienka netreba. Keď na stránke žiadny taký button nie je, zoznam je prázdny a cyklus neprebehne ani raz.
Pravidlo: if (ELEMENT) { ... } platí, keď querySelector element našiel. Keď vrátil null, blok sa preskočí.
Ukážka 10: js/app.js v aplikácii lezecká stena
Vo vzore cv10 sú v js/app.js ukážky 5, 7 a 8. Ukážky 2, 3, 4 a 6 boli na pochopenie zápisu, v aplikácii nie sú.
| Ukážka | Kde je HTML (file a rola) | Čo v ňom pribudlo |
|---|---|---|
| 5, počítadlo | content/add-route.php, content/edit-route.php (main entity, formulár) |
textarea note má maxlength="200", pod ňou <div id="note-count"> |
| 7, filter | content/routes.php (main entity, zoznam) |
input id="search", každá karta má class route-card, počet je v <span id="shown"> |
| 8, otázka | content/data.php (lookup tables), content/detail.php (main entity) |
button Zmazať má data-confirm="Naozaj zmazať?" |
// ROLA: JavaScript aplikácie, spoločný file. Pripája ho template.php, platí pre každú stránku.
// ROBÍ: počítadlo znakov pri poznámke, filter zoznamu pri písaní, otázka pred zmazaním.
// VO SVOJEJ APLIKÁCII: zmeň selectory (#note, #search, .route-card) podľa svojho HTML.
console.log('app.js je pripojený'); // vypíše text do Console; používateľ ho na stránke nevidí
// 1. Počítadlo znakov pri poznámke (add-route.php, edit-route.php)
const note = document.querySelector('#note'); // textarea s id="note"; na ostatných stránkach null
const noteCount = document.querySelector('#note-count'); // text pod ňou
if (note) { // vykonaj len na stránke, kde textarea je
noteCount.textContent = note.value.length + ' / 200'; // počet znakov hneď po načítaní stránky (pri úprave už text je)
note.addEventListener('input', function () { // po každej zmene textu v textarea
noteCount.textContent = note.value.length + ' / 200'; // value: text v textarea; length: počet znakov; + spája texty
});
}
// 2. Filter zoznamu pri písaní (routes.php)
const search = document.querySelector('#search'); // input na hľadanie; na ostatných stránkach null
const cards = document.querySelectorAll('.route-card'); // každá karta v zozname
const shown = document.querySelector('#shown'); // text s počtom zobrazených kariet
if (search) { // vykonaj len na stránke, kde input je
search.addEventListener('input', function () { // po každej zmene textu v input
const text = search.value.toLowerCase(); // napísaný text malými písmenami
let count = 0; // počet kariet, ktoré zostanú zobrazené
for (const card of cards) { // prejdi karty po jednej
if (card.textContent.toLowerCase().includes(text)) { // obsahuje text karty napísaný text?
card.classList.remove('d-none'); // áno: zobraz ju
count = count + 1;
} else {
card.classList.add('d-none'); // nie: skry ju
}
}
shown.textContent = count; // počet nad zoznamom
});
}
// 3. Otázka pred zmazaním (data.php, detail.php): každý button s attribute data-confirm
const confirmButtons = document.querySelectorAll('button[data-confirm]');
for (const button of confirmButtons) { // pre každý taký button; keď žiadny nie je, cyklus neprebehne
button.addEventListener('click', function (event) { // event: údaje o tomto kliknutí, dodá ich prehliadač
if (button.dataset.asked !== 'yes') { // !== znamená nie je rovné: button ešte nemá data-asked="yes", je to prvé kliknutie
event.preventDefault(); // prehliadač po tomto kliknutí formulár neodošle
button.dataset.asked = 'yes'; // ďalšie kliknutie bude druhé
button.textContent = button.dataset.confirm; // text buttonu sa zmení na text z data-confirm
} // pri druhom kliknutí podmienka neplatí a formulár sa odošle
});
}
Filter cez GET z cv07 (select Grade a button Filtrovať) v routes.php zostáva. Ten posiela request a SELECT s WHERE vráti z databázy len vybrané cesty. Filter pri písaní hľadá len v kartách, ktoré na stránke práve sú.
Vo svojej aplikácii. V app.js zmeň selectory #note, #search a .route-card podľa id a class vo svojom HTML. Časť s button[data-confirm] sa nemení.
Ukážka 11: prompty
Prompt A, počítadlo znakov. Prikladá sa web/js/app.js a web/content/add-ENTITY.php.
Prikladám js/app.js a content file s formulárom. Doplň počítadlo znakov pre textarea alebo input, ktorý označím komentárom <!-- POČÍTADLO -->. Do HTML pridaj maxlength a pod element <div class="form-text"> s id končiacim na -count. Do js/app.js pridaj na koniec: querySelector pre oba elementy, podmienku if (element), addEventListener('input', function () { ... }) s textContent a value.length. Bez knižníc, bez šípkových funkcií, bez onclick v HTML. Komentár pri každom riadku po slovensky. Limit znakov nechaj ako // DOPLŇ. Vráť celé oba files.
Prompt B, filter pri písaní. Prikladá sa web/js/app.js a web/content/ENTITY.php.
Prikladám js/app.js a content file so zoznamom z databázy. Doplň filter pri písaní. Do HTML pridaj nad zoznam input type text s id search a každej položke zoznamu class, podľa ktorej ju JavaScript nájde; existujúci filter cez GET nechaj. Do js/app.js pridaj na koniec: querySelector pre input, querySelectorAll pre položky, podmienku if (search), addEventListener('input', ...), v ňom for (const ... of ...) s textContent.toLowerCase().includes(...) a classList.add / remove 'd-none'. Bez knižníc, bez šípkových funkcií. Komentár pri každom riadku po slovensky. Názov class položky nechaj ako // DOPLŇ. Vráť celé oba files.
Prompt C, otázka pred zmazaním. Prikladá sa web/js/app.js, web/content/data.php a web/content/detail.php.
Prikladám js/app.js a content files s formulármi na zmazanie. Každému buttonu Zmazať pridaj attribute data-confirm s textom otázky; formuláre a ich action nemeň. Do js/app.js pridaj na koniec: querySelectorAll('button[data-confirm]'), for (const button of ...), addEventListener('click', function (event) { ... }); pri prvom kliknutí event.preventDefault(), button.dataset.asked = 'yes' a text buttonu z button.dataset.confirm; druhé kliknutie formulár odošle. Bez alert a confirm, bez šípkových funkcií. Komentár pri každom riadku po slovensky. Text otázky nechaj ako // DOPLŇ. Vráť celé files.
Prečo sú prompty napísané práve takto:
- priložený
app.js: AI dopĺňa na koniec jedného file a nevytvára ďalší, - „bez šípkových funkcií”: kód je v tom istom zápise ako na tejto stránke a dá sa obhájiť,
- „bez onclick v HTML”: JavaScript zostane v
app.js, - „bez alert a confirm”: na stránke nič nevyskakuje,
- „existujúci filter cez GET nechaj” a „formuláre nemeň”: to, čo fungovalo v cv07 a cv08, zostane funkčné aj bez JavaScriptu,
// DOPLŇnecháva limit, názov class a text otázky na autorovi aplikácie.
Najčastejšie chyby a čo znamenajú
Chyby JavaScriptu sú v nástrojoch pre vývojárov (F12, karta Console), červenou. Stránka pri chybe vyzerá normálne, len JavaScript nič nerobí.
| Hláška alebo prejav | Príčina | Riešenie |
|---|---|---|
v Console nie je app.js je pripojený |
<script src="js/app.js"> chýba v template.php, alebo je zlá cesta |
riadok pred </body>; file je vo web/js/ |
GET .../js/app.js 404 |
file sa volá inak alebo je v inom priečinku | web/js/app.js |
Cannot read properties of null (reading 'addEventListener') |
querySelector element nenašiel: na tejto stránke nie je, alebo je preklep v id |
podmienka if (element) z ukážky 9; porovnať id v HTML so selectorom |
po chybe nefunguje ani zvyšok app.js |
JavaScript sa pri prvej chybe zastaví | opraviť prvú červenú hlášku v Console |
Unexpected token alebo missing ) after argument list |
chýba zátvorka, najčastejšie }); na konci addEventListener |
spočítať (, { a ich uzavretia |
zmena v app.js sa neprejaví |
prehliadač má starú verziu file v pamäti | obnoviť stránku cez Ctrl+F5 |
| button s otázkou formulár odošle hneď | chýba event.preventDefault() alebo event v function (event) |
doplniť podľa ukážky 8 |
| filter neskrýva nič | položky nemajú class, podľa ktorej ich querySelectorAll hľadá |
doplniť class do HTML |
The HTML from the examples belongs in the content file of the page where it should be. JavaScript code is added at the end of web/js/app.js. The live previews can be tried right here. Comments in the code and texts in the previews are in Slovak.
Example 1: the file js/app.js and including it
A new file web/js/app.js:
// ROLA: JavaScript aplikácie, spoločný file. Pripája ho template.php, platí pre každú stránku.
console.log('app.js je pripojený'); // vypíše text do Console (F12); používateľ ho na stránke nevidí
In web/template.php, the last line before </body>:
<script src="js/app.js"></script> <!-- prehliadač si vypýta file js/app.js a vykoná ho -->
</body>
The script is at the end of the page so that the whole HTML already exists when it runs.
The page looks the same. The Console shows the line app.js je pripojený (app.js is included):
Rule: console.log(VALUE); prints a value to the Console. It is a place for trying things out, like echo in PHP.
Example 2: finding an element
In the content file of the page:
<p id="info">Text pred kliknutím.</p>
const info = document.querySelector('#info'); // na stránke (document) nájdi element so selectorom #info a ulož ho do premennej info
console.log(info); // do Console (F12) vypíš ten element
console.log(info.textContent); // do Console vypíš text medzi jeho tagmi
The page shows the paragraph “Text pred kliknutím.” (Text before the click.) Two lines were added to the Console, the element and its text:
Rule: const NAME = document.querySelector('SELECTOR'); finds the first element the selector matches and stores it in the variable. The following lines work with it through NAME. When there is no such element on the page, the variable holds null.
Variants: the selectors from the table in the theory.
Example 3: changing text after a click
In the content file of the page, below the paragraph:
<button type="button" class="btn btn-outline-primary" id="change">Zmeň text</button> <!-- type="button": button nič neodosiela -->
const change = document.querySelector('#change'); // nájdi button s id="change"
change.addEventListener('click', function () { // keď používateľ klikne na button, vykonaj riadky v { }
info.textContent = 'Text po kliknutí.'; // text odseku sa zmení
}); // koniec function a koniec addEventListener
The variable info is from example 2.
The paragraph “Text pred kliknutím.” and below it the button Zmeň text (Change the text). After the click the paragraph says “Text po kliknutí.” (Text after the click.) The page did not reload, the address is the same. After F5 the original text is back, because the HTML from the server did not change.
Text pred kliknutím.
Rule: ELEMENT.addEventListener('EVENT', function () { WHAT SHOULD HAPPEN }); The lines in { } are not executed when the page loads. The browser remembers them and executes them every time the event happens. Such a block of statements is called a function.
Variants: another event from the table instead of 'click'. What can be changed: textContent (the text of an element), value (the value in an input), classList (classes).
Example 4: hiding and showing text
In the content file of the page:
<button type="button" class="btn btn-outline-secondary" id="toggle">Zobraz alebo skry</button>
<p id="more-text" class="d-none">Tento text je na začiatku skrytý.</p> <!-- d-none: Bootstrap class, element sa nezobrazuje -->
const toggle = document.querySelector('#toggle'); // button
const moreText = document.querySelector('#more-text'); // odsek, ktorý sa skrýva
toggle.addEventListener('click', function () { // po kliknutí na button
moreText.classList.toggle('d-none'); // ak class d-none má, odober ju; ak ju nemá, pridaj ju
});
The class d-none comes from Bootstrap, which is included in template.php.
The page shows only the button. After a click the paragraph is below it. After another click the paragraph disappears. The paragraph is still in the HTML; only its class changes.
Tento text je na začiatku skrytý.
Rule: ELEMENT.classList is the list of classes of an element.
Variants: .add('d-none') adds a class, .remove('d-none') removes it, .toggle('d-none') switches it, .contains('d-none') returns true or false. The class can be any class, including your own from style.css.
Example 5: a character counter while typing
In the content file of the page, inside the form:
<label class="form-label" for="name">Názov</label>
<input class="form-control" type="text" id="name" name="name" maxlength="50"> <!-- maxlength: prehliadač nepustí viac znakov -->
<div class="form-text" id="name-count">0 / 50</div> <!-- sem JavaScript píše počet -->
const nameInput = document.querySelector('#name'); // input
const nameCount = document.querySelector('#name-count'); // text pod ním
nameInput.addEventListener('input', function () { // po každej zmene textu v input
nameCount.textContent = nameInput.value.length + ' / 50'; // value: text v input; length: počet znakov; + spája texty
});
The PHP that processes the form does not change. name="name" stays; the value arrives in $_POST['name'] as before.
An empty input and below it 0 / 50. After typing “Ahoj” it says 4 / 50. The number changes after every character.
Rule: INPUT.value is what is currently typed in the input. Texts are joined with + in JavaScript, with a dot in PHP.
Variants: the same works for a textarea. .value.length is the number of characters, .value.trim() the text without spaces at the edges, .value.toLowerCase() the text in lowercase.
Example 6: a part of the form after checking a checkbox
In the content file of the page, inside the form:
<div class="form-check">
<input class="form-check-input" type="checkbox" id="more" name="more" value="yes">
<label class="form-check-label" for="more">Chcem napísať poznámku</label>
</div>
<div id="more-part" class="d-none"> <!-- táto časť je na začiatku skrytá -->
<label class="form-label" for="message">Poznámka</label>
<textarea class="form-control" id="message" name="message" rows="2"></textarea>
</div>
const more = document.querySelector('#more'); // checkbox
const morePart = document.querySelector('#more-part'); // časť formulára
more.addEventListener('change', function () { // keď sa checkbox zaškrtne alebo odškrtne
if (more.checked) { // checked: true, keď je zaškrtnutý
morePart.classList.remove('d-none'); // zobraz časť formulára
} else {
morePart.classList.add('d-none'); // skry ju
}
});
The hidden textarea is submitted too, just empty. PHP therefore treats message as an optional value.
The form shows only the checkbox. After checking it, Poznámka (Note) with a textarea appears below. After unchecking it disappears.
Rule: CHECKBOX.checked is true or false. The condition if ... else is written as in PHP.
Variants: for a select read SELECT.value (the value of the selected option). Showing and hiding alone can also be done in CSS with :has(#more:checked).
Example 7: filtering a list while typing
In the content file of the page:
<input class="form-control mb-3" type="text" id="search" placeholder="Hľadať">
<ul class="list-group">
<li class="list-group-item item">Jablko</li> <!-- class item: podľa nej JavaScript nájde každú položku -->
<li class="list-group-item item">Hruška</li>
<li class="list-group-item item">Jahoda</li>
</ul>
const search = document.querySelector('#search'); // input na hľadanie
const items = document.querySelectorAll('.item'); // každý element s class item, nie len prvý
search.addEventListener('input', function () { // po každej zmene textu v input
const text = search.value.toLowerCase(); // napísaný text malými písmenami
for (const item of items) { // prejdi položky po jednej, ako foreach v PHP
if (item.textContent.toLowerCase().includes(text)) { // obsahuje text položky napísaný text?
item.classList.remove('d-none'); // áno: zobraz ju
} else {
item.classList.add('d-none'); // nie: skry ju
}
}
});
The filter does not write to the database or send a request; it only hides what is already on the page.
An input and below it Jablko, Hruška, Jahoda. After typing “ja”, Jablko and Jahoda remain. After deleting the text all of them are back. The address in the browser does not change.
- Jablko
- Hruška
- Jahoda
Rule: document.querySelectorAll('SELECTOR') returns a list of elements. for (const X of LIST) { ... } goes through it. TEXT.includes(OTHER_TEXT) returns true when it contains it.
Variants: an item can be a table row (tr) or a card (div). When only a part of the item should be searched, give it the attribute data-name="jablko" and read it with item.dataset.name.
Example 8: a question before the form is submitted
Clicking a button in a form submits the form. The goal: the first click does not submit it, it only changes the text of the button into a question. Only the second click submits it.
In the content file of the page, the button in the form has the attribute data-confirm:
<form method="post" action="delete-item.php">
<input type="hidden" name="id" value="3">
<button class="btn btn-outline-danger btn-sm" data-confirm="Naozaj zmazať?">Zmazať</button> <!-- data-confirm: text otázky -->
</form>
const confirmButtons = document.querySelectorAll('button[data-confirm]'); // každý button, ktorý má attribute data-confirm
for (const button of confirmButtons) { // pre každý taký button
button.addEventListener('click', function (event) { // event: údaje o tomto kliknutí, dodá ich prehliadač
if (button.dataset.asked !== 'yes') { // !== znamená nie je rovné: button ešte nemá data-asked="yes", je to prvé kliknutie
event.preventDefault(); // prehliadač po tomto kliknutí formulár neodošle
button.dataset.asked = 'yes'; // zapíš buttonu data-asked="yes", ďalšie kliknutie bude druhé
button.textContent = button.dataset.confirm; // text buttonu sa zmení na text z data-confirm
} // pri druhom kliknutí podmienka neplatí a formulár sa odošle
});
}
The file that processes the form does not change. Without JavaScript the button deletes immediately, as before.
A button with the text Zmazať (Delete). After the first click its text is “Naozaj zmazať?” (Really delete?) and nothing was submitted. After the second click the form is submitted.
Druhé kliknutie: formulár by sa teraz odoslal na delete-item.php. Skúsiť znova
Rule: event.preventDefault() cancels what the browser would do after the event. For a click on a button in a form that is submitting the form; for a click on a link, going to another page. ELEMENT.dataset.NAME reads and writes the attribute data-NAME.
Variants: the attribute data-confirm can be put on any button. The text of the question can differ for each one and app.js does not change.
Example 9: an element that is not on the page
js/app.js is included on every page, but the input #name is on only one. On the others document.querySelector('#name') returns null, the line nameInput.addEventListener(...) ends with the error Cannot read properties of null and the rest of app.js is not executed.
In js/app.js every part with a single element is therefore wrapped in a condition:
if (nameInput) { // vykonaj len vtedy, keď element na stránke je
nameInput.addEventListener('input', function () {
nameCount.textContent = nameInput.value.length + ' / 50';
});
}
For for (const button of confirmButtons) no condition is needed. When the page has no such button, the list is empty and the loop does not run even once.
Rule: if (ELEMENT) { ... } holds when querySelector found the element. When it returned null, the block is skipped.
Example 10: js/app.js in the climbing wall application
In sample cv10 js/app.js contains examples 5, 7 and 8. Examples 2, 3, 4 and 6 were for understanding the notation; they are not in the application.
| Example | Where the HTML is (file and role) | What was added |
|---|---|---|
| 5, counter | content/add-route.php, content/edit-route.php (main entity, form) |
the textarea note has maxlength="200", below it <div id="note-count"> |
| 7, filter | content/routes.php (main entity, list) |
an input with id="search", every card has the class route-card, the count is in <span id="shown"> |
| 8, question | content/data.php (lookup tables), content/detail.php (main entity) |
the button Zmazať has data-confirm="Naozaj zmazať?" |
// ROLA: JavaScript aplikácie, spoločný file. Pripája ho template.php, platí pre každú stránku.
// ROBÍ: počítadlo znakov pri poznámke, filter zoznamu pri písaní, otázka pred zmazaním.
// VO SVOJEJ APLIKÁCII: zmeň selectory (#note, #search, .route-card) podľa svojho HTML.
console.log('app.js je pripojený'); // vypíše text do Console; používateľ ho na stránke nevidí
// 1. Počítadlo znakov pri poznámke (add-route.php, edit-route.php)
const note = document.querySelector('#note'); // textarea s id="note"; na ostatných stránkach null
const noteCount = document.querySelector('#note-count'); // text pod ňou
if (note) { // vykonaj len na stránke, kde textarea je
noteCount.textContent = note.value.length + ' / 200'; // počet znakov hneď po načítaní stránky (pri úprave už text je)
note.addEventListener('input', function () { // po každej zmene textu v textarea
noteCount.textContent = note.value.length + ' / 200'; // value: text v textarea; length: počet znakov; + spája texty
});
}
// 2. Filter zoznamu pri písaní (routes.php)
const search = document.querySelector('#search'); // input na hľadanie; na ostatných stránkach null
const cards = document.querySelectorAll('.route-card'); // každá karta v zozname
const shown = document.querySelector('#shown'); // text s počtom zobrazených kariet
if (search) { // vykonaj len na stránke, kde input je
search.addEventListener('input', function () { // po každej zmene textu v input
const text = search.value.toLowerCase(); // napísaný text malými písmenami
let count = 0; // počet kariet, ktoré zostanú zobrazené
for (const card of cards) { // prejdi karty po jednej
if (card.textContent.toLowerCase().includes(text)) { // obsahuje text karty napísaný text?
card.classList.remove('d-none'); // áno: zobraz ju
count = count + 1;
} else {
card.classList.add('d-none'); // nie: skry ju
}
}
shown.textContent = count; // počet nad zoznamom
});
}
// 3. Otázka pred zmazaním (data.php, detail.php): každý button s attribute data-confirm
const confirmButtons = document.querySelectorAll('button[data-confirm]');
for (const button of confirmButtons) { // pre každý taký button; keď žiadny nie je, cyklus neprebehne
button.addEventListener('click', function (event) { // event: údaje o tomto kliknutí, dodá ich prehliadač
if (button.dataset.asked !== 'yes') { // !== znamená nie je rovné: button ešte nemá data-asked="yes", je to prvé kliknutie
event.preventDefault(); // prehliadač po tomto kliknutí formulár neodošle
button.dataset.asked = 'yes'; // ďalšie kliknutie bude druhé
button.textContent = button.dataset.confirm; // text buttonu sa zmení na text z data-confirm
} // pri druhom kliknutí podmienka neplatí a formulár sa odošle
});
}
The GET filter from cv07 (the select Grade and the button Filtrovať) stays in routes.php. It sends a request, and a SELECT with WHERE returns only the chosen routes from the database. The filter while typing searches only the cards that are currently on the page.
In your own application. In app.js change the selectors #note, #search and .route-card to the id and class in your HTML. The part with button[data-confirm] does not change.
Example 11: prompts
Prompt A, the character counter. Attach web/js/app.js and web/content/add-ENTITY.php.
I attach js/app.js and a content file with a form. Add a character counter for the textarea or input that I mark with the comment <!-- POČÍTADLO -->. In the HTML add maxlength and below the element a <div class="form-text"> with an id ending in -count. In js/app.js add at the end: querySelector for both elements, the condition if (element), addEventListener('input', function () { ... }) with textContent and value.length. No libraries, no arrow functions, no onclick in HTML. A comment on every line in Slovak. Leave the character limit as // DOPLŇ. Return both files whole.
Prompt B, the filter while typing. Attach web/js/app.js and web/content/ENTITY.php.
I attach js/app.js and a content file with a list from the database. Add a filter while typing. In the HTML add an input type text with the id search above the list and give every item of the list a class by which JavaScript finds it; keep the existing GET filter. In js/app.js add at the end: querySelector for the input, querySelectorAll for the items, the condition if (search), addEventListener('input', ...), inside it for (const ... of ...) with textContent.toLowerCase().includes(...) and classList.add / remove 'd-none'. No libraries, no arrow functions. A comment on every line in Slovak. Leave the name of the item class as // DOPLŇ. Return both files whole.
Prompt C, the question before deleting. Attach web/js/app.js, web/content/data.php and web/content/detail.php.
I attach js/app.js and content files with delete forms. Give every Zmazať button the attribute data-confirm with the text of the question; do not change the forms or their action. In js/app.js add at the end: querySelectorAll('button[data-confirm]'), for (const button of ...), addEventListener('click', function (event) { ... }); on the first click event.preventDefault(), button.dataset.asked = 'yes' and the text of the button from button.dataset.confirm; the second click submits the form. No alert or confirm, no arrow functions. A comment on every line in Slovak. Leave the text of the question as // DOPLŇ. Return the files whole.
Why the prompts are written this way:
- the attached
app.js: the AI adds to the end of one file and does not create another, - “no arrow functions”: the code uses the same notation as this page and can be defended,
- “no onclick in HTML”: JavaScript stays in
app.js, - “no alert or confirm”: nothing pops up on the page,
- “keep the existing GET filter” and “do not change the forms”: what worked in cv07 and cv08 keeps working without JavaScript,
// DOPLŇleaves the limit, the class name and the text of the question to the author of the application.
Common errors and what they mean
JavaScript errors are in the developer tools (F12, the Console tab), in red. With an error the page looks normal, only JavaScript does nothing.
| Message or symptom | Cause | Fix |
|---|---|---|
the Console has no app.js je pripojený |
<script src="js/app.js"> is missing in template.php, or the path is wrong |
the line before </body>; the file is in web/js/ |
GET .../js/app.js 404 |
the file has another name or is in another folder | web/js/app.js |
Cannot read properties of null (reading 'addEventListener') |
querySelector did not find the element: it is not on this page, or the id has a typo |
the condition if (element) from example 9; compare the id in the HTML with the selector |
after an error the rest of app.js does not work either |
JavaScript stops at the first error | fix the first red message in the Console |
Unexpected token or missing ) after argument list |
a bracket is missing, most often }); at the end of addEventListener |
count (, { and their closings |
a change in app.js has no effect |
the browser keeps the old version of the file in memory | reload the page with Ctrl+F5 |
| the button with the question submits the form immediately | event.preventDefault() or event in function (event) is missing |
add them following example 8 |
| the filter hides nothing | the items lack the class querySelectorAll looks for |
add the class to the HTML |
Úlohy na cvičenieLab tasks
Prijať zadanie cv10 v Classroom 50 (platí pre skupiny B. Stehlíkovej; ostatné skupiny dostanú link od svojho cvičiaceho).
Výsledkom cv10 je aplikácia z cv08 s file js/app.js. ENTITY je názov table svojej main entity.
11.1 Kubeflow: skontroluj rozšírenia (SFTP, Five Server, Intelephense). Ak chýbajú, spusti v termináli príkaz na obnovu z návodu 04 Odovzdávanie.
11.2 git clone repository cv10 a prekopíruj aplikáciu z cv08:
rsync -a --exclude .git --exclude README.md cv08/ cv10/
Commit.
11.3 web/js/app.js s komentárom o role a console.log, pripojený v template.php pred </body> (ukážka 1). Over v Console, že na každej stránke z menu je riadok app.js je pripojený. Commit.
11.4 Počítadlo znakov pri jednom input alebo textarea vo formulári add-ENTITY.php (ukážka 5, prompt A). Ak je ten istý element aj v edit-ENTITY.php, počítadlo funguje aj tam.
11.5 Filter pri písaní v ENTITY.php (ukážka 7, prompt B). Filter cez GET z cv07 zostáva. Commit.
11.6 Otázka pred zmazaním pri každom buttone Zmazať v data.php a detail.php (ukážka 8, prompt C). Over: prvé kliknutie nič nezmaže, druhé zmaže.
11.7 Podmienky if pre elementy, ktoré nie sú na každej stránke (ukážka 9). Otvor každú položku menu a over, že Console je bez červených hlášok. Commit.
11.8 V nástrojoch pre vývojárov vypni JavaScript (F12, Ctrl+Shift+P, napíš „Disable JavaScript”) a over, že pridanie, úprava aj zmazanie fungujú. Potom JavaScript znova zapni.
11.9 Poriadok v projekte: spusti python3 unify.py --check. Do mapy aplikácie v README.md doplň riadok pre web/js/app.js. V repository nie sú files, ktoré aplikácia nepoužíva.
11.10 Commit a push, aspoň 4 commity v rôznych krokoch. Upload Folder: cv10 do ti/cv10/ a obsah web/ do ti/projekt/. Over vo svojom webovom priestore na sigma.tuke.sk.
Voliteľné úlohy:
11.11 Časť formulára, ktorá sa zobrazí po zaškrtnutí checkboxu (ukážka 6).
11.12 Počet zobrazených položiek nad zoznamom, ktorý sa mení pri filtrovaní (vo vzore <span id="shown">).
11.13 Počítadlo, ktoré zmení farbu textu, keď zostáva menej ako 10 znakov (classList a Bootstrap class text-danger).
Hodnotenie: 1 bod. Aplikácia s js/app.js (počítadlo znakov, filter pri písaní, otázka pred zmazaním) funguje vo svojom webovom priestore na sigma.tuke.sk a funguje aj s vypnutým JavaScriptom, kód je v repository. Po push sa spustia testy (10 kontrol); zelený výsledok znamená, že files a požadované časti kódu sú na mieste, body udeľuje učiteľka.
Accept assignment cv10 in Classroom 50 (applies to B. Stehlíková’s groups; other groups get the link from their own teacher).
The result of cv10 is the application from cv08 with the file js/app.js. ENTITY is the name of the table of your main entity.
11.1 Kubeflow: check the extensions (SFTP, Five Server, Intelephense). If they are missing, run the restore command from the guide 04 Submitting in the terminal.
11.2 git clone the repository cv10 and copy the application from cv08:
rsync -a --exclude .git --exclude README.md cv08/ cv10/
Commit.
11.3 web/js/app.js with the comment about its role and console.log, included in template.php before </body> (example 1). Verify in the Console that every page from the menu shows the line app.js je pripojený. Commit.
11.4 A character counter for one input or textarea in the form of add-ENTITY.php (example 5, prompt A). If the same element is also in edit-ENTITY.php, the counter works there too.
11.5 A filter while typing in ENTITY.php (example 7, prompt B). The GET filter from cv07 stays. Commit.
11.6 A question before deleting for every Zmazať button in data.php and detail.php (example 8, prompt C). Verify: the first click deletes nothing, the second one deletes.
11.7 The if conditions for elements that are not on every page (example 9). Open every menu item and verify that the Console has no red messages. Commit.
11.8 In the developer tools switch JavaScript off (F12, Ctrl+Shift+P, type “Disable JavaScript”) and verify that adding, editing and deleting work. Then switch JavaScript back on.
11.9 Tidying the project: run python3 unify.py --check. Add a line for web/js/app.js to the map of the application in README.md. The repository holds no files the application does not use.
11.10 Commit and push, at least 4 commits at different steps. Upload Folder: cv10 to ti/cv10/ and the content of web/ to ti/projekt/. Verify in your web space on sigma.tuke.sk.
Optional tasks:
11.11 A part of the form that appears after checking a checkbox (example 6).
11.12 The number of shown items above the list, changing while filtering (in the sample <span id="shown">).
11.13 A counter that changes the colour of its text when fewer than 10 characters remain (classList and the Bootstrap class text-danger).
Grading: 1 point. The application with js/app.js (character counter, filter while typing, question before deleting) works in your web space on sigma.tuke.sk and also works with JavaScript switched off, and the code is in the repository. Tests run after the push (10 checks); a green result means the files and the required parts of the code are in place, points are awarded by the teacher.
Obhajoba a live codingDefence and live coding
Pred obhajobou kola 2 si odovzdaný stav skopíruješ: rsync -a --exclude .git cv10/ obhajoba2/ a Upload Folder. Live coding sa robí v obhajoba2, odovzdaný stav sa nedotkne. Pri obhajobe budú použité iba zverejnené otázky a úlohy.
Vysvetli (code walkthrough)
- Kde beží PHP a kde JavaScript; čo z nich vidí databázu.
- Kde je
js/app.jspripojený a prečo práve pred</body>. - Čo je
documenta čo znamená bodka vdocument.querySelector('#search').value. - Ako sa pozná property a ako method.
- Čo vráti
querySelectora čoquerySelectorAll; čo vrátiquerySelector, keď element na stránke nie je. - Čo je event; vymenuj eventy použité v
app.jsa povedz, kedy nastanú. - Kedy sa vykonajú riadky vo
function () { ... }vaddEventListener. - Prejdi riadok po riadku počítadlo znakov: odkiaľ je text, kam sa píše počet.
- Prejdi riadok po riadku filter pri písaní.
- Čím sa filter pri písaní líši od filtra cez GET z cv07.
- Čo robí
classList.add('d-none')a čo sa pri tom stane s elementom v HTML. - Čo robí
event.preventDefault()pri buttone Zmazať a čo by sa stalo bez neho. - Ako
app.jsrozpozná prvé a druhé kliknutie na button Zmazať. - Na čo je attribute
data-confirma ako sa číta v JavaScripte. - Prečo je v
app.jspodmienkaif (search). - Kde sa hľadajú chyby JavaScriptu.
- Čo sa stane s aplikáciou, keď je JavaScript vypnutý.
Uprav (live coding)
- Zmeň limit počítadla znakov.
- Zmeň text otázky pri jednom buttone Zmazať.
- Pridaj
data-confirmďalšiemu buttonu v aplikácii. - Zmeň placeholder inputu na hľadanie.
- Vypíš cez
console.logtext, ktorý používateľ píše do inputu na hľadanie. - Pridaj počítadlo k ďalšiemu inputu vo formulári.
- Zmeň filter tak, aby hľadal od troch napísaných znakov.
- Pridaj button, ktorý po kliknutí zobrazí a skryje jeden odsek na úvodnej stránke.
Zdôvodni (design decisions)
- Prečo kontrola v PHP zostáva, keď formulár kontroluje aj prehliadač.
- Prečo je JavaScript v jednom file a nie v HTML cez
onclick. - Prečo otázka pred zmazaním nie je vyskakovacie okno.
- Prečo zmenu vzhľadu pri prejdení myšou robí CSS a nie JavaScript.
- Kedy použiť filter pri písaní a kedy filter cez GET.
Definition of Done
web/js/app.jsmá komentár o role a je pripojený vtemplate.phppred</body>,- počítadlo znakov, filter pri písaní a otázka pred zmazaním fungujú,
- Console je na každej stránke bez červených hlášok,
- v HTML nie je
onclickani iný JavaScript, vapp.jsnie jealert, - s vypnutým JavaScriptom fungujú pridanie, úprava aj zmazanie,
python3 unify.py --checknevypíše nič na dokončenie, mapa vREADME.mdobsahujejs/app.js,- všetko vo webovom priestore na sigma.tuke.sk (
ti/cv10/ati/projekt/) a v repository s aspoň 4 commitmi.
Before the defence of round 2 you copy the submitted state: rsync -a --exclude .git cv10/ obhajoba2/ and Upload Folder. Live coding is done in obhajoba2, the submitted state is not touched. Only the published questions and tasks are used at the defence.
Explain (code walkthrough)
- Where PHP runs and where JavaScript runs; which of them sees the database.
- Where
js/app.jsis included and why right before</body>. - What
documentis and what the dot means indocument.querySelector('#search').value. - How to recognise a property and how a method.
- What
querySelectorreturns and whatquerySelectorAllreturns; whatquerySelectorreturns when the element is not on the page. - What an event is; name the events used in
app.jsand say when they happen. - When the lines in
function () { ... }inaddEventListenerare executed. - Go through the character counter line by line: where the text comes from, where the count is written.
- Go through the filter while typing line by line.
- How the filter while typing differs from the GET filter from cv07.
- What
classList.add('d-none')does and what happens to the element in the HTML. - What
event.preventDefault()does for the Zmazať button and what would happen without it. - How
app.jsrecognises the first and the second click on the Zmazať button. - What the attribute
data-confirmis for and how it is read in JavaScript. - Why
app.jshas the conditionif (search). - Where JavaScript errors are found.
- What happens to the application when JavaScript is switched off.
Modify (live coding)
- Change the limit of the character counter.
- Change the text of the question for one Zmazať button.
- Add
data-confirmto another button in the application. - Change the placeholder of the search input.
- Print with
console.logthe text the user types into the search input. - Add a counter to another input in the form.
- Change the filter so that it starts searching from three typed characters.
- Add a button that shows and hides one paragraph on the home page after a click.
Justify (design decisions)
- Why the check in PHP stays when the browser checks the form too.
- Why JavaScript is in one file and not in HTML through
onclick. - Why the question before deleting is not a pop-up window.
- Why changing the look on mouse-over is done by CSS and not by JavaScript.
- When to use a filter while typing and when a GET filter.
Definition of Done
web/js/app.jshas the comment about its role and is included intemplate.phpbefore</body>,- the character counter, the filter while typing and the question before deleting work,
- the Console has no red messages on any page,
- the HTML has no
onclickor other JavaScript,app.jshas noalert, - with JavaScript switched off, adding, editing and deleting work,
python3 unify.py --checkprints nothing to finish, the map inREADME.mdcontainsjs/app.js,- everything is in your web space on sigma.tuke.sk (
ti/cv10/andti/projekt/) and in the repository with at least 4 commits.