AltSchool Of Engineering Tinyuka’24 Month 5 Week 3


Kindly see the revision of the previous class here. This week, we delved into Generators and Async Iterators and much more! Join me as we explore these fascinating concepts together!
Generators and Async Iterators
Generators are a special type of function in JavaScript that can pause execution and yield values using the yield keyword. This allows developers to create iterable sequences on demand. For example:
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = numberGenerator();
console.log(gen.next().value); // Outputs: 1
Async iterators build on this concept, enabling asynchronous iteration over data sources, such as API responses. They use the for await...of syntax to handle asynchronous data flow smoothly:
async function* asyncNumberGenerator() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
}
(async () => {
for await (const num of asyncNumberGenerator()) {
console.log(num); // Outputs: 1, then 2
}
})();
Proxy and Reflect
The Proxy object in JavaScript allows for the creation of a proxy for another object, enabling the interception and customization of operations such as property access, assignment, and function invocation. For instance:
const target = {};
const handler = {
get: (obj, prop) => {
return prop in obj ? obj[prop] : 'Property not found';
}
};
const proxy = new Proxy(target, handler);
console.log(proxy.someProperty); // Outputs: Property not found
The Reflect API complements Proxy by providing methods for common object operations, allowing for better handling of these operations. For example, Reflect.get() can be used to retrieve a property:
Reflect.set(target, 'name', 'Alice');
console.log(Reflect.get(target, 'name')); // Outputs: Alice
Eval: Running a Code String
The eval()
function is a powerful tool that executes a string of JavaScript code in the current context. While it can be useful for dynamic code execution, it should be used cautiously due to security risks and performance issues. For example:
const x = 10;
const result = eval('x + 5');
console.log(result); // Outputs: 15
Document and the DOM Tree
The Document Object Model (DOM) represents the structure of a web page as a tree of nodes. Each node corresponds to elements, attributes, and text in the HTML document. Understanding this hierarchy is essential for effective manipulation of web pages.
Walking the DOM
Walking the DOM refers to traversing this tree structure to access and manipulate various elements. For instance, you can navigate through parent, child, and sibling nodes using properties like parentNode, childNodes, and nextSibling.
Searching for Elements
To find elements within the DOM, you can use methods such as getElementById()
, getElementsByClassName()
, or getElementsByTagName()
. Alternatively, querySelector()
and querySelectorAll()
provide a more flexible way to select elements using CSS selectors:
const element = document.querySelector('.my-class'); // Selects the first element with class "my-class"
Node Properties
Nodes in the DOM have various properties, including nodeType, tagName, and textContent, which provide information about the type of node, its tag, and its contents. For example:
const header = document.querySelector('h1');
console.log(header.tagName); // Outputs: H1
console.log(header.textContent); // Outputs: The content of the H1
Attributes and Properties
Elements have attributes (like id, class, and src) that can be accessed and modified using methods like getAttribute()
and setAttribute()
. Additionally, properties like className and value can be directly manipulated:
const link = document.querySelector('a');
link.setAttribute('href', 'https://example.com');
console.log(link.href); // Outputs: https://example.com
Modifying the Document
You can create, remove, or alter elements in the DOM. For example, to add a new paragraph:
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';
document.body.appendChild(newParagraph);
Styles and Classes
CSS styles can be modified using the style property or by adding/removing classes with classList. This allows dynamic changes to the appearance of elements:
const box = document.querySelector('.box');
box.style.backgroundColor = 'blue'; // Changes background color
box.classList.add('active'); // Adds a class
Element Size and Scrolling
You can measure the size of elements using properties like offsetHeight and offsetWidth. Scrolling can also be controlled using scrollTop and scrollLeft to manage the viewport:
const scrollElement = document.querySelector('.scrollable');
scrollElement.scrollTop = 100; // Scrolls down 100 pixels
Window Sizes and Scrolling
The window object provides properties like innerHeight and innerWidth to determine the size of the viewport. Additionally, you can listen for scroll events to execute functions based on user actions:
window.addEventListener('scroll', () => {
console.log(window.scrollY); // Outputs the current vertical scroll position
});
Coordinates
To obtain the position of elements relative to the viewport, you can use methods like getBoundingClientRect()
, which returns the size of an element and its position relative to the viewport:
const rect = header.getBoundingClientRect();
console.log(rect.top, rect.left); // Outputs the coordinates of the header
Understanding Events
In JavaScript, events are actions or occurrences that happen in the browser, such as user interactions (clicks, keyboard input) or changes in the state of the document. Events allow developers to create dynamic and interactive web applications.
Basic Concepts
Events can be triggered by various actions. For example, a button click can be captured with an event listener:
const button = document.querySelector('button');
button.addEventListener('click', () => {
alert('Button was clicked!');
});
Bubbling and Capturing
Events in the DOM can propagate in two phases: bubbling and capturing.
Bubbling: The event starts from the target element and bubbles up to its ancestors. For example, if you click a button inside a div, the click event will trigger on the button first, then on the div.
Capturing: The event starts from the root and goes down to the target element. You can enable capturing by passing true as the third argument in
addEventListener()
:
document.querySelector('div').addEventListener('click', () => {
console.log('Div clicked (capturing phase)');
}, true);
Event Delegation
Event delegation is a technique where a single event listener is added to a parent element instead of multiple listeners for each child. This method improves performance and simplifies event management. For instance, if you have a list of items:
const list = document.querySelector('ul');
list.addEventListener('click', (event) => {
if (event.target.tagName === 'LI') {
console.log(`Item clicked: ${event.target.textContent}`);
}
});
Browser Default Actions
Many events have default actions associated with them. For example, clicking on a link typically navigates to another page. You can prevent these default actions using event.preventDefault()
:
const link = document.querySelector('a');
link.addEventListener('click', (event) => {
event.preventDefault(); // Prevents navigation
console.log('Link clicked, but no navigation occurred.');
});
Dispatching Custom Events
You can create and dispatch custom events to trigger specific behaviors in your application. This is useful for implementing complex interactions. Here’s how to create and dispatch a custom event:
const customEvent = new Event('myCustomEvent');
document.addEventListener('myCustomEvent', () => {
console.log('Custom event triggered!');
});
document.dispatchEvent(customEvent); // Triggers the custom event
Understanding UI Events
UI events in JavaScript allow developers to respond to user interactions with graphical elements on the screen. These events include mouse movements, keyboard actions, and scrolling, which are essential for creating interactive web applications.
Mouse Events
Mouse events are triggered by user actions involving the mouse. Common mouse events include:
mouseover: Fired when the mouse pointer enters an element.
mouseout: Fired when the mouse pointer leaves an element.
mouseenter: Similar to mouseover, but does not bubble and only triggers when entering the element itself.
mouseleave: Similar to mouseout, but does not bubble and only triggers when leaving the element itself.
Example:
const box = document.querySelector('.box');
box.addEventListener('mouseover', () => {
box.style.backgroundColor = 'lightblue';
});
box.addEventListener('mouseout', () => {
box.style.backgroundColor = '';
});
Drag and Drop with Mouse Events
Drag and drop functionality can be implemented using mouse events, allowing users to move elements around the page. You typically use mousedown, mousemove, and mouseup events to handle the dragging process.
Example:
const draggable = document.querySelector('.draggable');
draggable.addEventListener('mousedown', (event) => {
const offsetX = event.clientX - draggable.getBoundingClientRect().left;
const offsetY = event.clientY - draggable.getBoundingClientRect().top;
const onMouseMove = (event) => {
draggable.style.left = ${event.clientX - offsetX}px;
draggable.style.top = ${event.clientY - offsetY}px;
};
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', () => {
document.removeEventListener('mousemove', onMouseMove);
}, { once: true });
});
Pointer Events
Pointer events are a unified way to handle input from various devices, including mouse, touch, and pen. They include events like pointerdown, pointermove, and pointerup, allowing for more flexible interaction handling.
Example:
const element = document.querySelector('.element');
element.addEventListener('pointerdown', (event) => {
console.log(`Pointer down at ${event.clientX}, ${event.clientY}`);
});
Keyboard Events
Keyboard events are triggered by user actions on the keyboard. The two primary keyboard events are keydown and keyup. keydown is fired when a key is pressed, and keyup is fired when the key is released.
Example:
document.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
console.log('Enter key was pressed');
}
});
Scrolling Events
Scrolling events occur when the user scrolls the page or an element. You can listen for the scroll event to execute specific functions based on the scroll position.
Example:
window.addEventListener('scroll', () => {
console.log(`Scroll position: ${window.scrollY}`);
});
Understanding Forms and Controls
Forms are essential elements in web applications, allowing users to input and submit data. JavaScript provides various properties and methods to interact with form elements effectively, enhancing user experience and functionality.
Form Properties and Methods
Forms have a range of properties like elements, which returns a collection of all form controls, and methods such as reset()
to clear the form fields. For example:
const form = document.querySelector('form');
form.reset(); // Resets all fields in the form
Focusing: focus and blur
The focus and blur methods are used to manage the focus state of form controls. focus()
sets the focus on an element, while blur()
removes it.
const inputField = document.querySelector('input');
inputField.focus(); // Sets focus on the input field
inputField.blur(); // Removes focus from the input field
Event Handling
Forms generate various events that can be utilized for handling user interactions:
change: Triggered when the value of a form control changes.
input: Fired immediately when the value of an input field changes.
cut, copy, paste: Triggered during clipboard operations.
Example:
inputField.addEventListener('input', () => {
console.log('Input changed to: ', inputField.value);
});
Form Submission
Form submission can be handled through the submit event and the submit()
method. This allows you to prevent default submission behavior if necessary.
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevents the default form submission
console.log('Form submitted with data: ', new FormData(form));
});
Form Validation
HTML provides built-in validation through attributes like required, minlength, and pattern. The novalidate attribute can be used to disable default validation, while the Constraint Validation API allows for more programmatic control over validation logic.
Example:
<form novalidate>
<input type="text" required minlength="5">
<button type="submit">Submit</button>
</form>
Form Elements
Common form elements include:
input: For various types of user input (text, email, password).
select: Dropdown lists for selecting options.
textarea: Multi-line text input.
button: Triggers actions.
label: Associates text with form controls.
fieldset: Groups related controls.
legend: Provides a caption for a fieldset.
Example:
<form>
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name:</label>
<input type="text" id="name" required>
<label for="age">Age:</label>
<input type="number" id="age">
<button type="submit">Submit</button>
</fieldset>
</form>
Forms are vital for user interaction in web applications. By understanding form properties, methods, focusing techniques, event handling, validation, and various form elements, developers can create efficient and user-friendly forms that enhance data collection and user experience.
I’m Ikoh Sylva, a passionate cloud computing enthusiast with hands-on experience in AWS. I’m documenting my cloud journey from a beginner’s perspective, aiming to inspire others along the way.
If you find my content helpful, please like and follow my posts, and consider sharing this article with anyone starting their own cloud journey.
Let’s connect on social media. I’d love to engage and exchange ideas with you!
Subscribe to my newsletter
Read articles from Ikoh Sylva directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ikoh Sylva
Ikoh Sylva
I'm a Mobile and African Tech Enthusiast with a large focus on Cloud Technology (AWS)