?? Mastering JavaScript Web APIs: Unlocking the Power of Browser Features! ??

?? Mastering JavaScript Web APIs: Unlocking the Power of Browser Features! ??

https://basescripts.com/mastering-javascript-web-apis-unlocking-the-power-of-browser-feature

Exercise 1: Fetch API Basics

Problem: Use the Fetch API to retrieve data from https://jsonplaceholder.typicode.com/posts/1 and log the title of the post.

Explanation: Demonstrates basic usage of the Fetch API to make a GET request and handle the response as JSON.

Code:

fetch('https://jsonplaceholder.typicode.com/posts/1')

?.then(response => response.json())

?.then(data => console.log(data.title))

?.catch(error => console.error('Error:', error));

Exercise 2: DOM Manipulation with API Data

Problem: Fetch a list of users from https://jsonplaceholder.typicode.com/users, then display the names of the users in an HTML unordered list.

Explanation: Shows how to use the Fetch API to get data and dynamically update the DOM with the results.

Code:

<ul id="user-list"></ul>

<script>

?fetch('https://jsonplaceholder.typicode.com/users')

?.then(response => response.json())

?.then(users => {

?const userList = document.getElementById('user-list');

?users.forEach(user => {

?const li = document.createElement('li');

?li.textContent = user.name;

?userList.appendChild(li);

?});

?})

?.catch(error => console.error('Error:', error));

</script>

Exercise 3: Handling Form Submissions

Problem: Create an HTML form for submitting a name. Use JavaScript to handle the form submission by preventing the default action and logging the inputted name to the console.

Explanation: Utilizes JavaScript to handle form events and prevent traditional form submission behavior, demonstrating client-side form handling.

Code:

<form id="name-form">

?<input type="text" id="name-input" placeholder="Enter your name">

?<button type="submit">Submit</button>

</form>

<script>

?document.getElementById('name-form').addEventListener('submit', function(event) {

?event.preventDefault(); // Prevent the default form submission

?const name = document.getElementById('name-input').value;

?console.log(name);

?});

</script>

Exercise 4: Event Listener Removal

Problem: Add a click event listener to a button that alerts "Button clicked!" and then removes the event listener so that it only works once.

Explanation: Teaches how to properly add and remove event listeners, demonstrating the management of event handling in JavaScript.

Code:

<button id="my-button">Click me</button>

<script>

?const button = document.getElementById('my-button');

?const handleClick = () => {

?alert("Button clicked!");

?button.removeEventListener('click', handleClick);

?};

?button.addEventListener('click', handleClick);

</script>

Exercise 5: Using LocalStorage

Problem: Write JavaScript code that stores a value in localStorage and then retrieves it and logs it to the console.

Explanation: Demonstrates the usage of Web Storage API (localStorage) to persist data locally in the browser.

Code:

// Store a value

localStorage.setItem('myKey', 'myValue');

// Retrieve and log the value

const value = localStorage.getItem('myKey');

console.log(value);

Exercise 6: Implementing a Simple Animation

Problem: Use the Web Animations API to animate an HTML element moving from the left side of the screen to the right.

Explanation: Demonstrates the use of the Web Animations API to create basic animations directly in JavaScript.

Code:

<div id="animate-me" style="width: 50px; height: 50px; background-color: red;"></div>

<script>

?document.getElementById('animate-me').animate([

?{ transform: 'translateX(0px)' },

?{ transform: 'translateX(100px)' }

?], {

?duration: 1000, // 1 second

?fill: 'forwards'

?});

</script>

Exercise 7: Using the Geolocation API

Problem: Use the Geolocation API to log the user's current latitude and longitude to the console.

Explanation: Shows how to retrieve the user's current position using the Geolocation API.

Code:

if (navigator.geolocation) {

?navigator.geolocation.getCurrentPosition(position => {

?console.log(`Latitude: ${position.coords.latitude}, Longitude: ${position.coords.longitude}`);

?});

} else {

?console.log("Geolocation is not supported by this browser.");

}

Exercise 8: Interacting with the Document Object Model (DOM)

Problem: Create a script that changes the text content of an element with the id text-element to "Hello, DOM!".

Explanation: Demonstrates basic manipulation of the DOM to change the content of HTML elements.

Code:

<div id="text-element">Original text</div>

<script>

?document.getElementById('text-element').textContent = "Hello, DOM!";

</script>

Exercise 9: XMLHttpRequest to Fetch Data

Problem: Use XMLHttpRequest to make a GET request to https://jsonplaceholder.typicode.com/posts/1 and log the response.

Explanation: Shows how to use XMLHttpRequest to make an asynchronous HTTP request, a fundamental aspect of AJAX.

Code:

const xhr = new XMLHttpRequest();

xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);

xhr.onload = function() {

?if (xhr.status === 200) {

?console.log(xhr.responseText);

?} else {

?console.error('Error:', xhr.statusText);

?}

};

xhr.send();

Exercise 10: Mutation Observers

Problem: Use a MutationObserver to watch for changes to the text content of an element with the id observe-me, and log the new text content whenever it changes.

Explanation: Introduces MutationObserver to monitor DOM changes, a powerful tool for responding to dynamic changes in web applications.

Code:

<div id="observe-me">Watch me change</div>

<script>

?const targetNode = document.getElementById('observe-me');

?const observer = new MutationObserver(mutations => {

?mutations.forEach(mutation => {

?console.log('New text content:', mutation.target.textContent);

?});

?});

?observer.observe(targetNode, { childList: true, subtree: true });

</script>

要查看或添加评论,请登录

JavaScript Developer WorldWide的更多文章

社区洞察

其他会员也浏览了