APIs that are available in the browser:
alert
, setTimeout
, ...)DOM:
document.querySelector("body").textContent = "hello world";
HTML APIs:
alert('hello world');
setTimeout(() => {
console.log('3 seconds have passed');
}, 3000);
possibilities:
internally, within the HTML code:
<script type="module">
console.log('hello world');
</script>
externally, in a separate file:
<script src="main.js" type="module"></script>
"older" version of including JS:
<script></script>
"modern" version:
<script type="module"></script>
effects of using type="module"
:
DOM (Document Object Model) = JavaScript API for accessing and manipulating the HTML content of a page
DOM functionalities:
Querying HTML elements:
document.getElementById()
document.getElementsByClassName()
document.getElementsByTagName()
document.querySelector()
document.querySelectorAll()
<div id="chat-popup">...</div>
Accessing the DOM element:
let element = document.getElementById("chat-popup");
equivalent:
let element = document.querySelector("#chat-popup");
querying multiple elements:
let inputElements = document.querySelectorAll("input");
topics:
element.textContent = ...
element.innerText = ...
these two properties have similar functionalities
example: replacing the HTML body content with the text "hello world"
let body = document.querySelector('body');
body.textContent = 'hello world';
Accessing attributes: via getAttribute
and setAttribute
or via JS properties of the same name
HTML example:
<a href="https://example.com">example</a>
Accessing the attribute in JS:
exampleLink.getAttribute("href")
exampleLink.setAttribute("href", "https://xyz.com")
exampleLink.href
exampleLink.href = "https://xyz.com"
With some HTML attributes, the corresponding JS property is different:
attribute:
checkbox.setAttribute('checked', '');
checkbox.removeAttribute('checked');
DOM property:
checkbox.checked = true;
checkbox.checked = false;
The style
attribute is a string, the style
property is an object:
element.setAttribute(
'style',
'color: #99aaff; padding: 4px;'
);
element.style.color = '#99aaff';
element.style.padding = '4px';
The class
attribute can be manipulated via the className
and classList
properties.
element.setAttribute('class', 'btn btn-primary');
element.className = 'btn btn-primary';
element.classList.add('important');
document.createElement()
element1.append(...)
element.remove()
element.innerHTML
Example: creating a paragraph with a link
<p>
I'm learning <a href="https://example.com">JavaScript</a>.
</p>
let p = document.createElement('p');
let link = document.createElement('a');
link.href = 'https://example.com';
link.innerText = 'JavaScript';
p.append("I'm learning ", link, ".");
the new element (p
) can be appended to an existing element (e.g. the document body)
previous example with innerHTML
:
let p = document.createElement('p');
p.innerHTML =
'I\'m learning <a href="https://example.com">JavaScript</a>.';
Why not always use innerHTML
?
Using innerHTML
is dangerous when content can be generated by users.
example: a malicious user has registered to our website with these data:
John
Doe
<script>prompt("Enter your credit card number:")</script>
If we use innerHTML
to display the nickname to other users, the script will be executed in their browsers.
Note: using innerText
is not dangerous.
ways to prevent malicious code injection attacks:
avoid innerHTML
or
"escape" user-submitted content
"escaping" content:
user-submitted string: <script>...</script>
escaped string with HTML entities: <script>...</script>
Wir können auf Benutzerinteraktionen und andere Ereignisse reagieren, z.B.:
Wir können Funktionen als "Event-Listener" hinzufügen:
let button = document.querySelector('#my-button');
button.addEventListener('click', () => {
console.log('click event triggered on button');
});
Beispiel: Klickzähler - Anzeigen einer Zahl in einem div, die bei jedem Klick auf einen Button erhöht wird
let counterDisplay = document.createElement('div');
counterDisplay.textContent = '0';
let counterButton = document.createElement('button');
counterButton.textContent = 'erhöhen';
counterButton.addEventListener('click', () => {
counterDisplay.textContent =
Number(counterDisplay.textContent) + 1;
});
document
.querySelector('body')
.append(counterDisplay, counterButton);
Eventnamen:
Siehe https://www.w3schools.com/jsref/dom_obj_event.asp für eine ausführliche Liste
Ãœbung: Erstelle eine HTML-Datei mit verschiedenen Elementen, die Event-Listener haben. Wenn ein Event auftritt, logge es in die Konsole.
Beispielausgabe in der Konsole:
button1: mouseenter
button1: click
button1: mouseleave
textbox1: mouseenter
textbox1: click
textbox1: input
textbox1: input
textbox1: mouseleave
Wenn ein Event auftritt, können wir in JavaScript auf das entsprechende Event
-Objekt zugreifen:
myButton.addEventListener('click', (event) => {
console.log('myButton was clicked');
console.log('mouse button:', event.button);
console.log('coordinates:', event.clientX, event.clientY);
});
Beispiele:
Beispiel: Todo-Liste
Web components can be created via JavaScript and used like regular HTML elements
example: footer that can be used on multiple pages
<my-footer></my-footer>
example: elements that form a navbar
<my-navbar>
<my-logo></my-logo>
<my-navbar-item>
<a href="...">Home</a>
</my-navbar-item>
<my-navbar-item>
<a href="...">About</a>
</my-navbar-item>
</my-navbar>
example: map view with various configuration options
<my-map-view lat="48.2" lon="17.5" zoom="8"></my-map-view>
example: email list
<my-email-list>
<my-email from="..." to="..." title="..."></my-email>
<my-email from="..." to="..." title="..."></my-email>
</my-email-list>
relatively easy to implement:
more complicated (without additional tooling):
debugger
statement
breakpoints:
continuing manually:
watching variables