Keep it simple and stupid

HTML structure

Introduction

HTML is the standard language for web pages. HTML stands for Hyper Text Markup Language. As the name suggests, HTML is not a programming but a markup language, which helps defining the structure and role of content.

Syntax

HTML uses a system of tags to structure and present content on the web. Tags are enclosed in angle brackets, preceded by a forward slash when closing. All tags that contain text-based content or wrap other tags start with an opening <tag> and end with a closing </tag>. There are self-closing tags as well, like an image <img/> or a line break <br/>, since they can never have text content or child elements.

Tags can have attributes, which provide additional information about the element. Attributes are included within the opening tag and are written as name-value pairs. Some attributes do not require a value and can simply be written as their name, indicating a true value.

For example, the <img> tag for images typically includes the src attribute to specify the image source, and the alt attribute for alternative text:

<img src="image.jpg" alt="Description of image">

An example of an attribute without a value is the checked attribute in a checkbox input:

<input type="checkbox" checked>

HTML elements can also be nested within each other to create complex structures. Here is an example with a paragraph containing a link:

<p>This is a <a href="https://example.tld">link</a> inside a paragraph.</p>

Setup

The basic and mandatory structure of an HTML document includes the <!DOCTYPE html> declaration, which is not a tag but an instruction for the browser to interpret the current page as HTML 5, followed by the <html> element, which traditionally contains two main child elements: The <head> contains metadata, links to stylesheets, scripts, and other information that the browser uses to render the page. The <body> contains the (visual) content of the document. This structure already shows that tags can be nested (with some limitations).

<!DOCTYPE html>
<html>
	<head>
		<title>Title</title>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="stylesheet" href="styles.css">
	</head>
	<body>
		<main class="page__content">
			<!-- Content here -->
		</main>
	</body>
</html>

Content elements

Structure

Example
<header class="page__header">
	<!-- Site title -->
</header>
<nav class="page__menu">
	<!-- Main navigation -->
</nav>
<main class="page__content">
	<section>
		<article>
			<!-- Article content -->
		</article>
	</section>
	<aside>
		<!-- Sidebar content -->
	</aside>
</main>
<footer class="page__footer">
	<!-- Footer links -->
</footer>
Header

The <header> tag represents the introductory content or navigational aids for a section or the whole page. It contains headings, logos, search forms, or other introductory content and is typically used at the top of a page or section. It should not be nested within other headers, footers, or main elements.

Main

The <main> tag designates the primary content of the document related to the central topic, excluding any content that is repeated across documents, such as sidebars, navigation links, and footers. It should only be used once per page.

Nav

The <nav> tag is used to define a set of navigation links. It is intended for major block of navigation links and should be used for primary navigation sections, such as menus, tables of contents, or indexes.

Articles

The <article> tag represents a complete and self-contained piece of content that is intended to be independently distributable or reusable, such as a blog post, a news article, a forum post, or any other content item that could stand on its own. Each article should make sense when isolated from the rest of the content on the page.

Sections

The <section> tag represents a standalone section of content that forms part of a larger document, typically with a heading. It is used to group related content together and often includes its own heading. Sections are thematically related groupings and are appropriate when the content within the section is logically connected and could potentially be grouped in an outline format.

Aside

The <aside> tag represents a section of content that is tangentially related to the content around it. It is often used for sidebars, pull quotes, advertisements, or groups of navigation elements. Content inside an <aside> element should be related to the surrounding content but separate enough to be considered as an aside.

Footer

The <footer> tag represents the footer for its nearest sectioning content or sectioning root element. It typically contains information about the author, links to related documents, copyright data, and other metadata. Footers are used to provide additional information and links at the bottom of a page or section.

Divisions

The <div> tag is a generic container for flow content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. The tag is one of the most commonly used elements in HTML and can help to structure a webpage by grouping content logically.

Text

Headings

Define different levels of headings from <h1> to <h6> , used for section titles. The <h1> tag represents the main subject of the content and should typically be used only once per page. All other headings can be used multiple times — but when nesting content, it is logically recommended to always use the next level without skipping.

<h1>Main Subject</h1>
<h2>A Second level</h2>
<h2>B Second level</h2>
<h3>B 1 Third level</h3>
Paragraphs

The <p> tag represents a paragraph of text. It is used to structure blocks of text into paragraphs, providing semantic meaning to text content.

<p>This is a paragraph of text.</p>
Lists

The <ul> (unordered list) and <ol> (ordered list) tags represent lists of items. <li> (list item) tags are used within <ul> or <ol> to define each item in the list. Lists are used to group related items together, providing an organized structure to content.

<ul>
	<li>Item 1</li>
	<li>Item 2</li>
	<li>Item 3</li>
</ul>
Links

The <a> (anchor) tag is used to create hyperlinks. It is used with the href (Hypertext Reference) attribute to specify the URL (Uniform Resource Locator) of the page or resource to which the link points. Links are used to navigate between pages or sections within a page, and to open available services. The <a> tag can also have additional attributes to enrich the intended behavior of interaction, such as target (specifies where to open the linked document), rel (defines the relationship between the linked document and the current document), and title (provides additional information about the link).

<!-- External Link -->
<a href="https://example.tld/path">example.tld</a>

<!-- Internal Anchor Link -->
<a href="#section-1">Title of Section 1</a>

<!-- Mailto Basic -->
<a href="mailto:example@example.tld">Email me</a>

<!-- Open Email Client with Multiple Recipients -->
<a href="mailto:example1@example.tld,example2@example.tld">Email us</a>

<!-- Mailto with Subject and Body -->
<a href="mailto:example@example.tld?subject=Hello&body=Hi%20there!">Send Email</a>

<!-- Phone Link -->
<a href="tel:+1234567890">Call us</a>

<!-- SMS Link -->
<a href="sms:+1234567890">Send SMS</a>

<!-- Download Link -->
<a href="/path/to/file.zip" download>>Download File</a>

<!-- Link with Tooltip -->
<a href="https://example.tld/path" title="This is the tooltip">Tooltip on hover</a>

<!-- Link with Target Attribute -->
<a href="https://example.tld/path" target="_blank">Open in New Tab</a>

<!-- Link with Rel Attribute for Security -->
<a href="https://example.tld/path" target="_blank" rel="noopener noreferrer">Secure External Link</a>

<!-- Email Link with CC and BCC -->
<a href="mailto:example@example.tld?cc=cc@example.tld&bcc=bcc@example.tld">Email with CC and BCC</a>

<!-- FTP Link -->
<a href="ftp://ftp.example.tld/file.zip">Download via FTP</a>

<!-- File Protocol Link -->
<a href="file:///C:/path/to/file.txt">Open Local File</a>

<!-- Link with JavaScript -->
<a href="javascript:void(0);" onclick="alert('Hello World!');">Click for Alert</a>
																				
Bold

The <b> and <strong> tags are used to make text bold. The <b> tag is used for stylistic purposes, while <strong> indicates that the text is of strong importance.

<b>This text is bold.</b>
<strong>This text is strongly emphasized.</strong>
Italic

The <i> and <em> tags are used to make text italic. The <i> tag is used for stylistic purposes, while <em> indicates that the text has emphasized stress.

<i>This text is italic.</i>
<em>This text is emphasized.</em>
Span

The <span> tag is an inline container used to mark up a part of a text or a part of a document. It is often used with CSS to apply styles or with JavaScript to manipulate specific parts of the content.

<span class="uppercase">
	<span class="kern--TA">T</span>arget
</span>
Code

The <code> tag is used to define a piece of computer code. This element is usually displayed in the browser's default monospace font.

<code>let x = 5;</code>
Blockquote

The <blockquote> tag is used to define a section that is quoted from another source. It is typically displayed as an indented block of text. It can be used in combination with a <cite> tag to give appropriate credits

<blockquote>
		<p>This is a blockquote.</p>
</blockquote>

<!-- Complete Example -->
<figure>
	<blockquote>
		<p>This is a blockquote.</p>
	</blockquote>
	<figcaption>
		Quotation from <cite><a href="https://example.tld/source">Source Title</a></cite> by Author Name.
	</figcaption>
</figure>
Superscript and Subscript

The <sup> tag is used to define superscript text, and the <sub> tag is used to define subscript text.

<sup>Superscript</sup>
<sub>Subscript</sub>

Media

Images

The <img> tag is used to embed images in an HTML document. It is a self-closing tag that requires the src attribute to specify the image URL and the alt attribute for accessibility.

Additionally, you can use the width and height attributes to define the dimensions of the image. The loading attribute can be used to specify lazy loading.

<img src="image.jpg" alt="Description" width="600" height="400" loading="lazy">
Videos

The <video> tag is used to embed videos in an HTML document. It supports multiple video formats and can be customized with various attributes like controls for playback controls and the <source> element for specifying different video sources.

The tag also supports attributes such as muted   loop and poster . The muted attribute silences the video by default, while the loop attribute makes the video replay automatically after it finishes. The poster attribute specifies an image to be shown while the video is downloading, or until the user hits the play button.

<video controls>
	<source src="clip.mp4" type="video/mp4">
</video>

<!-- looped videos have to be muted to work with autoplay -->
<video autoplay loop muted poster="clip.png">
	<source src="clip.mp4" type="video/mp4">
	<source src="clip.ogg" type="video/ogg">
	Your browser does not support the video tag.
</video>
Audio

The <audio> tag is used to embed audio content in an HTML document. Similar to the <video> tag, it supports multiple audio formats and can be customized with attributes such as controls for playback controls and the <source> element for specifying different audio sources.

<audio controls>
	<source src="audio.mp3" type="audio/mpeg">
	Your browser does not support the audio element.
</audio>

CSS styling

Introduction

CSS (Cascading Style Sheets) is used to define the presentation of HTML or XML documents, controlling layout, appearance, and style across multiple web pages simultaneously. CSS applies styles to elements based on selectors targeting HTML elements, classes, IDs, or other attributes.

Syntax

CSS rules consist of selectors that specify which elements to style, and declarations that define the style rules using properties and values. Within a CSS rule, selectors identify elements, and declarations specify aspects such as color, size, or positioning.

selector {
	property: value;
}

Selectors

Basic Selectors

Selectors in CSS are patterns used to select the elements you want to style. The class selector selects elements with a specific class using .classname and the ID selector selects a single element with a specific ID using #idname.

You can combine multiple selectors to apply styles to elements that match all criteria using selector1.selector2. Additionally, you can apply the same styles to multiple selectors using selector1, selector2.

Attribute selectors select elements based on attribute values. For example, [href] selects elements with an href attribute, [data-template="value"] selects elements with a data-template attribute equal to "value", and [data-template^="value"] selects elements with a data-template attribute that starts with "value".

.example-class {
	color: blue;
}

#example-id {
	font-size: 1.5rem;
}

.button.primary {
	background-color: green;
}

h1, h2, h4 {
	margin-bottom: 1rem;
}

[data-template] {
	border: 1px solid red;
}

[data-template="example"] {
	border-color: blue;
}

[data-template^="start"] {
	border-color: green;
}

Combinators

Combinators in CSS are used to combine multiple selectors. The descendant combinator selects elements that are descendants of another element using ancestor descendant while the child combinator selects elements that are direct children of another element using parent > child.

The adjacent sibling combinator selects an element that is the next sibling of another element using previous + next and the general sibling combinator selects all elements that are siblings of a specified element using previous ~ siblings.

.container .item {
	color: red; /* all .item elements inside .container */
}

.container > .item {
	color: blue; /* all direct child .item elements of .container */
}

.item + .item {
	margin-top: 1rem; /* the next .item element after an .item */
}

.item ~ .item {
	color: green; /* all .item elements after an .item */
}

Pseudo-Classes

Pseudo-classes in CSS are used to define the special states of an element. The :hover pseudo-class selects an element when you mouse over it, and the :focus pseudo-class selects an element when it has focus.

The :nth-child() pseudo-class selects elements based on their position in a group of siblings, and the :not() pseudo-class selects elements that do not match a specified selector. Modern pseudo-classes like :is() :where() and :has() provide more powerful ways to select elements based on complex conditions.

a:hover {
	color: red;
}

input:focus {
	border-color: blue;
}

li:nth-child(2) {
	color: green;
}

div:not(.example) {
	background-color: yellow;
}

:is(h1, h2, h3) {
	margin-bottom: 1rem;
}

:where(.container) .item {
	padding: 1rem;
}

div:has(img) {
	border: 2px solid black;
}

Pseudo-Elements

Pseudo-elements in CSS are used to style specific parts of an element. The ::before pseudo-element inserts content before the content of an element, and the ::after pseudo-element inserts content after the content of an element.

The ::first-line pseudo-element styles the first line of a block-level element, and the ::first-letter pseudo-element styles the first letter of a block-level element.

p::before {
	content: "Note: ";
	font-weight: bold;
}

p::after {
	content: " (Read more)";
	font-style: italic;
}

p::first-line {
	font-weight: bold;
}

p::first-letter {
	font-size: 2em;
	float: left;
}

Rules

CSS at-rules are special instructions or conditional statements that can control how CSS is applied. The @import rule imports external style sheets, and the @media rule applies styles based on media queries.

The @font-face rule defines custom fonts, and the @keyframes rule specifies animations. Other at-rules like @supports can be used to apply styles based on feature support.

@import url("styles.css");

@media (max-width: 600px) {
	body {
		background-color: lightblue;
	}
}

@font-face {
	font-family: "MyFont";
	src: url("myfont.woff2") format("woff2");
}

@keyframes example {
	from { opacity: 0; }
	to { opacity: 1; }
}

div {
	animation: example 2s infinite;
}

Functions

CSS functions are used to perform calculations and manipulate values. The calc() function performs calculations to determine CSS property values, and the var() function inserts the value of CSS variable.

The url() function defines the location of a resource, and functions like rgb() rgba() hsl() and hsla() define colors using RGB or HSL color models.

.box {
	width: calc(100% - 2rem);
	background-color: var(--main-bg-color);
	background-image: url("background.jpg");
	color: rgba(255, 255, 255, 0.8);
}

:root {
	--main-bg-color: #ff6347;
}

Units

CSS units are used to define the size of various properties like width, height, padding, and margin. There are several types of units, each with its specific use case.

Absolute units such as px (pixels) are fixed and do not change with the viewport size. Relative units like em and rem (root em) are scalable based on the font size of the element or the root element respectively. Typographic units such as lh (line height), ex (x-height), cap (cap height), and ch (character width) relate to the font metrics.

Viewport units, including vw (viewport width), vh (viewport height), vmin (minimum of viewport width or height), and vmax (maximum of viewport width or height), are relative to the size of the viewport. Newer dynamic viewport units like dvh (dynamic viewport height) adapt to the actual visible area of the viewport, taking into account interface elements.

Percentage units are relative to the parent element's size, making them useful for responsive design. Other units like fr (fractional units) are used in CSS Grid layouts to allocate space proportionally.

.example {
	width: 50%; /* percentage relative to parent element */
	font-size: 1.5em; /* relative to the font size of the element */
	margin: 2rem; /* relative to the font size of the root element */
	line-height: 2lh; /* relative to the line height of the element */
	height: 100vh; /* relative to 100% of the viewport height */
	min-height: 100dvh; /* relative to 100% of the dynamic viewport height */
	padding: 1px; /* absolute pixel value */
	max-width: 80ch; /* relative to the width of the '0' character */
	border-width: 2ex; /* relative to the x-height of the font */
	grid-template-columns: 1fr 2fr; /* fractional units for grid layout */
}

Box model

Explanation

The CSS box model defines the rectangular boxes generated for elements in the document tree and their dimensions and spacing. The box model consists of the content area, padding, border, and margin.

Content is the actual content of the box, where text and images appear. padding defines the space between the content and the border, inside the element. border defines the edge of the box, surrounding the padding (if any) and content. margin defines the space outside the border and creates distance between the element and others.

Below is a visual representation of the box model, similar to how it is displayed in browser developer tools:

Position
Margin
Border
Padding
Content

Margins

Margins in CSS are used to create space around elements, outside of any borders. The margin property is a shorthand to set all sides in a specific order: top, right, bottom, left. It can accept one value to apply to all sides, two values for top/bottom left/right, three values for top left/right bottom, or four individual values for each side. Alternatively, margins can be set individually using properties such as margin-top.

Logical properties like margin-block and margin-inline adjust margins based on the writing mode of the document, making them adaptable to different languages and text directions. They can take either one or two values for start and end.

Margins can be set to positive or negative values, which can be useful for adjusting element positioning and spacing. Additionally, vertical margins of adjacent block-level elements may collapse, combining into a single margin that is equal to the largest individual margin.

.container {
	margin: 1rem 2rem; /* shorthand for margin top/bottom and left/right */
	margin-top: -1rem; /* Negative margin at the top of the element */
	margin-inline: 2rem; /* 2rem at start and end of block axis */
	margin-block: 0 1rem; /* 0 at start and 1rem at end of block axis */
	margin-block-start: 1rem; /* Margin at start of block axis */
	margin-inline-end: 2rem; /* Margin at end of inline axis */
}

Paddings

Paddings in CSS are used to create space within an element, between the content and its border. The padding property is a shorthand to set all sides in a specific order: top, right, bottom, left. It can accept one value to apply to all sides, two values for top/bottom and left/right, three values for top, left/right, and bottom, or four individual values for each side. Alternatively, paddings can be set individually using properties such as padding-top.

Logical properties like padding-block and padding-inline adjust paddings based on the writing mode of the document, making them adaptable to different languages and text directions. One value defines padding for start and end together, while two values define them separately.

Paddings can be set to any positive value, which can be useful for controlling the spacing within elements. Unlike margins, paddings do not collapse when adjacent block-level elements meet.

.container {
	padding: 1rem 2rem; /* shorthand for padding top/bottom and left/right */
	padding-top: 1rem; /* Padding at the top of the element */
	padding-inline: 2rem; /* 2rem at start and end of block axis */
	padding-block: 0 1rem; /* 0 at start and 1rem at end of block axis */
	padding-block-start: 1rem; /* Padding at start of block axis */
	padding-inline-end: 2rem; /* Padding at end of inline axis */
}

Borders

Borders in CSS are used to create a visible boundary around elements. The border property is a shorthand to set the width, style, and color of the border in a single declaration. Alternatively, each of these properties can be set individually using border-width border-style and border-color.

Specific sides of an element's border can also be styled individually using properties like border-bottom and border-bottom-style.

The border-radius property is used to round the corners of an element, even if the border is not visible.

.box {
	border: 1px solid #000; /* shorthand for border width, style, and color */
	border-width: 2px; /* sets the width of the border */
	border-style: dashed; /* sets the style of the border */
	border-color: #333; /* sets the color of the border */
	border-bottom: 2px solid #000; /* sets the border for the bottom side */
	border-bottom-style: dotted; /* sets the style of the bottom border */
	border-radius: 1rem; /* rounds the corners of the border */
	border-top-left-radius: 1rem; /* rounds the top left corner of the border */
}

Width & Height

Width and height properties in CSS are used to define the dimensions of an element. These properties can take various units, including percentages, viewport units, and special values. Common values include 100% to set the dimension relative to the parent element, 100vh to set the height relative to the viewport height, and auto to maintain intrinsic aspect ratios.

Special values like fit-content max-content and min-content adjust the size based on content. Intrinsic sizing values such as intrinsic and min-intrinsic can also be used to fit content naturally within the layout.

img {
	width: 100%; /* sets the width to 100% of the parent element */
	height: auto; /* maintains the intrinsic aspect ratio */
}

.container {
	width: fit-content; /* adjusts width to fit the content */
	max-width: max-content; /* sets the maximum width based on content */
	min-width: min-content; /* sets the minimum width based on content */
	height: 100vh; /* sets the height to 100% of the viewport height */
	max-height: 50vh; /* sets the maximum height to 50% of the viewport height */
}

Typography

Load Fonts

@font-face defines a custom font for use in a web page. It allows specifying various font characteristics and sources.

While all modern browsers support the revised Web Open Font File Format 2.0 woff2 with higher compression, it’s common practice to use woff as a fallback to broaden the range of supported browsers. Older formats like SVG are now considered obsolete and are rarely used.

Variable web fonts are an advancement in typography on the web. They allow a single font file to contain multiple styles and weights, offering greater flexibility and reduced file sizes compared to using multiple separate font files.

/* Variable font: */
@font-face {
	font-display: swap; /* Ensures text remains visible while custom font loads */
	font-family: Fontname; /* Name of the custom font family */
	font-style: oblique -12deg 0deg; /* Defines the available range of styles for the font */
	font-weight: 100 900; /* Defines the available range of weights for the font */
	src: url(../fonts/fontname.woff2) format("woff2"), /* URL and format of the font file */
		url(../fonts/fontname.woff) format("woff"), /* First fallback URL and format */
		url(../fonts/fontname.ttf) format("ttf"); /* Second fallback URL and format */
	}

/* Static font: */
@font-face {
	font-display: fallback; /* Immediate rendering with the fallback font while custom font loads */
	font-family: "Custom Font";
	font-style: normal;
	font-weight: normal;
	src: url(../fonts/fontname.woff2) format("woff2"),
		url(../fonts/fontname.woff) format("woff");
	unicode-range: U+000-5FF; /* Optional, limits the subset of characters displayed for defined family, next fallback of elements font-family stack is used for all other characters */
}

Family

font-family Specifies the typeface or font family used for text elements. You can chain multiple fonts as fallbacks.

body {
	font-family: "Custom Font", "Arial", sans-serif; /* Preferred font, fallback to Arial or generic sans-serif */
}

Feature Settings

font-feature-settings enable or disable specific OpenType features in the font, such as ligatures or alternate glyphs.

body {
	font-feature-settings: "liga" on, "dlig" on; /* Enables standard and discretionary ligatures */
}

Variation Settings

font-variation-settings controls the variation of a variable font, adjusting aspects like weight, width, slant, and other design axes.

body {
font-variation-settings:
	"wght" 500, /* Weight axis, value 500 */
	"wdth" 75%, /* Width axis, 75% of the full width */
	"slnt" -10; /* Slant axis, -10 degrees */
}

Size

font-size sets the size of the text relative to the default font size. Common units include: em (relative to the parent element), rem (relative to the root element), px (pixels), and % (percentage).

h1 {
	font-size: 2em; /* Relative size based on the parent element's font size */
}

Weight

Defines the thickness or boldness of the font. Common values include: 100 (Thin), 300 (Light), 400 (Regular), 500 (Medium), 700 (Bold), 900 (Heavy). Keywords like normal , bold and thin can also be used. Not all font families support all weights.

p {
	font-weight: 400; /* Regular font weight */
}

Style

Specifies the italicization of text. Values include normal italic and oblique.

em {
	font-style: italic; /* Renders text in italic */
}

Variant

Specifies variations in the appearance of fonts, such as converting lowercase letters to small capitals. Values include normal and small-caps.

p {
	font-variant: small-caps; /* Converts lowercase letters to small capitals */
}

Transform

Changes the capitalization of text. Values include uppercase lowercase capitalize and none.

h2 {
	text-transform: uppercase; /* Converts text to uppercase */
}

Spacing

letter-spacing controls the space between characters in text. It can be adjusted to improve readability or achieve a specific design effect.

word-spacing adjusts the space between words in text. Similar to letter spacing, it can be used for readability or design purposes.

h1 {
	letter-spacing: 0.5px; /* Example of setting letter spacing */
	word-spacing: -1px; /* Example of setting word spacing */
}

Line height

Sets the height of lines of text. It can be a unitless number, a percentage, or a specific length. A good practice is to set line-height slightly larger than the font-size to improve readability.

body {
	line-height: 1.5; /* Example of setting line height */
}

Text alignment

Controls the alignment of text within its container. Common values include left right center and justify.

p {
	text-align: center; /* Aligns text to the center */
}

Text decoration

Adds decorations to text, such as underline, overline, and line-through.

a {
	text-decoration: none; /* Removes underline from links */
}

JavaScript functionality

Introduction

JavaScript is a versatile programming language used primarily for creating dynamic and interactive content on web pages. It is one of the core technologies of the World Wide Web, alongside HTML and CSS. JavaScript enables developers to add functionality to websites, ranging from simple scripts to complex applications.

Unlike HTML and CSS which are markup and styling languages respectively, JavaScript is a full-fledged programming language. It is executed by web browsers on the client-side, meaning it runs locally on users' devices rather than on a remote server. This capability allows JavaScript to manipulate webpage elements, respond to user actions, and communicate asynchronously with servers to update content without reloading the entire page.

Core Concepts

Data Types

Strings

In JavaScript, strings are sequences of characters, enclosed within single quotes, double quotes, or backticks.

const greeting = 'Hello';
const name = "John";
const message = `Welcome, ${name}!`;

Variables greeting name and message demonstrate different ways to define and use strings in JavaScript.

Arrays

Arrays in JavaScript are ordered collections of values, which can be of any data type.

const numbers = [1, 2, 3, 4, 5];
const fruits = ['apple', 'banana', 'orange'];

Examples numbers and fruits demonstrate how to define and access elements in arrays.

Objects

Objects in JavaScript are collections of key-value pairs, where keys are strings and values can be any data type.

const person = {
	firstName: 'John',
	lastName: 'Doe',
	age: 30,
	hobbies: ['reading', 'coding']
};

Example person demonstrates how to define and access properties of an object.

Functions

One of the core concepts in JavaScript is the function, which is a block of code designed to perform a specific task. The structure for defining JavaScript functions involves using the function keyword, followed by a name for the function, parentheses () and a block of code enclosed in curly braces {}. The function can then be called or invoked to execute the code within it.

JavaScript also supports anonymous functions, which are functions without a name. These are often used as arguments to other functions or as immediately invoked function expressions (IIFE). An IIFE is a function that runs as soon as it is defined.

Another modern way to define functions in JavaScript is using arrow functions, introduced in ES6. Arrow functions allow for a shorter syntax and do not have their own this context. They are particularly useful for concise function expressions.

JavaScript also supports function expressions, where functions can be assigned to variables. These can be named or anonymous, and they are useful for passing functions as arguments to other functions.

In addition to these, JavaScript has generator functions, which can pause execution and yield multiple values using the function* syntax. These functions can be iterated over using the next() method.

function myFunction() {
    // code to be executed
}

const anonymousFunction = function() {
    // code to be executed
};

(function() {
    // code to be executed immediately
})();

const arrowFunction = () => {
    // code to be executed
};

function* generatorFunction() {
    yield 'first value';
    yield 'second value';
}

// Calling the functions
myFunction();
anonymousFunction();
arrowFunction();

const gen = generatorFunction();
console.log(gen.next().value); // 'first value'
console.log(gen.next().value); // 'second value'

Conditionals

If Else

if else andelse if statements are used to execute code based on conditions.

const x = 10;
if (x >= 5) {
	console.log("x is greater than or equals 5");
} else if (x > 0 && x < 5) {
	console.log("x is bigger then 0 and smaller than 5");
} else {
	console.log("x is not a number or smaller then 0");
}

In this example, since x is 10, the console logs "x is greater than or equals 5".

Switch

The switch statement is used to perform different actions based on different conditions.

const fruit = "apple";
switch (fruit) {
	case "banana":
		console.log("Banana is selected");
		break;
	case "apple":
		console.log("Apple is selected");
		break;
	default:
		console.log("No fruit selected");
}

This example checks the value of fruit and logs "Apple is selected" since the value is "apple", afterwards break is used to stop further processing, since the case is fullfilled.

Ternary Operator

The ternary operator is a shorthand for the if else statement.

const age = 18;
const canVote = age >= 18 ? "Yes" : "No";
console.log(canVote); // Logs "Yes"

This example uses the ternary operator to check if age is 18 or older and sets canVote accordingly.

Loops

For

A for loop is used when you know how many times you want to repeat a block of code.

for (let i = 0; i < 5; i++) {
	console.log(i);
}

In this example, the loop runs 5 times (i starts at 0, increments by 1 each iteration until it's less than 5).

forEach

forEach is used to iterate over elements of an array. It executes a provided function once for each array element.

const array = [1, 2, 3];
array.forEach(element => {
	console.log(element);
});

This loop logs each element of the array (1, 2, 3) to the console.

While

A while loop repeats a block of code while a specified condition is true.

let i = 0;
while (i < 5) {
	console.log(i);
	i++;
}

This loop logs values of i (0 to 4) until i is no longer less than 5.

Do While

A do while loop is similar to a while loop, but it executes the block of code once before checking the condition.

let i = 0;
do {
	console.log(i);
	i++;
} while (i < 5);

This loop logs values of i (0 to 4) until i is no longer less than 5, but guarantees at least one execution.

For Of

The for...of loop iterates over iterable objects (like arrays).

const array = [1, 2, 3];
for (const element of array) {
	console.log(element);
}

This loop logs each element of the array (1, 2, 3) to the console.

For In

The for...in loop iterates over the enumerable properties of an object.

const object = {a: 1, b: 2, c: 3};
for (const key in object) {
	console.log(key + ": " + object[key]);
}

This loop logs each property of the object ("a: 1", "b: 2", "c: 3") to the console.

Continue

The continue statement skips the current iteration of a loop and proceeds to the next iteration.

// This loop logs 0, 1, 3, and 4, skipping 2:
for (let i = 0; i < 5; i++) {
	if (i === 2) continue;
	console.log(i);
}

Break

The break statement exits the loop immediately.

// This loop logs 0 and 1, then exits:
for (let i = 0; i < 5; i++) {
	if (i === 2) break;
	console.log(i);
}

DOM Manipulation

Getting Elements

The Document Object Model (DOM) is a representation of the HTML structure of a webpage, allowing JavaScript to interact with and manipulate the content. To modify an element, you first need to select it. One common way to do this is by using the document.getElementById method, which selects an element by its unique ID.

You can also select elements by their class name using the document.getElementsByClassName method, which returns a collection of all elements with the specified class name.

Another method is document.querySelector which selects the first element that matches a specified CSS selector, and document.querySelectorAll which returns a collection of all elements that match the specified CSS selector.

// Getting an element by its ID
const elementById = document.getElementById("myElement");

// Getting elements by their class name
const elementsByClassName = document.getElementsByClassName("myClass");

// Getting the first element that matches a CSS selector
const firstElementBySelector = document.querySelector(".myClass");

// Getting all elements that match a CSS selector
const allElementsBySelector = firstElementBySelector.querySelectorAll(".myClass"); // select all elements of class myClass inside firstElementBySelector element

In the code example, you might notice the use of the const keyword. const is used to declare variables that are constant and cannot be reassigned. For variables that might be reassigned, you can use let. Both const and let are block-scoped, meaning they are only accessible within the block they are defined. For defining variables in older JavaScript code, you might see var which is function-scoped and can be reassigned.

Changing Content

Once you have selected an element, you can change its content using the innerHTML property. This allows you to set new HTML or text content inside the selected element.

element.innerHTML = "New content";

Adding Event Listeners

To make your web pages interactive, you can add event listeners to elements. An event listener waits for a specific event, such as a click, to occur on the element, and then executes a function in response. The addEventListener method is used to attach an event listener to an element.

// Click event: Triggered when an element is clicked.
element.addEventListener("click", function() {
	alert("Element clicked!");
});

// Mouseover event: Triggered when the mouse pointer is moved over an element.
element.addEventListener("mouseover", function() {
	element.style.backgroundColor = "yellow";
});

// Mouseout event: Triggered when the mouse pointer is moved out of an element.
element.addEventListener("mouseout", function() {
	element.style.backgroundColor = "";
});

// Keydown event: Triggered when a key is pressed down.
document.addEventListener("keydown", function(event) {
	console.log("Key pressed: " + event.key);
});

// Keyup event: Triggered when a key is released.
document.addEventListener("keyup", function(event) {
	console.log("Key released: " + event.key);
});

Resources and tools

To get a basic understanding of Hypertext Markup Language (HTML) , Cascading Style Sheets (CSS) and Javascript (JS) there are tons of resources available in the world wide web. Here are two popular resources to start with:

There are also some free courses on learning platforms like CodeCadamy or SuperHi:

How you are going to code is up to you, but for a fast workflow we suggest to use Visual Studio Code with Live Preview extension:

To create reduced prototypes or to experiment, you can use online editors like Codepen:

Visually build and understand CSS Flexbox:

Visually build and understand CSS Grid:

A basic tutorial about variable web fonts:

Test and play with variable fonts:

Native scroll driven animations (highly experimental, Chrome only):

To check if a feature is available across all browsers and versions: