Assignments Of Day 29: JavaScript and Web APIs

Rashmi Mishra
0

Assignments Of Day 29: JavaScript and Web APIs

Assignment 1: Fetch Data from an API

Objective: Use the fetch() API to get data from a public API and display it in the console.

Instructions:

  • Fetch a list of posts from the JSONPlaceholder API (https://jsonplaceholder.typicode.com/posts).
  • Log the title of each post to the console.

Solution:

javascript

Copy code

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

  .then(response => response.json())  // Parse the JSON response

  .then(data => {

    data.forEach(post => {

      console.log(post.title);  // Display the title of each post

    });

  })

  .catch(error => {

    console.error('Error:', error);  // Handle any errors

  });

Explanation:

  • fetch() sends an HTTP GET request to the specified URL.
  • The response.json() method parses the JSON response into a JavaScript object.
  • We loop through the array of posts and log the title of each post.

Assignment 2: Get User's Geolocation

Objective: Use the Geolocation API to retrieve the user's current latitude and longitude.

Instructions:

  • Retrieve the user's current location and display the latitude and longitude in the console.

Solution:

javascript

Copy code

if (navigator.geolocation) {

  navigator.geolocation.getCurrentPosition(

    (position) => {

      console.log('Latitude: ' + position.coords.latitude);  // Display latitude

      console.log('Longitude: ' + position.coords.longitude);  // Display longitude

    },

    (error) => {

      console.error('Error: ' + error.message);  // Handle error

    }

  );

} else {

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

}

Explanation:

  • navigator.geolocation.getCurrentPosition() retrieves the user's location.
  • The callback function receives the position, which includes coords.latitude and coords.longitude.
  • The error callback handles cases where the user denies permission or if there is another error.

Assignment 3: Store User's Favorite Color Using Local Storage

Objective: Use localStorage to store and retrieve a user's favorite color.

Instructions:

  • Create an input field where a user can type their favorite color.
  • When the user submits the form, store the color in localStorage.
  • On page load, check if there is a color stored in localStorage. If so, display it.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Store Favorite Color</title>

</head>

<body>

  <h2>Enter Your Favorite Color</h2>

  <input type="text" id="colorInput" placeholder="Enter color">

  <button id="saveButton">Save Color</button>

  <p id="storedColor">Your favorite color is: </p>

 

  <script>

    // Check if a color is stored in localStorage on page load

    window.onload = function() {

      let savedColor = localStorage.getItem('favoriteColor');

      if (savedColor) {

        document.getElementById('storedColor').textContent = 'Your favorite color is: ' + savedColor;

      }

    };

 

    // Save color when button is clicked

    document.getElementById('saveButton').addEventListener('click', function() {

      let color = document.getElementById('colorInput').value;

      localStorage.setItem('favoriteColor', color);

      document.getElementById('storedColor').textContent = 'Your favorite color is: ' + color;

    });

  </script>

</body>

</html>

Explanation:

  • We use localStorage.setItem() to store the favorite color entered by the user.
  • On page load (window.onload), we check if a favorite color is stored in localStorage using localStorage.getItem().
  • If a color is found, it is displayed on the page.

Assignment 4: Use Fetch API to Get Weather Information

Objective: Use the Fetch API to retrieve weather information from an external weather API.

Instructions:

  • Use the OpenWeatherMap API (you need to sign up for a free API key).
  • Fetch the current weather data for a city (e.g., "London").
  • Display the temperature and weather description in the console.

Solution:

javascript

Copy code

const apiKey = 'YOUR_API_KEY';  // Replace with your OpenWeatherMap API key

const city = 'London';

 

fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`)

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

  .then(data => {

    console.log(`Temperature in ${city}: ${data.main.temp}°C`);

    console.log(`Weather: ${data.weather[0].description}`);

  })

  .catch(error => {

    console.error('Error fetching weather data:', error);

  });

Explanation:

  • We use fetch() to make a GET request to the OpenWeatherMap API, passing the city name and API key.
  • The weather data is returned as a JSON object. We then access the main.temp and weather[0].description properties to display the temperature and weather description.

Assignment 5: Get User's Location and Store It in LocalStorage

Objective: Combine the Geolocation API and localStorage to store the user's location for future use.

Instructions:

  • Get the user's latitude and longitude using the Geolocation API.
  • Store the latitude and longitude in localStorage.
  • If the location is already stored in localStorage, display it on the page.

Solution:

javascript

Copy code

if (navigator.geolocation) {

  // Check if location is already stored in localStorage

  const storedLocation = localStorage.getItem('userLocation');

  if (storedLocation) {

    const location = JSON.parse(storedLocation);

    console.log('Stored Location: ', location);

    document.getElementById('location').textContent = `Stored Location: Latitude ${location.latitude}, Longitude ${location.longitude}`;

  } else {

    // Get user's current location

    navigator.geolocation.getCurrentPosition(

      (position) => {

        const userLocation = {

          latitude: position.coords.latitude,

          longitude: position.coords.longitude

        };

 

        // Store location in localStorage

        localStorage.setItem('userLocation', JSON.stringify(userLocation));

       

        console.log('Current Location: ', userLocation);

        document.getElementById('location').textContent = `Current Location: Latitude ${userLocation.latitude}, Longitude ${userLocation.longitude}`;

      },

      (error) => {

        console.error('Error fetching location:', error);

      }

    );

  }

} else {

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

}

Explanation:

  • First, we check if the user's location is already stored in localStorage.
  • If not, we use the Geolocation API to fetch the user's location and store it in localStorage.
  • If the location is stored, we display it directly from localStorage.

Assignment 6: Store Session Data Using SessionStorage

Objective: Use sessionStorage to store temporary session data.

Instructions:

  • Create an input field where a user can type their name.
  • Store the name in sessionStorage.
  • On page load, check if the name is stored in sessionStorage and display it.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Store Session Data</title>

</head>

<body>

  <h2>Enter Your Name</h2>

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

  <button id="saveNameButton">Save Name</button>

  <p id="storedName">Your name is: </p>

 

  <script>

    // Check if a name is stored in sessionStorage on page load

    window.onload = function() {

      let savedName = sessionStorage.getItem('userName');

      if (savedName) {

        document.getElementById('storedName').textContent = 'Your name is: ' + savedName;

      }

    };

 

    // Save name when button is clicked

    document.getElementById('saveNameButton').addEventListener('click', function() {

      let name = document.getElementById('nameInput').value;

      sessionStorage.setItem('userName', name);

      document.getElementById('storedName').textContent = 'Your name is: ' + name;

    });

  </script>

</body>

</html>

Explanation:

  • We store the user's name in sessionStorage when they click the "Save Name" button.
  • On page load, we check if the name is already stored in sessionStorage. If found, we display it.

These assignments will help reinforce the key concepts of JavaScript and Web APIs, including fetch(), Geolocation API, and Web Storage (localStorage and sessionStorage).

4o mini

You said:

more

ChatGPT said:

ChatGPT

Here are more assignments related to JavaScript and Web APIs:


Assignment 7: Fetch Data from an API and Display in HTML Table

Objective: Use the fetch() method to retrieve data from a public API and dynamically create an HTML table to display it.

Instructions:

  • Fetch a list of users from the JSONPlaceholder API.
  • Create an HTML table that will display the user's name, email, and company name.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Fetch Data and Display in Table</title>

</head>

<body>

  <h2>User Information</h2>

  <table border="1" id="userTable">

    <thead>

      <tr>

        <th>Name</th>

        <th>Email</th>

        <th>Company</th>

      </tr>

    </thead>

    <tbody>

      <!-- Data will be inserted here -->

    </tbody>

  </table>

 

  <script>

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

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

      .then(data => {

        let tableBody = document.querySelector('#userTable tbody');

        data.forEach(user => {

          let row = document.createElement('tr');

          row.innerHTML = `

            <td>${user.name}</td>

            <td>${user.email}</td>

            <td>${user.company.name}</td>

          `;

          tableBody.appendChild(row);

        });

      })

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

  </script>

</body>

</html>

Explanation:

  • We use fetch() to get data from the jsonplaceholder API and parse it into a JavaScript object.
  • For each user, we create a new table row and append it to the table body.

Assignment 8: Get User's Geolocation and Show on Map

Objective: Use the Geolocation API to retrieve the user's current location and show it on a Google Map.

Instructions:

  • Retrieve the user's latitude and longitude using the Geolocation API.
  • Display the user's location on a Google Map by embedding a Google Map in the webpage (you'll need to create a Google Maps API key).

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>User Location on Google Map</title>

  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>

</head>

<body>

  <h2>Your Current Location</h2>

  <div id="map" style="height: 400px; width: 100%;"></div>

 

  <script>

    let map, marker;

 

    function initMap() {

      if (navigator.geolocation) {

        navigator.geolocation.getCurrentPosition(

          function(position) {

            let lat = position.coords.latitude;

            let lon = position.coords.longitude;

 

            map = new google.maps.Map(document.getElementById('map'), {

              center: { lat: lat, lng: lon },

              zoom: 12

            });

 

            marker = new google.maps.Marker({

              position: { lat: lat, lng: lon },

              map: map,

              title: 'Your Location'

            });

          },

          function(error) {

            console.error('Geolocation error:', error);

          }

        );

      } else {

        alert('Geolocation is not supported by this browser.');

      }

    }

  </script>

</body>

</html>

Explanation:

  • We use the Geolocation API to get the user's latitude and longitude.
  • After retrieving the coordinates, we initialize a Google Map centered at the user's location and place a marker there.

Assignment 9: Store User Preferences Using localStorage

Objective: Store and retrieve user preferences (like theme color) using localStorage.

Instructions:

  • Create an input field where a user can choose a background color (use color picker).
  • Save the chosen color in localStorage.
  • On page load, check if a color is stored in localStorage and apply it to the background.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Save User Preferences</title>

</head>

<body>

  <h2>Choose Your Background Color</h2>

  <input type="color" id="colorPicker">

  <button id="saveColorBtn">Save Color</button>

 

  <script>

    // Apply the saved color if available

    window.onload = function() {

      let savedColor = localStorage.getItem('backgroundColor');

      if (savedColor) {

        document.body.style.backgroundColor = savedColor;

      }

    };

 

    // Save the selected color to localStorage

    document.getElementById('saveColorBtn').addEventListener('click', function() {

      let color = document.getElementById('colorPicker').value;

      localStorage.setItem('backgroundColor', color);

      document.body.style.backgroundColor = color;

    });

  </script>

</body>

</html>

Explanation:

  • We use localStorage.setItem() to save the chosen color and apply it to the backgroundColor style of the body.
  • On page load, we retrieve the color from localStorage and apply it if it exists.

Assignment 10: Fetch and Display Comments for a Post

Objective: Fetch comments related to a specific post from the JSONPlaceholder API and display them.

Instructions:

  • Fetch comments related to a specific post using the JSONPlaceholder API.
  • Display the name and email of the commenter for each comment in a list.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Post Comments</title>

</head>

<body>

  <h2>Comments for Post 1</h2>

  <ul id="commentsList">

    <!-- Comments will be listed here -->

  </ul>

 

  <script>

    fetch('https://jsonplaceholder.typicode.com/comments?postId=1')

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

      .then(data => {

        let commentsList = document.getElementById('commentsList');

        data.forEach(comment => {

          let listItem = document.createElement('li');

          listItem.innerHTML = `<strong>${comment.name}</strong> (${comment.email}): ${comment.body}`;

          commentsList.appendChild(listItem);

        });

      })

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

  </script>

</body>

</html>

Explanation:

  • The fetch() method is used to retrieve the comments for post ID 1.
  • Each comment's name, email, and body are displayed in a list.

Assignment 11: Track User's Theme Preference Using sessionStorage

Objective: Use sessionStorage to store and retrieve a user's theme preference for the current session.

Instructions:

  • Create buttons for "Dark Theme" and "Light Theme".
  • When a user selects a theme, store the theme choice in sessionStorage and apply it to the page.
  • If a theme is stored in sessionStorage, apply it automatically when the page loads.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Session Theme Preference</title>

  <style>

    body.light-theme {

      background-color: white;

      color: black;

    }

    body.dark-theme {

      background-color: black;

      color: white;

    }

  </style>

</head>

<body>

  <h2>Select Theme</h2>

  <button id="darkThemeBtn">Dark Theme</button>

  <button id="lightThemeBtn">Light Theme</button>

 

  <script>

    // On page load, apply the stored theme if available

    window.onload = function() {

      let storedTheme = sessionStorage.getItem('theme');

      if (storedTheme) {

        document.body.classList.add(storedTheme);

      }

    };

 

    // Set Dark Theme

    document.getElementById('darkThemeBtn').addEventListener('click', function() {

      document.body.classList.remove('light-theme');

      document.body.classList.add('dark-theme');

      sessionStorage.setItem('theme', 'dark-theme');

    });

 

    // Set Light Theme

    document.getElementById('lightThemeBtn').addEventListener('click', function() {

      document.body.classList.remove('dark-theme');

      document.body.classList.add('light-theme');

      sessionStorage.setItem('theme', 'light-theme');

    });

  </script>

</body>

</html>

Explanation:

  • We store the selected theme (dark-theme or light-theme) in sessionStorage.
  • On page load, the stored theme is retrieved and applied to the body of the page.

Let me know if you need further assignments or explanations on any of these topics!

4o mini

You said:

give more

ChatGPT said:

ChatGPT

Here are more assignments related to JavaScript and Web APIs:


Assignment 12: Fetch and Display Posts

Objective: Fetch a list of posts from a public API and display them in a styled HTML list.

Instructions:

  • Fetch a list of posts from the JSONPlaceholder API.
  • Display the title of each post in a list.
  • For each post title, create a clickable link that displays the full content of the post when clicked.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Posts</title>

  <style>

    .post {

      margin-bottom: 20px;

      padding: 10px;

      border: 1px solid #ddd;

      cursor: pointer;

    }

    .post:hover {

      background-color: #f0f0f0;

    }

  </style>

</head>

<body>

  <h2>List of Posts</h2>

  <div id="postsList"></div>

 

  <script>

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

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

      .then(posts => {

        const postsList = document.getElementById('postsList');

        posts.forEach(post => {

          const postElement = document.createElement('div');

          postElement.classList.add('post');

          postElement.innerHTML = `<strong>${post.title}</strong>`;

          postElement.addEventListener('click', () => {

            alert(post.body);

          });

          postsList.appendChild(postElement);

        });

      })

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

  </script>

</body>

</html>

Explanation:

  • We fetch posts from the API and display each post's title as a clickable item.
  • When clicked, the full content of the post is shown in an alert.

Assignment 13: Display Weather Information

Objective: Fetch weather data from a public weather API and display the current temperature and weather condition for a city.

Instructions:

  • Use the OpenWeatherMap API to fetch current weather data.
  • Display the city's name, current temperature (in Celsius), and weather description.
  • Handle the case where the API fetch fails or the city is not found.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Weather Info</title>

</head>

<body>

  <h2>Weather Information</h2>

  <input type="text" id="cityInput" placeholder="Enter city">

  <button id="getWeatherBtn">Get Weather</button>

  <div id="weatherInfo"></div>

 

  <script>

    const apiKey = 'YOUR_API_KEY'; // Replace with your OpenWeatherMap API key

    document.getElementById('getWeatherBtn').addEventListener('click', function() {

      const city = document.getElementById('cityInput').value;

      if (city) {

        fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`)

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

          .then(data => {

            if (data.cod === 200) {

              const weatherInfo = `

                <h3>${data.name} - ${data.weather[0].description}</h3>

                <p>Temperature: ${data.main.temp}°C</p>

              `;

              document.getElementById('weatherInfo').innerHTML = weatherInfo;

            } else {

              document.getElementById('weatherInfo').innerHTML = '<p>City not found. Please try again.</p>';

            }

          })

          .catch(error => {

            document.getElementById('weatherInfo').innerHTML = '<p>Error fetching weather data.</p>';

          });

      } else {

        alert('Please enter a city name.');

      }

    });

  </script>

</body>

</html>

Explanation:

  • We use the OpenWeatherMap API to fetch weather data for the city entered by the user.
  • If the API returns a valid response, we display the city name, weather description, and temperature.
  • We handle errors by displaying an appropriate message if the city is not found or the API fails.

Assignment 14: Create and Store a User's Favorite Movie List with localStorage

Objective: Use localStorage to store a user's favorite movies list.

Instructions:

  • Allow the user to input a movie name in a text box and add it to their favorites list.
  • Display the list of movies below the input.
  • Store the list in localStorage so it persists even after the page is refreshed.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Favorite Movies</title>

</head>

<body>

  <h2>My Favorite Movies</h2>

  <input type="text" id="movieInput" placeholder="Enter a movie name">

  <button id="addMovieBtn">Add Movie</button>

  <ul id="movieList"></ul>

 

  <script>

    // Load movies from localStorage on page load

    window.onload = function() {

      const movies = JSON.parse(localStorage.getItem('movies')) || [];

      const movieList = document.getElementById('movieList');

      movies.forEach(movie => {

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

        listItem.textContent = movie;

        movieList.appendChild(listItem);

      });

    };

 

    // Add a new movie to the list

    document.getElementById('addMovieBtn').addEventListener('click', function() {

      const movieInput = document.getElementById('movieInput');

      const movieName = movieInput.value.trim();

      if (movieName) {

        const movies = JSON.parse(localStorage.getItem('movies')) || [];

        movies.push(movieName);

        localStorage.setItem('movies', JSON.stringify(movies));

 

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

        listItem.textContent = movieName;

        document.getElementById('movieList').appendChild(listItem);

        movieInput.value = ''; // Clear input field

      } else {

        alert('Please enter a movie name.');

      }

    });

  </script>

</body>

</html>

Explanation:

  • We store the user's movie list in localStorage as an array, ensuring that the data persists even after a page refresh.
  • The list is dynamically updated both in the DOM and in localStorage when a new movie is added.

Assignment 15: Implement Search Functionality with Fetch API

Objective: Implement a search feature that fetches data from an API based on the user's search term.

Instructions:

  • Fetch a list of users from the JSONPlaceholder API.
  • Implement a search functionality that filters the users by their name as the user types in the input field.
  • Display the search results dynamically as the user types.

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Search Users</title>

</head>

<body>

  <h2>Search Users</h2>

  <input type="text" id="searchInput" placeholder="Search for a user">

  <ul id="userList"></ul>

 

  <script>

    let users = [];

 

    // Fetch the users from the API

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

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

      .then(data => {

        users = data;

        displayUsers(users);

      });

 

    // Display users in the list

    function displayUsers(userArray) {

      const userList = document.getElementById('userList');

      userList.innerHTML = '';

      userArray.forEach(user => {

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

        listItem.textContent = user.name;

        userList.appendChild(listItem);

      });

    }

 

    // Search users as the user types

    document.getElementById('searchInput').addEventListener('input', function() {

      const query = this.value.toLowerCase();

      const filteredUsers = users.filter(user => user.name.toLowerCase().includes(query));

      displayUsers(filteredUsers);

    });

  </script>

</body>

</html>

Explanation:

  • The user data is fetched once when the page loads.
  • As the user types into the search field, the list of users is filtered in real-time, displaying only users whose names match the search query.

Assignment 16: Display Current Time using Date API

Objective: Use JavaScript's Date API to display the current date and time, and update it every second.

Instructions:

  • Display the current date and time in a specific format (e.g., YYYY-MM-DD HH:mm:ss).
  • Update the time every second using setInterval().

Solution:

html

Copy code

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Current Time</title>

</head>

<body>

  <h2>Current Time</h2>

  <div id="currentTime"></div>

 

  <script>

    function updateTime() {

      const currentDate = new Date();

      const hours = currentDate.getHours().toString().padStart(2, '0');

      const minutes = currentDate.getMinutes().toString().padStart(2, '0');

      const seconds = currentDate.getSeconds().toString().padStart(2, '0');

      const dateString = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${currentDate.getDate().toString().padStart(2, '0')} ${hours}:${minutes}:${seconds}`;

      document.getElementById('currentTime').innerText = dateString;

    }

 

    setInterval(updateTime, 1000); // Update time every second

    updateTime(); // Initial call to display time immediately

  </script>

</body>

</html>

Explanation:

  • We use the Date object to fetch the current time and format it properly.
  • setInterval() is used to update the time every second.

Post a Comment

0Comments

Post a Comment (0)