DEV Community

Whoissosick
Whoissosick

Posted on

Working with the DOM, Click Events, and Web APIs

What Is an API, and What Are Web APIs?

These types of APIs are often divided into two main categories: browser APIs and third-party APIs.

Browser APIs expose data from the browser. As a web developer, you can access and manipulate this data using JavaScript.

They also provide access to various functionalities, such as manipulating the structure of the website, handling events, working with storage, and communicating with the network.

Some examples of commonly used Browser APIs include:

The DOM API, which you can use to manipulate HTML elements, their styles, and attributes. You will learn much more about the DOM in the coming lessons. It’s a core concept in web development.

The Storage API, to store data locally on the user’s device.

What Is the requestAnimationFrame() API, and How Can It Be Used to Set Up an Animation Loop?

To use the requestAnimationFrame() method, all you need to do is to call it and pass a callback function into it: requestAnimationFrame(callback);

Calling requestAnimationFrame() must first occur inside a function that handles the animation, such as animate(), along with a function to update the animation, traditionally called update():

function animate() {
 // Update the animation...
 // for example, move an element, change a style, and more.
 update();
 // Request the next frame
 requestAnimationFrame(animate);
}
Enter fullscreen mode Exit fullscreen mode

The update() function is where the magic happens. Inside it, you get to change whatever you want to animate. For example, updating a style or changing the position of an element:

function update() {
 element.style.transform = `translateX(${position}px)`;
 position += 2;
}
Enter fullscreen mode Exit fullscreen mode

What finally kicks off the animation is calling requestAnimationFrame() and passing in the animate function, this time outside the animate function: requestAnimationFrame(animate);

What Is the Web Animations API, and How Does It Relate to CSS Animation Properties?

When to use: When you need animations to respond to user interactions like clicks, scrolls, or allow dynamic control such as pausing or reversing.

The Web Animations API (WAAPI) allows you to create and control animations directly within JavaScript.

At the core of WAAPI is the Animation constructor, which provides several instance methods and properties that allow you to dynamically animate elements. A significant method in the Animation constructor is animate(). It allows you to create an animation by specifying keyframes and options like duration, direction, easing, and iterations.

const square = document.querySelector("#square");

const animation = square.animate(
  [{ transform: "translateX(0px)" }, { transform: "translateX(100px)" }],
  {
    duration: 2000, // makes animation lasts 2 seconds
    iterations: Infinity, // loops indefinitely
    direction: "alternate", // moves back and forth
    easing: "ease-in-out" // smooth easing
  }
);
Enter fullscreen mode Exit fullscreen mode
const square = document.querySelector("#square");
const playBtn = document.querySelector("#playBtn");
const pauseBtn = document.querySelector("#pauseBtn");

const animation = square.animate(
  [{ transform: "translateX(0px)" }, { transform: "translateX(200px)" }],
  {
    duration: 5000, // Animation lasts 5 seconds
    // iterations: Infinity, // Loops indefinitely
    direction: "alternate", // Moves back and forth
    easing: "ease-in-out" // Smooth easing function
  }
);

// Set the onfinish property to log a message when the animation ends
animation.onfinish = () => {
  console.log("Animation finished!");
};

// Play the animation when the "Play" button is clicked
playBtn.addEventListener("click", () => {
  animation.play();
  console.log("You start the animation");
});

// Pause the animation when the "Pause" button is clicked
pauseBtn.addEventListener("click", () => {
  animation.pause();
  console.log("You pause the animation");
});
Enter fullscreen mode Exit fullscreen mode

What Is the Canvas API, and How Does It Work?

The Canvas API is a powerful tool that lets you manipulate graphics right inside your JavaScript file. Everything begins with a canvas element in HTML. This element serves as a drawing surface that you can manipulate using the instance methods and properties of the Canvas API.

First, you need to create a canvas element in your HTML file:

<canvas id="my-canvas"></canvas>
Enter fullscreen mode Exit fullscreen mode

The canvas element is represented by the HTMLCanvasElement interface, which provides methods and properties for manipulating it. Additionally, you can use methods and properties from other interfaces in the Canvas API.

You can give your canvas a width and height inside the HTML:

<canvas id="my-canvas" width="400" height="400"></canvas>
Enter fullscreen mode Exit fullscreen mode

Or you can use the width and height properties of the HTMLCanvasElement interface:

const canvas = document.getElementById("my-canvas");
canvas.width = 400;
canvas.height = 400;
Enter fullscreen mode Exit fullscreen mode

For now, you can't see anything on the screen yet. After creating your canvas element, the next thing to do is to get access to the drawing context of the canvas with the getContext() method of the HTMLCanvasElement interface.

The most common context is 2d, which allows you to draw in two dimensions:

const canvas = document.getElementById("my-canvas");
const ctx = canvas.getContext('2d');
Enter fullscreen mode Exit fullscreen mode

If you log the ctx variable to the console, you'll see the methods and properties of CanvasRenderingContext2D that you can use to create shapes, colors, lines, and more, along with their default values:

The Canvas API provides several methods and properties for drawing shapes, lines, and text. One of those is the fillStyle property, which you can combine with the fillRect() method to draw a rectangle or square:

<html>
  <head>
  </head>
  <body>
    <canvas id="my-canvas" width="400" height="400"></canvas>
    <script src="index.js"></script>
  </body>
</html>
const canvas = document.getElementById("my-canvas");

const ctx = canvas.getContext("2d");

// Set the background color
ctx.fillStyle = "crimson";

// Draw a rectangle
ctx.fillRect(1, 1, 150, 100);
Enter fullscreen mode Exit fullscreen mode

fillRect takes 4 number values which represent the x axis, y axis, width, and height, respectively.

There's something on the screen now. You can also draw text or even create an animation. Here's a canvas to represent text:

<canvas id="my-text-canvas" width="300" height="70"></canvas>
Enter fullscreen mode Exit fullscreen mode

To finally draw the text, pass the text into the fillText() method as the first argument, followed by the values for the x and y axis:

<html>
  <head>
  </head>
  <body>
    <canvas id="my-text-canvas" width="300" height="70"></canvas>
    <script src="index.js"></script>
  </body>
</html>
const textCanvas = document.getElementById("my-text-canvas");

const textCanvasCtx = textCanvas.getContext("2d");

// Set font family and size
textCanvasCtx.font = "30px Arial";

// Set text color
textCanvasCtx.fillStyle = "crimson";

// Draw the text
textCanvasCtx.fillText("Hello HTML Canvas!", 1, 50);
Enter fullscreen mode Exit fullscreen mode

The result in the browser will be the red text Hello HTML Canvas!.

These's much more you can do with the Canvas API. For example, you can combine it with requestAnimationFrame to create custom animations, visualizations, games, and more.

How Do You Open and Close Dialog Elements Using JavaScript?

Dialogs let you display important information or actions to users. With HTML's built-in dialog element, you can easily create these dialogs (both modal and non-modal dialogs) in your web apps.

A modal dialog is a type of dialog that forces the user to interact with it before they can access the rest of the application or webpage. It effectively blocks interaction with other content until the user completes an action, such as closing the dialog or submitting a form.

When you want to make sure the user focuses on a specific action or message of a modal, you can open the modal dialog using the showModal() method. This will add a backdrop to the other items on the page and disable them. This is ideal for modals that display forms, confirmations, and critical information that requires user action.

Here's the HTML for the modal dialog:

<dialog id="my-modal">
  <p>This is a modal dialog.</p>
</dialog>
Enter fullscreen mode Exit fullscreen mode

For now, you can't see anything on the page because the modal is closed on the initial render. You can automatically open the modal by using the showModal() method:

<dialog id="modal">
  <p>This is a modal dialog.</p>
</dialog>
<script src="index.js"></script>
const dialog = document.getElementById("modal");
dialog.showModal();
Enter fullscreen mode Exit fullscreen mode

The result in the browser will show a modal with the text This is a modal dialog.

It's best to give control to the user. To achieve this, you can add a click event listener to a button and use the showModal() method:

<dialog id="modal">
  <p>This is a modal dialog.</p>
</dialog>
<button id="open-modal-btn">Open Modal Dialog</button>
<script src="index.js"></script>
const dialog = document.getElementById("modal");
const openButton = document.getElementById("open-modal-btn");

openButton.addEventListener("click", () => {
  dialog.showModal();
});
Enter fullscreen mode Exit fullscreen mode

If you needed to show a dialog while still allowing interaction with content outside of the dialog, then you can use the show() method:

<dialog id="modal">
  <p>This is a modal dialog.</p>
</dialog>
<button id="open-modal-btn">Open Modal Dialog</button>
<script src="index.js"></script>
const dialog = document.getElementById("modal");
const openButton = document.getElementById("open-modal-btn");

openButton.addEventListener("click", () => {
  dialog.show();
});
Enter fullscreen mode Exit fullscreen mode

To close a modal, you can add a button to the modal inside the dialog element and use the close() method:

closeButton.addEventListener("click", () => {
  dialog.close();
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)