JavaScript in the browser

JavaScript in the browser

APIs that are available in the browser:

Examples in the browser console

DOM:

document.querySelector("body").textContent = "hello world";

HTML APIs:

alert('hello world');
setTimeout(() => {
  console.log('3 seconds have passed');
}, 3000);

Including JavaScript in HTML documents

Including JavaScript in HTML documents

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>

Meaning of type="module"

"older" version of including JS:

<script></script>

"modern" version:

<script type="module"></script>

Meaning of type="module"

effects of using type="module":

  • JS is only executed once the HTML document has fully loaded and is ready (JS is execution is "deferred")
  • JS is executed in "strict mode" (e.g. forbids undeclared variables)
  • import / export functionality is enabled

Document Object Model

Document Object Model

DOM (Document Object Model) = JavaScript API for accessing and manipulating the HTML content of a page

Document Object Model

DOM functionalities:

  • Finding (Querying) HTML elements
  • Modifying HTML elements (text content, attributes)
  • Creating and adding HTML elements
  • Responding to events (e.g., click)

DOM: Querying elements

DOM: Querying elements

Querying HTML elements:

  • document.getElementById()
  • document.getElementsByClassName()
  • document.getElementsByTagName()
  • document.querySelector()
  • document.querySelectorAll()
  • ...

DOM: Querying elements

<div id="chat-popup">...</div>

Accessing the DOM element:

let element = document.getElementById("chat-popup");

equivalent:

let element = document.querySelector("#chat-popup");

DOM: Querying elements

querying multiple elements:

let inputElements = document.querySelectorAll("input");

DOM: Modifying elements

DOM: Modifying elements

topics:

  • modifying text content of an element
  • modifying attributes of an element

Modifying text content

  • element.textContent = ...
  • element.innerText = ...

these two properties have similar functionalities

Modifying text content

example: replacing the HTML body content with the text "hello world"

let body = document.querySelector('body');

body.textContent = 'hello world';

Accessing Attributes

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"

HTML Attributes and JS Properties

With some HTML attributes, the corresponding JS property is different:

  • different data type (attributes are always strings)
  • different name

HTML Attributes and JS Properties

attribute:

checkbox.setAttribute('checked', '');
checkbox.removeAttribute('checked');

DOM property:

checkbox.checked = true;
checkbox.checked = false;

HTML Attributes and JS Properties

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';

HTML Attributes and JS Properties

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');

DOM: Creating and appending content

DOM: Creating and appending content

  • document.createElement()
  • element1.append(...)
  • element.remove()
  • element.innerHTML

Creating and appending content

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)

Creating and appending content

previous example with innerHTML:

let p = document.createElement('p');
p.innerHTML =
  'I\'m learning <a href="https://example.com">JavaScript</a>.';

Creating and appending content

Why not always use innerHTML?

  • can be subject to attacks (malicious code injection / XSS)
  • event listeners cannot be added

Dangers of using innerHTML

Using innerHTML is dangerous when content can be generated by users.

example: a malicious user has registered to our website with these data:

  • first name: John
  • last name: Doe
  • nickname: <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.

Dangers of using innerHTML

ways to prevent malicious code injection attacks:

avoid innerHTML

or

"escape" user-submitted content

Dangers of using innerHTML

"escaping" content:

user-submitted string: <script>...</script>

escaped string with HTML entities: &lt;script&gt;...&lt;/script&gt;

Exercises

  • create a chess board
  • display a static todo list

DOM: Events

DOM: Events

Wir können auf Benutzerinteraktionen und andere Ereignisse reagieren, z.B.:

  • Klicken / Drücken auf ein Element
  • Bewegen der Maus über ein Element
  • Eingabe in ein Eingabefeld
  • Absenden eines Formulars
  • ...

DOM: Events

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');
});

DOM: Events

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);

DOM: Events

Eventnamen:

  • click (kann durch jedes HTML-Element ausgelöst werden)
  • input (wird ausgelöst, wenn der Wert eines Eingabefelds geändert wird)
  • submit (für Formulare)
  • mouseenter (wenn der Mauszeiger in ein Element hinein bewegt wird)
  • ...

Siehe https://www.w3schools.com/jsref/dom_obj_event.asp für eine ausführliche Liste

DOM: Events

Ãœ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

DOM: Event-Objekte

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

DOM: Events

Beispiele:

  • Spiel: click the box

DOM: Formulare und Formularereignisse

Beispiel: Todo-Liste

Web components

Web components

Web components can be created via JavaScript and used like regular HTML elements

Web components

example: footer that can be used on multiple pages

<my-footer></my-footer>

Web components

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>

Web components

example: map view with various configuration options

<my-map-view lat="48.2" lon="17.5" zoom="8"></my-map-view>

Web components

example: email list

<my-email-list>
  <my-email from="..." to="..." title="..."></my-email>
  <my-email from="..." to="..." title="..."></my-email>
</my-email-list>

Web components: functionalities

relatively easy to implement:

  • custom, scoped styling
  • passing content to elements (slots)
  • passing data via static properties
  • custom events (e.g. custom button press, value change, other interactions)

more complicated (without additional tooling):

  • components that change over time (e.g. because of changing properties or user interactions)

Debugging in the browser

Debugging in the browser

debugger statement

Debugging in the browser

breakpoints:

  • setting breakpoints
  • activating / deactivating breakpoints

Debugging in the browser

continuing manually:

  • play / pause
  • step over: go to next line
  • step into: follow a function call
  • step out: leave the current function call

Debugging in the browser

watching variables

Ãœbungen

  • Lottery number generator
  • clock
  • todo list
  • chess board
  • chat view