API Projects – CodingNepal https://www.codingnepalweb.com CodingNepal is a blog dedicated to providing valuable and informative content about web development technologies such as HTML, CSS, JavaScript, and PHP. Fri, 15 Dec 2023 12:17:32 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 Build An AI Image Generator Website in HTML CSS and JavaScript https://www.codingnepalweb.com/ai-image-generator-website-html-javascript/ https://www.codingnepalweb.com/ai-image-generator-website-html-javascript/#respond Fri, 15 Dec 2023 01:52:37 +0000 https://www.codingnepalweb.com/?p=5761 Build An AI Image Generator Website in HTML CSS and JavaScript

Websites like Midjourney and DALL-E have gained significant popularity in recent months or years for their ability to generate creative and imaginative images using AI. If you’re a beginner web developer, have you ever considered creating your own version of an AI image generator website? The great news is that with the help of only HTML, CSS, and JavaScript, you too can build a website like Midjourney or DALL-E.

If you’re unfamiliar, Midjourny and DALL-E are AI image-generation websites. They use a machine-learning model to create images based on text descriptions. Users can input their desired image prompt, and these websites will generate a corresponding image that matches the description.

In this blog post, I will provide a step-by-step guide on how to build your own website for generating AI images using HTML, CSS, and JavaScript. The website will be built entirely from scratch using pure JavaScript. So, as a beginner, you can gain practical experience by applying your newly learned HTML, CSS, and JavaScript skills to real-world web projects.

On this custom AI image generation website, users enter their prompt, choose the number of images they want to generate, and click the “Generate” button. The AI will then create images based on the user prompt. To download each image, the user can click on the corresponding download button provided.

Video Tutorial of AI Image Generator HTML and JavaScript

If you enjoy learning through video tutorials, the above YouTube video can be an excellent resource. In the video, I’ve explained each line of code and included informative comments to make building your own AI image generator website simple and easy to follow.

However, if you like reading blog posts or want a step-by-step guide for this project, you can continue reading this post. By the end of this post, you will have your own AI image generator website that you can showcase with your friends and include in your portfolio.

Steps to Build AI Image Generator Website HTML & JavaScript

To build an AI image generator website using HTML, CSS, and vanilla JavaScript, follow these simple step-by-step instructions:

  • First, create a folder with any name you like. Then, make the necessary files inside it.
  • Create a file called index.html to serve as the main file.
  • Create a file called style.css for the CSS code.
  • Create a file called script.js for the JavaScript code.
  • Finally, download the Images folder and put it in your project directory. This folder contains default showcase images for the website. You can also use your own images.

To start, add the following HTML codes to your index.html file. These codes include essential HTML markup with different semantic tags, such as div, form, input, button, image, etc., to build the website layout.

<!DOCTYPE html>
<!-- Coding By CodingNepal - www.codingnepalweb.com -->
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI Image Generator HTML CSS and JavaScript | CodingNepal</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js" defer></script>
</head>
<body>
  <section class="image-generator">
    <div class="content">
      <h1>AI Image Generator Tool JavaScript</h1>
      <p>Convert your text into an image within a second using this
        JavaScript-powered AI Image Generator tool.</p>
      <form action="#" class="generate-form">
        <input class="prompt-input" type="text" placeholder="Describe what you want to see" required>
        <div class="controls">
          <select class="img-quantity">
            <option value="1">1 Image</option>
            <option value="2">2 Images</option>
            <option value="3">3 Images</option>
            <option value="4" selected>4 Images</option>
          </select>
          <button type="submit" class="generate-btn">Generate</button>
        </div>
      </form>
    </div>
  </section>
  <section class="image-gallery">
    <div class="img-card"><img src="images/img-1.jpg" alt="image"></div>
    <div class="img-card"><img src="images/img-2.jpg" alt="image"></div>
    <div class="img-card"><img src="images/img-3.jpg" alt="image"></div>
    <div class="img-card"><img src="images/img-4.jpg" alt="image"></div>
  </section>
</body>
</html>

Next, add the following CSS codes to your style.css file to make your AI image generator website beautiful and user-friendly. You can customize the different CSS properties, such as color, background, font, etc., to give a personalized touch to your website. Now, if you load the web page in your browser, you can see your AI image generator website with four preloaded images.

/* Importing Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

.image-generator {
  height: 40vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  background: url("images/bg.jpg");
  background-size: cover;
  background-position: center;
}

.image-generator::before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0.5;
  background: #121212;
}

.image-generator .content {
  position: relative;
  color: #fff;
  padding: 0 15px;
  max-width: 760px;
  text-align: center;
}

.image-generator h1 {
  font-size: 2.5rem;
  font-weight: 700;
}

.image-generator p {
  margin-top: 10px;
  font-size: 1.35rem;
}

.image-generator .generate-form {
  height: 56px;
  padding: 6px;
  display: flex;
  margin-bottom: 15px;
  background: #fff;
  align-items: center;
  border-radius: 30px;
  margin-top: 45px;
  justify-content: space-between;
}

.generate-form .prompt-input {
  width: 100%;
  height: 100%;
  outline: none;
  padding: 0 17px;
  border: none;
  background: none;
  font-size: 1rem;
  border-radius: 30px;
}

.generate-form .controls {
  display: flex;
  height: 100%;
  gap: 15px;
}

.generate-form .img-quantity {
  outline: none;
  border: none;
  height: 44px;
  background: none;
  font-size: 1rem;
}

.generate-form .generate-btn {
  font-size: 1rem;
  outline: none;
  border: none;
  font-weight: 500;
  color: #fff;
  cursor: pointer;
  height: 100%;
  padding: 0 25px;
  border-radius: 30px;
  background: #4949E7;
}

.generate-form .generate-btn[disabled] {
  opacity: 0.6;
  pointer-events: none;
}

.generate-form button:hover {
  background: #1d1de2;
}

.image-gallery {
  display: flex;
  gap: 15px;
  padding: 0 15px;
  flex-wrap: wrap;
  justify-content: center;
  margin: 50px auto;
  max-width: 1250px;
}

.image-gallery .img-card {
  display: flex;
  position: relative;
  align-items: center;
  justify-content: center;
  background: #f2f2f2;
  border-radius: 4px;
  overflow: hidden;
  aspect-ratio: 1 / 1;
  width: 285px;
}

.image-gallery .img-card img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

.image-gallery .img-card.loading img {
  width: 80px;
  height: 80px;
}

.image-gallery .img-card .download-btn {
  bottom: 15px;
  right: 15px;
  height: 36px;
  width: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-decoration: none;
  background: #fff;
  border-radius: 50%;
  position: absolute;
  opacity: 0;
  pointer-events: none;
  transition: 0.2s ease;
}

.image-gallery .img-card .download-btn img {
  width: 14px;
  height: 14px;
}

.image-gallery .img-card:not(.loading):hover .download-btn {
  opacity: 1;
  pointer-events: auto;
}

@media screen and (max-width: 760px) {
  .image-generator {
    height: 45vh;
    padding-top: 30px;
    align-items: flex-start;
  }

  .image-generator h1 {
    font-size: 1.8rem;
  }

  .image-generator p {
    font-size: 1rem;
  }

  .image-generator .generate-form {
    margin-top: 30px;
    height: 52px;
    display: block;
  }

  .generate-form .controls {
    height: 40px;
    margin-top: 15px;
    justify-content: end;
    align-items: center;
  }

  .generate-form .generate-btn[disabled] {
    opacity: 1;
  }

  .generate-form .img-quantity {
    color: #fff;
  }

  .generate-form .img-quantity option {
    color: #000;
  }

  .image-gallery {
    margin-top: 20px;
  }

  .image-gallery .img-card:not(.loading) .download-btn {
    opacity: 1;
    pointer-events: auto;
  }
}

@media screen and (max-width: 500px) {
  .image-gallery .img-card {
    width: 100%;
  }
}

Finally, add the following JavaScript code to your script.js file to make your AI image generator website functional. This code handles various functions, even listeners, input handling, API calls, image rendering, etc. to generate AI images based on user prompts.

const generateForm = document.querySelector(".generate-form");
const generateBtn = generateForm.querySelector(".generate-btn");
const imageGallery = document.querySelector(".image-gallery");

const OPENAI_API_KEY = "YOUR-OPENAI-API-KEY-HERE"; // Your OpenAI API key here
let isImageGenerating = false;

const updateImageCard = (imgDataArray) => {
  imgDataArray.forEach((imgObject, index) => {
    const imgCard = imageGallery.querySelectorAll(".img-card")[index];
    const imgElement = imgCard.querySelector("img");
    const downloadBtn = imgCard.querySelector(".download-btn");
    
    // Set the image source to the AI-generated image data
    const aiGeneratedImage = `data:image/jpeg;base64,${imgObject.b64_json}`;
    imgElement.src = aiGeneratedImage;
    
    // When the image is loaded, remove the loading class and set download attributes
    imgElement.onload = () => {
      imgCard.classList.remove("loading");
      downloadBtn.setAttribute("href", aiGeneratedImage);
      downloadBtn.setAttribute("download", `${new Date().getTime()}.jpg`);
    }
  });
}

const generateAiImages = async (userPrompt, userImgQuantity) => {
  try {
    // Send a request to the OpenAI API to generate images based on user inputs
    const response = await fetch("https://api.openai.com/v1/images/generations", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${OPENAI_API_KEY}`,
      },
      body: JSON.stringify({
        prompt: userPrompt,
        n: userImgQuantity,
        size: "512x512",
        response_format: "b64_json"
      }),
    });

    // Throw an error message if the API response is unsuccessful
    if(!response.ok) throw new Error("Failed to generate AI images. Make sure your API key is valid.");

    const { data } = await response.json(); // Get data from the response
    updateImageCard([...data]);
  } catch (error) {
    alert(error.message);
  } finally {
    generateBtn.removeAttribute("disabled");
    generateBtn.innerText = "Generate";
    isImageGenerating = false;
  }
}

const handleImageGeneration = (e) => {
  e.preventDefault();
  if(isImageGenerating) return;

  // Get user input and image quantity values
  const userPrompt = e.srcElement[0].value;
  const userImgQuantity = parseInt(e.srcElement[1].value);
  
  // Disable the generate button, update its text, and set the flag
  generateBtn.setAttribute("disabled", true);
  generateBtn.innerText = "Generating";
  isImageGenerating = true;
  
  // Creating HTML markup for image cards with loading state
  const imgCardMarkup = Array.from({ length: userImgQuantity }, () => 
      `<div class="img-card loading">
        <img src="images/loader.svg" alt="AI generated image">
        <a class="download-btn" href="#">
          <img src="images/download.svg" alt="download icon">
        </a>
      </div>`
  ).join("");

  imageGallery.innerHTML = imgCardMarkup;
  generateAiImages(userPrompt, userImgQuantity);
}

generateForm.addEventListener("submit", handleImageGeneration);

Please note that your website is still unable to generate AI images because you have not provided your API key in the OPENAI_API_KEY variable. We’re using OpenAI API to generate images. So to get a free API key from OpenAI, sign up for an account at https://platform.openai.com/account/api-keys.

” Remember that when you sign up for OpenAI, you’ll get a free $5 credit for your API usage. If your account is older than 3 months or the credit runs out, you’ll need a paid account or create a new one with a new number to keep using the API. Your API usage and expiration date can be found on the account’s usage page.”

To understand the JavaScript code better, I recommend watching the above video tutorial, reading the code comments, and experimenting with the code.

Conclusion and Final words

In conclusion, building your own AI-powered image generation website is not just an exciting project but also a valuable opportunity to apply your web development skills to projects that are increasingly in demand in today’s digital world.

By following the steps outlined in this article, I believe that you have successfully created your own unique version of an AI image generator. Feel free to experiment with different styles and features to take your website to the next level. To further improve your skills, I recommend you try creating a ChatGPT clone, chatbot, or image search engine.

If you encounter any problems while building your AI-powered image generation website, you can download the source code files for this project for free by clicking the Download button. Remember that after downloading the file, you’ll have to provide your valid OpenAI API key into the OPENAI_API_KEY variable in the script.js file.

 

]]>
https://www.codingnepalweb.com/ai-image-generator-website-html-javascript/feed/ 0
How to Build A Weather App in HTML CSS and JavaScript https://www.codingnepalweb.com/weather-app-project-html-javascript/ https://www.codingnepalweb.com/weather-app-project-html-javascript/#respond Wed, 28 Jun 2023 19:28:38 +0000 https://www.codingnepalweb.com/?p=5614 Build A Weather App in HTML CSS and JavaScript Weather App Project HTML CSS and JavaScript

Are you new to web development and eager to enhance your skills by working on practical projects? Look no further! Building a weather app is an excellent way to begin your journey. With just HTML, CSS, and JavaScript, you can create an application that not only improves your web development abilities but also makes you familiar with JavaScript API calls.

In this blog post, I’ll guide you through building a weather app project using HTML, CSS, and JavaScript from scratch. If you prefer using Bootstrap, I’ve already covered that in a previous blog post on creating a Weather App in HTML, Bootstrap, and JavaScript. However, this weather project has some extra features that make it more useful.

In this weather app project, users can enter any city name to get the 5-day weather forecast or simply click on the “Use Current Location” button to get their current location’s weather details, including temperature, wind speed, humidity, and more. This project is also mobile-friendly, which means it looks great on all devices.

Video Tutorial of Weather App Project in JavaScript

If you prefer learning through video tutorials, this YouTube video is an excellent resource for understanding the process of creating your own weather app project. In the video, I’ve explained each line of code and provided informative comments to make it beginner-friendly and easy to follow.

However, if you like reading blog posts or want to know the steps involved in creating this weather app project, you can continue reading this post. By the end of this post, you will have your own weather app and a basic understanding of the basics of DOM manipulation, event handling, CSS styling, and APIs.

Steps To Create Weather App in HTML & JavaScript

To create your weather app using HTML, CSS, and JavaScript, follow these step-by-step instructions:

  1. Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a script.js file. The file name must be script and its extension .js

To start, add the following HTML codes to your index.html file. This code includes a weather app header, input, button, and unordered list (ul) that are used as a placeholder for weather details. Later, using JavaScript, we’ll replace these placeholders with actual weather details.

<!DOCTYPE html>
<!-- Coding By CodingNepal - www.codingnepalweb.com -->
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Weather App Project JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="script.js" defer></script>
  </head>
  <body>
    <h1>Weather Dashboard</h1>
    <div class="container">
      <div class="weather-input">
        <h3>Enter a City Name</h3>
        <input class="city-input" type="text" placeholder="E.g., New York, London, Tokyo">
        <button class="search-btn">Search</button>
        <div class="separator"></div>
        <button class="location-btn">Use Current Location</button>
      </div>
      <div class="weather-data">
        <div class="current-weather">
          <div class="details">
            <h2>_______ ( ______ )</h2>
            <h6>Temperature: __°C</h6>
            <h6>Wind: __ M/S</h6>
            <h6>Humidity: __%</h6>
          </div>
        </div>
        <div class="days-forecast">
          <h2>5-Day Forecast</h2>
          <ul class="weather-cards">
            <li class="card">
              <h3>( ______ )</h3>
              <h6>Temp: __C</h6>
              <h6>Wind: __ M/S</h6>
              <h6>Humidity: __%</h6>
            </li>
            <li class="card">
              <h3>( ______ )</h3>
              <h6>Temp: __C</h6>
              <h6>Wind: __ M/S</h6>
              <h6>Humidity: __%</h6>
            </li>
            <li class="card">
              <h3>( ______ )</h3>
              <h6>Temp: __C</h6>
              <h6>Wind: __ M/S</h6>
              <h6>Humidity: __%</h6>
            </li>
            <li class="card">
              <h3>( ______ )</h3>
              <h6>Temp: __C</h6>
              <h6>Wind: __ M/S</h6>
              <h6>Humidity: __%</h6>
            </li>
            <li class="card">
              <h3>( ______ )</h3>
              <h6>Temp: __C</h6>
              <h6>Wind: __ M/S</h6>
              <h6>Humidity: __%</h6>
            </li>
          </ul>
        </div>
      </div>
    </div>
    
  </body>
</html>

Next, add the following CSS codes to your style.css file to apply visual styling to your weather app. Now, if you load the web page in your browser, you will see the header at the top, a sidebar with input and buttons, and weather detail placeholders. You can customize this code to your liking by adjusting the color, font, size, and other CSS properties.

/* Import Google font - Open Sans */
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;500;600;700&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Open Sans', sans-serif;
}
body {
  background: #E3F2FD;
}
h1 {
  background: #5372F0;
  font-size: 1.75rem;
  text-align: center;
  padding: 18px 0;
  color: #fff;
}
.container {
  display: flex;
  gap: 35px;
  padding: 30px;
}
.weather-input {
  width: 550px;
}
.weather-input input {
  height: 46px;
  width: 100%;
  outline: none;
  font-size: 1.07rem;
  padding: 0 17px;
  margin: 10px 0 20px 0;
  border-radius: 4px;
  border: 1px solid #ccc;
}
.weather-input input:focus {
  padding: 0 16px;
  border: 2px solid #5372F0;
}
.weather-input .separator {
  height: 1px;
  width: 100%;
  margin: 25px 0;
  background: #BBBBBB;
  display: flex;
  align-items: center;
  justify-content: center;
}
.weather-input .separator::before{
  content: "or";
  color: #6C757D;
  font-size: 1.18rem;
  padding: 0 15px;
  margin-top: -4px;
  background: #E3F2FD;
}
.weather-input button {
  width: 100%;
  padding: 10px 0;
  cursor: pointer;
  outline: none;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  color: #fff;
  background: #5372F0;
  transition: 0.2s ease;
}
.weather-input .search-btn:hover {
  background: #2c52ed;
}
.weather-input .location-btn {
  background: #6C757D;
}
.weather-input .location-btn:hover {
  background: #5c636a;
}
.weather-data {
  width: 100%;
}
.weather-data .current-weather {
  color: #fff;
  background: #5372F0;
  border-radius: 5px;
  padding: 20px 70px 20px 20px;
  display: flex;
  justify-content: space-between;
}
.current-weather h2 {
  font-weight: 700;
  font-size: 1.7rem;
}
.weather-data h6 {
  margin-top: 12px;
  font-size: 1rem;
  font-weight: 500;
}
.current-weather .icon {
  text-align: center;
}
.current-weather .icon img {
  max-width: 120px;
  margin-top: -15px;
}
.current-weather .icon h6 {
  margin-top: -10px;
  text-transform: capitalize;
}
.days-forecast h2 {
  margin: 20px 0;
  font-size: 1.5rem;
}
.days-forecast .weather-cards {
  display: flex;
  gap: 20px;
}
.weather-cards .card {
  color: #fff;
  padding: 18px 16px;
  list-style: none;
  width: calc(100% / 5);
  background: #6C757D;
  border-radius: 5px;
}
.weather-cards .card h3 {
  font-size: 1.3rem;
  font-weight: 600;
}
.weather-cards .card img {
  max-width: 70px;
  margin: 5px 0 -12px 0;
}

@media (max-width: 1400px) {
  .weather-data .current-weather {
    padding: 20px;
  }
  .weather-cards {
    flex-wrap: wrap;
  }
  .weather-cards .card {
    width: calc(100% / 4 - 15px);
  }
}
@media (max-width: 1200px) {
  .weather-cards .card {
    width: calc(100% / 3 - 15px);
  }
}
@media (max-width: 950px) {
  .weather-input {
    width: 450px;
  }
  .weather-cards .card {
    width: calc(100% / 2 - 10px);
  }
}
@media (max-width: 750px) {
  h1 {
    font-size: 1.45rem;
    padding: 16px 0;
  }
  .container {
    flex-wrap: wrap;
    padding: 15px;
  }
  .weather-input {
    width: 100%;
  }
  .weather-data h2 {
    font-size: 1.35rem;
  }
}

Finally, add the following JavaScript code to your script.js file. This script code will make your weather app functional, which means now you can get a 5-day weather forecast for any city or your current location.

const cityInput = document.querySelector(".city-input");
const searchButton = document.querySelector(".search-btn");
const locationButton = document.querySelector(".location-btn");
const currentWeatherDiv = document.querySelector(".current-weather");
const weatherCardsDiv = document.querySelector(".weather-cards");

const API_KEY = "YOUR-API-KEY-HERE"; // API key for OpenWeatherMap API

const createWeatherCard = (cityName, weatherItem, index) => {
    if(index === 0) { // HTML for the main weather card
        return `<div class="details">
                    <h2>${cityName} (${weatherItem.dt_txt.split(" ")[0]})</h2>
                    <h6>Temperature: ${(weatherItem.main.temp - 273.15).toFixed(2)}°C</h6>
                    <h6>Wind: ${weatherItem.wind.speed} M/S</h6>
                    <h6>Humidity: ${weatherItem.main.humidity}%</h6>
                </div>
                <div class="icon">
                    <img src="https://openweathermap.org/img/wn/${weatherItem.weather[0].icon}@4x.png" alt="weather-icon">
                    <h6>${weatherItem.weather[0].description}</h6>
                </div>`;
    } else { // HTML for the other five day forecast card
        return `<li class="card">
                    <h3>(${weatherItem.dt_txt.split(" ")[0]})</h3>
                    <img src="https://openweathermap.org/img/wn/${weatherItem.weather[0].icon}@4x.png" alt="weather-icon">
                    <h6>Temp: ${(weatherItem.main.temp - 273.15).toFixed(2)}°C</h6>
                    <h6>Wind: ${weatherItem.wind.speed} M/S</h6>
                    <h6>Humidity: ${weatherItem.main.humidity}%</h6>
                </li>`;
    }
}

const getWeatherDetails = (cityName, latitude, longitude) => {
    const WEATHER_API_URL = `https://api.openweathermap.org/data/2.5/forecast?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;

    fetch(WEATHER_API_URL).then(response => response.json()).then(data => {
        // Filter the forecasts to get only one forecast per day
        const uniqueForecastDays = [];
        const fiveDaysForecast = data.list.filter(forecast => {
            const forecastDate = new Date(forecast.dt_txt).getDate();
            if (!uniqueForecastDays.includes(forecastDate)) {
                return uniqueForecastDays.push(forecastDate);
            }
        });

        // Clearing previous weather data
        cityInput.value = "";
        currentWeatherDiv.innerHTML = "";
        weatherCardsDiv.innerHTML = "";

        // Creating weather cards and adding them to the DOM
        fiveDaysForecast.forEach((weatherItem, index) => {
            const html = createWeatherCard(cityName, weatherItem, index);
            if (index === 0) {
                currentWeatherDiv.insertAdjacentHTML("beforeend", html);
            } else {
                weatherCardsDiv.insertAdjacentHTML("beforeend", html);
            }
        });        
    }).catch(() => {
        alert("An error occurred while fetching the weather forecast!");
    });
}

const getCityCoordinates = () => {
    const cityName = cityInput.value.trim();
    if (cityName === "") return;
    const API_URL = `https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${API_KEY}`;
    
    // Get entered city coordinates (latitude, longitude, and name) from the API response
    fetch(API_URL).then(response => response.json()).then(data => {
        if (!data.length) return alert(`No coordinates found for ${cityName}`);
        const { lat, lon, name } = data[0];
        getWeatherDetails(name, lat, lon);
    }).catch(() => {
        alert("An error occurred while fetching the coordinates!");
    });
}

const getUserCoordinates = () => {
    navigator.geolocation.getCurrentPosition(
        position => {
            const { latitude, longitude } = position.coords; // Get coordinates of user location
            // Get city name from coordinates using reverse geocoding API
            const API_URL = `https://api.openweathermap.org/geo/1.0/reverse?lat=${latitude}&lon=${longitude}&limit=1&appid=${API_KEY}`;
            fetch(API_URL).then(response => response.json()).then(data => {
                const { name } = data[0];
                getWeatherDetails(name, latitude, longitude);
            }).catch(() => {
                alert("An error occurred while fetching the city name!");
            });
        },
        error => { // Show alert if user denied the location permission
            if (error.code === error.PERMISSION_DENIED) {
                alert("Geolocation request denied. Please reset location permission to grant access again.");
            } else {
                alert("Geolocation request error. Please reset location permission.");
            }
        });
}

locationButton.addEventListener("click", getUserCoordinates);
searchButton.addEventListener("click", getCityCoordinates);
cityInput.addEventListener("keyup", e => e.key === "Enter" && getCityCoordinates());

Please note that your weather app is still unable to show the weather forecast for any location because you’ve not provided your OpenWeatherMap API key in the API_KEY variable. To get a free API key, sign up for an account at https://home.openweathermap.org/api_keys. Your API key may take minutes or hours to activate. You’ll get an error like “Invalid API Key” or something similar during this time.

In the code, there are two API calls. The first one fetches the geographic coordinates of the user-entered city. These coordinates are then used in the second API call to retrieve the weather forecast, which is displayed on the page. The code also includes a feature that asks for user location permission and, once granted, makes the second API call to fetch the weather forecast based on the user’s current location.

Conclusion and Final Words

In conclusion, building a weather app project allows you to apply your web development skills to a real-world application. Also, it helps you to better understand DOM manipulation, Event handling, CSS styling, APIs, and more. I hope that by following the steps in this post, you’ve successfully created your weather app using HTML, CSS, and JavaScript.

To understand this project’s code better, I recommend watching the above tutorial video, reading the code comments, and experimenting with the code. If you want to further enhance your web development skills, you should try recreating the Working Chatbot using HTML, CSS, and JavaScript.

If you encounter any difficulties while creating your weather app or your code is not working as expected, you can download the source code files for this weather app project for free by clicking the Download button. Keep in mind that after downloading the file, you’ll have to paste an “OpenWeatherMap API Key into the API_KEY variable in the script.js file.

]]>
https://www.codingnepalweb.com/weather-app-project-html-javascript/feed/ 0
How to Create Working Chatbot in HTML CSS and JavaScript https://www.codingnepalweb.com/create-chatbot-html-css-javascript/ https://www.codingnepalweb.com/create-chatbot-html-css-javascript/#respond Wed, 14 Jun 2023 11:42:10 +0000 https://www.codingnepalweb.com/?p=5582 How to Create Working Chatbot in HTML CSS and JavaScript

You may have seen chatbots on multiple websites, as they are now essential components for modern websites and apps. If you are unfamiliar, a chatbot is a computer program that serves as a virtual assistant and is capable of understanding user queries and providing relevant responses.

Building a chatbot is a practical way for beginner web developers to gain hands-on experience with HTML, CSS, and JavaScript, as these skills are crucial for creating real-world projects. So, in this blog post, I’ll guide you through creating a working chatbot using HTML, CSS, and JavaScript from scratch.

In this chatbot, users can ask any question and receive instant responses. This chatbot has an elegant and responsive user interface, ensuring a seamless experience across various devices. Keep in mind that to generate a response to the user query, this chatbot uses the OpenAI API, which is free.

Video Tutorial of Chatbot in HTML CSS & JavaScript

If you prefer learning through video tutorials, the provided video is an excellent resource for you to understand the process of creating your own functional chatbot. In the video, I explain each line of code and provide informative comments to make it beginner-friendly and easy to follow.

However, if you prefer reading blog posts or want a quick summary of the steps involved in creating this chatbot project, you can continue reading this post. By the end of this post, you will have your own chatbot that you can use to ask questions or integrate into your website or existing web projects.

Steps To Create Working Chatbot in HTML & JavaScript

To create your own working chatbot using HTML, CSS, and JavaScript, follow these step-by-step instructions:

  1. Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a script.js file. The file name must be script and its extension .js

To start, add the following HTML codes to your index.html file: This code snippet includes a chatbot header, a chatbox unordered list (ul), and an input field for user messages. By default, the chatbot will display a greeting message as the first chat “li”. We’ll use JavaScript later to dynamically add more chat “li” that contain chat details.

<!DOCTYPE html>
<!-- Coding By CodingNepal - www.codingnepalweb.com -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Chatbot in JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Google Fonts Link For Icons -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@48,400,1,0" />
    <script src="script.js" defer></script>
  </head>
  <body>
    <button class="chatbot-toggler">
      <span class="material-symbols-rounded">mode_comment</span>
      <span class="material-symbols-outlined">close</span>
    </button>
    <div class="chatbot">
      <header>
        <h2>Chatbot</h2>
        <span class="close-btn material-symbols-outlined">close</span>
      </header>
      <ul class="chatbox">
        <li class="chat incoming">
          <span class="material-symbols-outlined">smart_toy</span>
          <p>Hi there 👋<br>How can I help you today?</p>
        </li>
      </ul>
      <div class="chat-input">
        <textarea placeholder="Enter a message..." spellcheck="false" required></textarea>
        <span id="send-btn" class="material-symbols-rounded">send</span>
      </div>
    </div>

  </body>
</html>

Next, add the following CSS codes to your style.css file to apply visual styling to your chatbot. Now, if you load the web page in your browser, you will only see the chatbot toggle button at the bottom right corner. You can customize this code to your liking by adjusting the color, font, size, and other CSS properties.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background: #E3F2FD;
}
.chatbot-toggler {
  position: fixed;
  bottom: 30px;
  right: 35px;
  outline: none;
  border: none;
  height: 50px;
  width: 50px;
  display: flex;
  cursor: pointer;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #724ae8;
  transition: all 0.2s ease;
}
body.show-chatbot .chatbot-toggler {
  transform: rotate(90deg);
}
.chatbot-toggler span {
  color: #fff;
  position: absolute;
}
.chatbot-toggler span:last-child,
body.show-chatbot .chatbot-toggler span:first-child  {
  opacity: 0;
}
body.show-chatbot .chatbot-toggler span:last-child {
  opacity: 1;
}
.chatbot {
  position: fixed;
  right: 35px;
  bottom: 90px;
  width: 420px;
  background: #fff;
  border-radius: 15px;
  overflow: hidden;
  opacity: 0;
  pointer-events: none;
  transform: scale(0.5);
  transform-origin: bottom right;
  box-shadow: 0 0 128px 0 rgba(0,0,0,0.1),
              0 32px 64px -48px rgba(0,0,0,0.5);
  transition: all 0.1s ease;
}
body.show-chatbot .chatbot {
  opacity: 1;
  pointer-events: auto;
  transform: scale(1);
}
.chatbot header {
  padding: 16px 0;
  position: relative;
  text-align: center;
  color: #fff;
  background: #724ae8;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.chatbot header span {
  position: absolute;
  right: 15px;
  top: 50%;
  display: none;
  cursor: pointer;
  transform: translateY(-50%);
}
header h2 {
  font-size: 1.4rem;
}
.chatbot .chatbox {
  overflow-y: auto;
  height: 510px;
  padding: 30px 20px 100px;
}
.chatbot :where(.chatbox, textarea)::-webkit-scrollbar {
  width: 6px;
}
.chatbot :where(.chatbox, textarea)::-webkit-scrollbar-track {
  background: #fff;
  border-radius: 25px;
}
.chatbot :where(.chatbox, textarea)::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 25px;
}
.chatbox .chat {
  display: flex;
  list-style: none;
}
.chatbox .outgoing {
  margin: 20px 0;
  justify-content: flex-end;
}
.chatbox .incoming span {
  width: 32px;
  height: 32px;
  color: #fff;
  cursor: default;
  text-align: center;
  line-height: 32px;
  align-self: flex-end;
  background: #724ae8;
  border-radius: 4px;
  margin: 0 10px 7px 0;
}
.chatbox .chat p {
  white-space: pre-wrap;
  padding: 12px 16px;
  border-radius: 10px 10px 0 10px;
  max-width: 75%;
  color: #fff;
  font-size: 0.95rem;
  background: #724ae8;
}
.chatbox .incoming p {
  border-radius: 10px 10px 10px 0;
}
.chatbox .chat p.error {
  color: #721c24;
  background: #f8d7da;
}
.chatbox .incoming p {
  color: #000;
  background: #f2f2f2;
}
.chatbot .chat-input {
  display: flex;
  gap: 5px;
  position: absolute;
  bottom: 0;
  width: 100%;
  background: #fff;
  padding: 3px 20px;
  border-top: 1px solid #ddd;
}
.chat-input textarea {
  height: 55px;
  width: 100%;
  border: none;
  outline: none;
  resize: none;
  max-height: 180px;
  padding: 15px 15px 15px 0;
  font-size: 0.95rem;
}
.chat-input span {
  align-self: flex-end;
  color: #724ae8;
  cursor: pointer;
  height: 55px;
  display: flex;
  align-items: center;
  visibility: hidden;
  font-size: 1.35rem;
}
.chat-input textarea:valid ~ span {
  visibility: visible;
}

@media (max-width: 490px) {
  .chatbot-toggler {
    right: 20px;
    bottom: 20px;
  }
  .chatbot {
    right: 0;
    bottom: 0;
    height: 100%;
    border-radius: 0;
    width: 100%;
  }
  .chatbot .chatbox {
    height: 90%;
    padding: 25px 15px 100px;
  }
  .chatbot .chat-input {
    padding: 5px 15px;
  }
  .chatbot header span {
    display: block;
  }
}

Finally, add the following JavaScript code to your script.js file: This script code will make your chatbot functional, which means now you can ask your questions, show or hide the chatbot by clicking the bottom right toggle button, and more.

const chatbotToggler = document.querySelector(".chatbot-toggler");
const closeBtn = document.querySelector(".close-btn");
const chatbox = document.querySelector(".chatbox");
const chatInput = document.querySelector(".chat-input textarea");
const sendChatBtn = document.querySelector(".chat-input span");

let userMessage = null; // Variable to store user's message
const API_KEY = "PASTE-YOUR-API-KEY"; // Paste your API key here
const inputInitHeight = chatInput.scrollHeight;

const createChatLi = (message, className) => {
    // Create a chat <li> element with passed message and className
    const chatLi = document.createElement("li");
    chatLi.classList.add("chat", `${className}`);
    let chatContent = className === "outgoing" ? `<p></p>` : `<span class="material-symbols-outlined">smart_toy</span><p></p>`;
    chatLi.innerHTML = chatContent;
    chatLi.querySelector("p").textContent = message;
    return chatLi; // return chat <li> element
}

const generateResponse = (chatElement) => {
    const API_URL = "https://api.openai.com/v1/chat/completions";
    const messageElement = chatElement.querySelector("p");

    // Define the properties and message for the API request
    const requestOptions = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
            model: "gpt-3.5-turbo",
            messages: [{role: "user", content: userMessage}],
        })
    }

    // Send POST request to API, get response and set the reponse as paragraph text
    fetch(API_URL, requestOptions).then(res => res.json()).then(data => {
        messageElement.textContent = data.choices[0].message.content.trim();
    }).catch(() => {
        messageElement.classList.add("error");
        messageElement.textContent = "Oops! Something went wrong. Please try again.";
    }).finally(() => chatbox.scrollTo(0, chatbox.scrollHeight));
}

const handleChat = () => {
    userMessage = chatInput.value.trim(); // Get user entered message and remove extra whitespace
    if(!userMessage) return;

    // Clear the input textarea and set its height to default
    chatInput.value = "";
    chatInput.style.height = `${inputInitHeight}px`;

    // Append the user's message to the chatbox
    chatbox.appendChild(createChatLi(userMessage, "outgoing"));
    chatbox.scrollTo(0, chatbox.scrollHeight);
    
    setTimeout(() => {
        // Display "Thinking..." message while waiting for the response
        const incomingChatLi = createChatLi("Thinking...", "incoming");
        chatbox.appendChild(incomingChatLi);
        chatbox.scrollTo(0, chatbox.scrollHeight);
        generateResponse(incomingChatLi);
    }, 600);
}

chatInput.addEventListener("input", () => {
    // Adjust the height of the input textarea based on its content
    chatInput.style.height = `${inputInitHeight}px`;
    chatInput.style.height = `${chatInput.scrollHeight}px`;
});

chatInput.addEventListener("keydown", (e) => {
    // If Enter key is pressed without Shift key and the window 
    // width is greater than 800px, handle the chat
    if(e.key === "Enter" && !e.shiftKey && window.innerWidth > 800) {
        e.preventDefault();
        handleChat();
    }
});

sendChatBtn.addEventListener("click", handleChat);
closeBtn.addEventListener("click", () => document.body.classList.remove("show-chatbot"));
chatbotToggler.addEventListener("click", () => document.body.classList.toggle("show-chatbot"));

Please note that your chatbot is currently unable to retrieve responses to your questions because you have not provided your API key in the AP_KEY variable. To get a free API key from OpenAI, sign up for an account at https://platform.openai.com/account/api-keys.

” Remember that when you sign up for OpenAI, you’ll get a free $5 credit for your API usage. If your account is older than 3 months or the credit runs out, you’ll need a paid account or create a new one with a new number to keep using the API. Your API usage and expiration date can be found on the account’s usage page.”

The above code provided follows a simple flow. First, it displays the user’s message in the chatbox and uses the OpenAI API to generate an appropriate response to the message. While waiting for the API response, a “Thinking…” message is shown. Once the response is received, it replaces the “Thinking…” message in the chatbox.

To understand codes better, I recommend watching the above tutorial video, reading the code comments, and experimenting with the code.

Conclusion and Final Words

In conclusion, creating a working chatbot allows you to apply your skills to a real-world application. I hope that by following the steps in this post, you’ve successfully created your own chatbot using HTML, CSS, and JavaScript.

To further improve your web development skills, you can try recreating the ChatGPT Clone Project using HTML, CSS, and JavaScript. This project helps you expand your knowledge by creating a ChatGPT clone with additional features like dark/light themes and saved chats using local storage.

If you encounter any difficulties while creating your own Chatbot or your code is not working as expected, you can download the source code files for this Chatbot project for free by clicking the Download button. Remember that after downloading the file, you’ll have to paste an “OpenAI API key” into the API_KEY variable in the script.js file.

 

]]>
https://www.codingnepalweb.com/create-chatbot-html-css-javascript/feed/ 0
Create Weather App in HTML Bootstrap and JavaScript https://www.codingnepalweb.com/weather-app-html-bootstrap-javascript/ https://www.codingnepalweb.com/weather-app-html-bootstrap-javascript/#respond Fri, 09 Jun 2023 13:00:33 +0000 https://www.codingnepalweb.com/?p=5568 Create A Weather App in HTML Bootstrap and JavaScript

In today’s digital age, weather apps have become an essential tool for staying informed about ever-changing weather conditions. As a beginner web developer, the idea of creating your weather app can be both exciting and educational.

In this blog post, I’ll guide you through the steps of creating a responsive weather app project using HTML, Bootstrap, and JavaScript. By creating this weather project, not only will you learn the basics of DOM manipulation, event handling, and CSS styling, but you’ll also gain valuable experience working with APIs.

In this weather app, users can enter the name of a city and get different weather details like temperature in Celsius, wind speed, humidity, and a 5-day forecast. But if you wish, you can easily add or remove the particular weather details because we’ll use the OpenWeatherMap API, so you’ll have access to a wide array of weather information.

Steps To Create Weather App in Bootstrap & JavaScript

To create your own weather app project using HTML, Bootstrap, and JavaScript, follow these step-by-step instructions:

  1. Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a script.js file. The file name must be script and its extension .js

To start, add the following HTML codes to your index.html file. Since we’ve used Bootstrap for this project, the design, and layout are almost ready and responsive. After saving the HTML file and opening it in your browser, you’ll see a header, a search box on the left side, and some placeholders for weather details.

<!DOCTYPE html>
<!-- Coding By CodingNepal - www.codingnepalweb.com -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Weather App Project | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <script src="script.js" defer></script>
  </head>
  <body>
    <header class="bg-success text-center py-3">
      <h1 class="fw-bold h3 text-white my-1">Weather Dashboard</h1>
    </header>
    <div class="container-fluid my-4 weather-data">
      <div class="row">
        <div class="col-xxl-3 col-md-4 px-lg-4">
          <h5 class="fw-bold">Enter a City Name</h5>
          <input type="text" id="city-input" class="py-2 form-control" placeholder="E.g., New York, London, Tokyo">
          <button id="search-btn" class="btn btn-success py-2 w-100 mt-3 mb-2">Search</button>
        </div>
        <div class="col-xxl-9 col-md-8 mt-md-1 mt-4 pe-lg-4">
          <div class="current-weather bg-success text-white py-2 px-4 rounded-3">
            <div class="mt-3 d-flex justify-content-between">
              <div>
                <h3 class="fw-bold">_______ ( ______ )</h3>
                <h6 class="my-3 mt-3">Temperature: __°C</h6>
                <h6 class="my-3">Wind: __ M/S</h6>
                <h6 class="my-3">Humidity: __%</h6>
              </div>
          </div>
          </div>
          <h4 class="fw-bold my-4">5-Day Forecast</h4>
          <div class="days-forecast row row-cols-1 row-cols-sm-2 row-cols-lg-4 row-cols-xl-5 justify-content-between">
            <div class="col mb-3">
              <div class="card border-0 bg-secondary text-white">
                <div class="card-body p-3 text-white">
                  <h5 class="card-title fw-semibold">( ______ )</h5>
                  <h6 class="card-text my-3 mt-3">Temp: __°C</h6>
                  <h6 class="card-text my-3">Wind: __ M/S</h6>
                  <h6 class="card-text my-3">Humidity: __%</h6>
                </div>
              </div>
            </div>
            <div class="col mb-3">
              <div class="card border-0 bg-secondary text-white">
                <div class="card-body p-3 text-white">
                  <h5 class="card-title fw-semibold">( ______ )</h5>
                  <h6 class="card-text my-3 mt-3">Temp: __°C</h6>
                  <h6 class="card-text my-3">Wind: __ M/S</h6>
                  <h6 class="card-text my-3">Humidity: __%</h6>
                </div>
              </div>
            </div>
            <div class="col mb-3">
              <div class="card border-0 bg-secondary text-white">
                <div class="card-body p-3 text-white">
                  <h5 class="card-title fw-semibold">( ______ )</h5>
                  <h6 class="card-text my-3 mt-3">Temp: __°C</h6>
                  <h6 class="card-text my-3">Wind: __ M/S</h6>
                  <h6 class="card-text my-3">Humidity: __%</h6>
                </div>
              </div>
            </div>
            <div class="col mb-3">
              <div class="card border-0 bg-secondary text-white">
                <div class="card-body p-3 text-white">
                  <h5 class="card-title fw-semibold">( ______ )</h5>
                  <h6 class="card-text my-3 mt-3">Temp: __°C</h6>
                  <h6 class="card-text my-3">Wind: __ M/S</h6>
                  <h6 class="card-text my-3">Humidity: __%</h6>
                </div>
              </div>
            </div>
            <div class="col mb-3">
              <div class="card border-0 bg-secondary text-white">
                <div class="card-body p-3 text-white">
                  <h5 class="card-title fw-semibold">( ______ )</h5>
                  <h6 class="card-text my-3 mt-3">Temp: __°C</h6>
                  <h6 class="card-text my-3">Wind: __ M/S</h6>
                  <h6 class="card-text my-3">Humidity: __%</h6>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

  </body>
</html>

Next, add the following few CSS codes to your style.css file to add custom styling to some elements like font family, and image width.

/* Import Google font - Open Sans */
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;500;600;700;800&display=swap');

* {
  font-family: 'Open Sans', sans-serif;
}

.current-weather img {
  max-width: 120px;
  margin-top: -15px;
}

Finally, add the following JavaScript code to your script.js file to make the weather app functional, which means getting different weather details for an entered city.

const cityInput = document.querySelector("#city-input");
const searchButton = document.querySelector("#search-btn");
const currentWeatherDiv = document.querySelector(".current-weather");
const daysForecastDiv = document.querySelector(".days-forecast");

const API_KEY = "PASTE-YOUR-API-KEY"; // Paste your API here

// Create weather card HTML based on weather data
const createWeatherCard = (cityName, weatherItem, index) => {
    if(index === 0) {
        return `<div class="mt-3 d-flex justify-content-between">
                    <div>
                        <h3 class="fw-bold">${cityName} (${weatherItem.dt_txt.split(" ")[0]})</h3>
                        <h6 class="my-3 mt-3">Temperature: ${((weatherItem.main.temp - 273.15).toFixed(2))}°C</h6>
                        <h6 class="my-3">Wind: ${weatherItem.wind.speed} M/S</h6>
                        <h6 class="my-3">Humidity: ${weatherItem.main.humidity}%</h6>
                    </div>
                    <div class="text-center me-lg-5">
                        <img src="https://openweathermap.org/img/wn/${weatherItem.weather[0].icon}@4x.png" alt="weather icon">
                        <h6>${weatherItem.weather[0].description}</h6>
                    </div>
                </div>`;
    } else {
        return `<div class="col mb-3">
                    <div class="card border-0 bg-secondary text-white">
                        <div class="card-body p-3 text-white">
                            <h5 class="card-title fw-semibold">(${weatherItem.dt_txt.split(" ")[0]})</h5>
                            <img src="https://openweathermap.org/img/wn/${weatherItem.weather[0].icon}.png" alt="weather icon">
                            <h6 class="card-text my-3 mt-3">Temp: ${((weatherItem.main.temp - 273.15).toFixed(2))}°C</h6>
                            <h6 class="card-text my-3">Wind: ${weatherItem.wind.speed} M/S</h6>
                            <h6 class="card-text my-3">Humidity: ${weatherItem.main.humidity}%</h6>
                        </div>
                    </div>
                </div>`;
    }
}

// Get weather details of passed latitude and longitude
const getWeatherDetails = (cityName, latitude, longitude) => {
    const WEATHER_API_URL = `https://api.openweathermap.org/data/2.5/forecast?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;

    fetch(WEATHER_API_URL).then(response => response.json()).then(data => {
        const forecastArray = data.list;
        const uniqueForecastDays = new Set();

        const fiveDaysForecast = forecastArray.filter(forecast => {
            const forecastDate = new Date(forecast.dt_txt).getDate();
            if (!uniqueForecastDays.has(forecastDate) && uniqueForecastDays.size < 6) {
                uniqueForecastDays.add(forecastDate);
                return true;
            }
            return false;
        });

        cityInput.value = "";
        currentWeatherDiv.innerHTML = "";
        daysForecastDiv.innerHTML = "";

        fiveDaysForecast.forEach((weatherItem, index) => {
            const html = createWeatherCard(cityName, weatherItem, index);
            if (index === 0) {
                currentWeatherDiv.insertAdjacentHTML("beforeend", html);
            } else {
                daysForecastDiv.insertAdjacentHTML("beforeend", html);
            }
        });        
    }).catch(() => {
        alert("An error occurred while fetching the weather forecast!");
    });
}

// Get coordinates of entered city name
const getCityCoordinates = () => {
    const cityName = cityInput.value.trim();
    if (cityName === "") return;
    const API_URL = `https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${API_KEY}`;
  
    fetch(API_URL).then(response => response.json()).then(data => {
        if (!data.length) return alert(`No coordinates found for ${cityName}`);
        const { lat, lon, name } = data[0];
        getWeatherDetails(name, lat, lon);
    }).catch(() => {
        alert("An error occurred while fetching the coordinates!");
    });
}

searchButton.addEventListener("click", () => getCityCoordinates());

Please note that your weather app is currently unable to retrieve weather details because you have not provided your API key in the AP_KEY variable. To get a free API key from OpenWeatherMap, sign up for an account at https://home.openweathermap.org/api_keys.

In the code, there are two API calls. The first call gets the geographic coordinates of the city entered by the user. These coordinates are then used in the second call to retrieve the weather details, which are subsequently displayed on the page. Feel free to experiment with the code to gain a better understanding of its functionality.

Conclusion and Final Words

In conclusion, this blog post has guided you through the process of creating your own weather app using HTML, Bootstrap, and JavaScript. By following the steps outlined here, I hope you have successfully created your own weather app and learned how to work with APIs.

In addition to this weather app project, you can explore other exciting Bootstrap and JavaScript API projects available on this website to enhance your web development skills. These include Bootstrap Websites, ChatGPT Clone, Functional Image Gallery, Currency Converter, and more.

If you encounter any difficulties while creating your own weather app or your code is not working as expected, you can download the source code files for this weather app project for free by clicking the Download button. You can also view a live demo of it by clicking the View Live button.

]]>
https://www.codingnepalweb.com/weather-app-html-bootstrap-javascript/feed/ 0
How to Create Your Own ChatGPT in HTML CSS and JavaScript https://www.codingnepalweb.com/create-chatgpt-clone-html-css-javascript/ https://www.codingnepalweb.com/create-chatgpt-clone-html-css-javascript/#respond Wed, 31 May 2023 08:17:30 +0000 https://www.codingnepalweb.com/?p=5535 Create Your Own ChatGPT in HTML, CSS, and JavaScript ChatGPT Clone HTML, CSS, and JavaScript

ChatGPT has gained significant popularity in recent months or years, completely changing how we interact with automated chatbots. As a beginner web developer, you might be curious about creating your own ChatGPT. The good news is that it is possible to create a ChatGPT clone using HTML, CSS, and vanilla JavaScript.

If you’re unfamiliar, ChatGPT is an advanced chatbot model developed by OpenAI. It uses artificial intelligence to generate human-like responses in a conversational format. ChatGPT has gained widespread popularity due to its ability to simulate natural conversations.

In this blog post, we will guide you through the steps of creating your very own ChatGPT using HTML, CSS, and JavaScript. By building a ChatGPT clone project, beginner web developers can gain practical experience by applying their HTML, CSS, and JavaScript skills to real-world projects.

This ChatGPT clone project allows you to ask questions and receive instant responses. Additionally, you have the option to switch between dark and light themes. Your chat history is saved in the browser’s local storage, ensuring it remains even if you refresh the page. However, you can easily delete chats by clicking on the dedicated “Delete Chat” button.

Video Tutorial of ChatGPT Clone in HTML & JavaScript

If you prefer learning through video tutorials, the provided video is an excellent resource for you to understand the process of creating your own ChatGPT. In the video, I explain each line of code and provide informative comments to make it beginner-friendly and easy to follow.

However, if you prefer reading blog posts or want a quick summary of the steps involved in creating a ChatGPT clone project, you can continue reading this post. By the end of this post, you will have your own ChatGPT that you can chat with.

Steps To Create ChatGPT Clone in HTML & JavaScript

To create your own ChatGPT using HTML, CSS, and JavaScript, follow these step-by-step instructions:

  1. Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a script.js file. The file name must be script and its extension .js
  5. Download and place the images folder in your project directory. This folder includes the user avatar and chatbot logo.

To start, add the following HTML codes to your index.html file: In this code snippet, you will find an empty “chat-container” div. We will later use JavaScript to dynamically add the “chat” div that will contain all the chat details.

<!DOCTYPE html>
<!-- Coding By CodingNepal - www.codingnepalweb.com -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>ChatGPT Clone in JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Google Fonts Link For Icons -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" />
    <script src="script.js" defer></script>
  </head>
  <body>
    <!-- Chats container -->
    <div class="chat-container"></div>
    
    <!-- Typing container -->
    <div class="typing-container">
      <div class="typing-content">
        <div class="typing-textarea">
          <textarea id="chat-input" spellcheck="false" placeholder="Enter a prompt here" required></textarea>
          <span id="send-btn" class="material-symbols-rounded">send</span>
        </div>
        <div class="typing-controls">
          <span id="theme-btn" class="material-symbols-rounded">light_mode</span>
          <span id="delete-btn" class="material-symbols-rounded">delete</span>
      </div>
    </div>

  </body>
</html>

Next, add the following CSS codes to your style.css file to apply visual styling to your ChatGPT interface. Now, if you load the web page in your browser, you will see ChatGPT displayed with a text input box and some icons at the bottom.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
:root {
  --text-color: #FFFFFF;
  --icon-color: #ACACBE;
  --icon-hover-bg: #5b5e71;
  --placeholder-color: #dcdcdc;
  --outgoing-chat-bg: #343541;
  --incoming-chat-bg: #444654;
  --outgoing-chat-border: #343541;
  --incoming-chat-border: #444654;
}
.light-mode {
  --text-color: #343541;
  --icon-color: #a9a9bc;
  --icon-hover-bg: #f1f1f3;
  --placeholder-color: #6c6c6c;
  --outgoing-chat-bg: #FFFFFF;
  --incoming-chat-bg: #F7F7F8;
  --outgoing-chat-border: #FFFFFF;
  --incoming-chat-border: #D9D9E3;
}
body {
  background: var(--outgoing-chat-bg);
}

/* Chats container styling */
.chat-container {
  overflow-y: auto;
  max-height: 100vh;
  padding-bottom: 150px;
}
:where(.chat-container, textarea)::-webkit-scrollbar {
  width: 6px;
}
:where(.chat-container, textarea)::-webkit-scrollbar-track {
  background: var(--incoming-chat-bg);
  border-radius: 25px;
}
:where(.chat-container, textarea)::-webkit-scrollbar-thumb {
  background: var(--icon-color);
  border-radius: 25px;
}
.default-text {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: 70vh;
  padding: 0 10px;
  text-align: center;
  color: var(--text-color);
}
.default-text h1 {
  font-size: 3.3rem;
}
.default-text p {
  margin-top: 10px;
  font-size: 1.1rem;
}
.chat-container .chat {
  padding: 25px 10px;
  display: flex;
  justify-content: center;
  color: var(--text-color);
}
.chat-container .chat.outgoing {
  background: var(--outgoing-chat-bg);
  border: 1px solid var(--outgoing-chat-border);
}
.chat-container .chat.incoming {
  background: var(--incoming-chat-bg);
  border: 1px solid var(--incoming-chat-border);
}
.chat .chat-content {
  display: flex;
  max-width: 1200px;
  width: 100%;
  align-items: flex-start;
  justify-content: space-between;
}
span.material-symbols-rounded {
  user-select: none;
  cursor: pointer;
}
.chat .chat-content span {
  cursor: pointer;
  font-size: 1.3rem;
  color: var(--icon-color);
  visibility: hidden;
}
.chat:hover .chat-content:not(:has(.typing-animation), :has(.error)) span {
  visibility: visible;
}
.chat .chat-details {
  display: flex;
  align-items: center;
}
.chat .chat-details img {
  width: 35px;
  height: 35px;
  align-self: flex-start;
  object-fit: cover;
  border-radius: 2px;
}
.chat .chat-details p {
  white-space: pre-wrap;
  font-size: 1.05rem;
  padding: 0 50px 0 25px;
  color: var(--text-color);
  word-break: break-word;
}
.chat .chat-details p.error {
  color: #e55865;
}
.chat .typing-animation {
  padding-left: 25px;
  display: inline-flex;
}
.typing-animation .typing-dot {
  height: 7px;
  width: 7px;
  border-radius: 50%;
  margin: 0 3px;
  opacity: 0.7;
  background: var(--text-color);
  animation: animateDots 1.5s var(--delay) ease-in-out infinite;
}
.typing-animation .typing-dot:first-child {
  margin-left: 0;
}
@keyframes animateDots {
  0%,44% {
    transform: translateY(0px);
  }
  28% {
    opacity: 0.4;
    transform: translateY(-6px);
  }
  44% {
    opacity: 0.2;
  }
}

/* Typing container styling */
.typing-container {
  position: fixed;
  bottom: 0;
  width: 100%;
  display: flex;
  padding: 20px 10px;
  justify-content: center;
  background: var(--outgoing-chat-bg);
  border-top: 1px solid var(--incoming-chat-border);
}
.typing-container .typing-content {
  display: flex;
  max-width: 950px;
  width: 100%;
  align-items: flex-end;
}
.typing-container .typing-textarea {
  width: 100%;
  display: flex;
  position: relative;
}
.typing-textarea textarea {
  resize: none;
  height: 55px;
  width: 100%;
  border: none;
  padding: 15px 45px 15px 20px;
  color: var(--text-color);
  font-size: 1rem;
  border-radius: 4px;
  max-height: 250px;
  overflow-y: auto;
  background: var(--incoming-chat-bg);
  outline: 1px solid var(--incoming-chat-border);
}
.typing-textarea textarea::placeholder {
  color: var(--placeholder-color);
}
.typing-content span {
  width: 55px;
  height: 55px;
  display: flex;
  border-radius: 4px;
  font-size: 1.35rem;
  align-items: center;
  justify-content: center;
  color: var(--icon-color);
}
.typing-textarea span {
  position: absolute;
  right: 0;
  bottom: 0;
  visibility: hidden;
}
.typing-textarea textarea:valid ~ span {
  visibility: visible;
}
.typing-controls {
  display: flex;
}
.typing-controls span {
  margin-left: 7px;
  font-size: 1.4rem;
  background: var(--incoming-chat-bg);
  outline: 1px solid var(--incoming-chat-border);
}
.typing-controls span:hover {
  background: var(--icon-hover-bg);
}

/* Reponsive Media Query */
@media screen and (max-width: 600px) {
  .default-text h1 {
    font-size: 2.3rem;
  }
  :where(.default-text p, textarea, .chat p) {
    font-size: 0.95rem!important;
  }
  .chat-container .chat {
    padding: 20px 10px;
  }
  .chat-container .chat img {
    height: 32px;
    width: 32px;
  }
  .chat-container .chat p {
    padding: 0 20px;
  }
  .chat .chat-content:not(:has(.typing-animation), :has(.error)) span {
    visibility: visible;
  }
  .typing-container {
    padding: 15px 10px;
  }
  .typing-textarea textarea {
    height: 45px;
    padding: 10px 40px 10px 10px;
  }
  .typing-content span {
    height: 45px;
    width: 45px;
    margin-left: 5px;
  }
  span.material-symbols-rounded {
    font-size: 1.25rem!important;
  }
}

Finally, add the following JavaScript code to your script.js file. This script code will make your ChatGPT functional by enabling features such as chatting, switching between dark and light themes, and saving chat history in the browser.

const chatInput = document.querySelector("#chat-input");
const sendButton = document.querySelector("#send-btn");
const chatContainer = document.querySelector(".chat-container");
const themeButton = document.querySelector("#theme-btn");
const deleteButton = document.querySelector("#delete-btn");

let userText = null;
const API_KEY = "PASTE-YOUR-API-KEY-HERE"; // Paste your API key here

const loadDataFromLocalstorage = () => {
    // Load saved chats and theme from local storage and apply/add on the page
    const themeColor = localStorage.getItem("themeColor");

    document.body.classList.toggle("light-mode", themeColor === "light_mode");
    themeButton.innerText = document.body.classList.contains("light-mode") ? "dark_mode" : "light_mode";

    const defaultText = `<div class="default-text">
                            <h1>ChatGPT Clone</h1>
                            <p>Start a conversation and explore the power of AI.<br> Your chat history will be displayed here.</p>
                        </div>`

    chatContainer.innerHTML = localStorage.getItem("all-chats") || defaultText;
    chatContainer.scrollTo(0, chatContainer.scrollHeight); // Scroll to bottom of the chat container
}

const createChatElement = (content, className) => {
    // Create new div and apply chat, specified class and set html content of div
    const chatDiv = document.createElement("div");
    chatDiv.classList.add("chat", className);
    chatDiv.innerHTML = content;
    return chatDiv; // Return the created chat div
}

const getChatResponse = async (incomingChatDiv) => {
    const API_URL = "https://api.openai.com/v1/completions";
    const pElement = document.createElement("p");

    // Define the properties and data for the API request
    const requestOptions = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
            model: "text-davinci-003",
            prompt: userText,
            max_tokens: 2048,
            temperature: 0.2,
            n: 1,
            stop: null
        })
    }

    // Send POST request to API, get response and set the reponse as paragraph element text
    try {
        const response = await (await fetch(API_URL, requestOptions)).json();
        pElement.textContent = response.choices[0].text.trim();
    } catch (error) { // Add error class to the paragraph element and set error text
        pElement.classList.add("error");
        pElement.textContent = "Oops! Something went wrong while retrieving the response. Please try again.";
    }

    // Remove the typing animation, append the paragraph element and save the chats to local storage
    incomingChatDiv.querySelector(".typing-animation").remove();
    incomingChatDiv.querySelector(".chat-details").appendChild(pElement);
    localStorage.setItem("all-chats", chatContainer.innerHTML);
    chatContainer.scrollTo(0, chatContainer.scrollHeight);
}

const copyResponse = (copyBtn) => {
    // Copy the text content of the response to the clipboard
    const reponseTextElement = copyBtn.parentElement.querySelector("p");
    navigator.clipboard.writeText(reponseTextElement.textContent);
    copyBtn.textContent = "done";
    setTimeout(() => copyBtn.textContent = "content_copy", 1000);
}

const showTypingAnimation = () => {
    // Display the typing animation and call the getChatResponse function
    const html = `<div class="chat-content">
                    <div class="chat-details">
                        <img src="images/chatbot.jpg" alt="chatbot-img">
                        <div class="typing-animation">
                            <div class="typing-dot" style="--delay: 0.2s"></div>
                            <div class="typing-dot" style="--delay: 0.3s"></div>
                            <div class="typing-dot" style="--delay: 0.4s"></div>
                        </div>
                    </div>
                    <span onclick="copyResponse(this)" class="material-symbols-rounded">content_copy</span>
                </div>`;
    // Create an incoming chat div with typing animation and append it to chat container
    const incomingChatDiv = createChatElement(html, "incoming");
    chatContainer.appendChild(incomingChatDiv);
    chatContainer.scrollTo(0, chatContainer.scrollHeight);
    getChatResponse(incomingChatDiv);
}

const handleOutgoingChat = () => {
    userText = chatInput.value.trim(); // Get chatInput value and remove extra spaces
    if(!userText) return; // If chatInput is empty return from here

    // Clear the input field and reset its height
    chatInput.value = "";
    chatInput.style.height = `${initialInputHeight}px`;

    const html = `<div class="chat-content">
                    <div class="chat-details">
                        <img src="images/user.jpg" alt="user-img">
                        <p>${userText}</p>
                    </div>
                </div>`;

    // Create an outgoing chat div with user's message and append it to chat container
    const outgoingChatDiv = createChatElement(html, "outgoing");
    chatContainer.querySelector(".default-text")?.remove();
    chatContainer.appendChild(outgoingChatDiv);
    chatContainer.scrollTo(0, chatContainer.scrollHeight);
    setTimeout(showTypingAnimation, 500);
}

deleteButton.addEventListener("click", () => {
    // Remove the chats from local storage and call loadDataFromLocalstorage function
    if(confirm("Are you sure you want to delete all the chats?")) {
        localStorage.removeItem("all-chats");
        loadDataFromLocalstorage();
    }
});

themeButton.addEventListener("click", () => {
    // Toggle body's class for the theme mode and save the updated theme to the local storage 
    document.body.classList.toggle("light-mode");
    localStorage.setItem("themeColor", themeButton.innerText);
    themeButton.innerText = document.body.classList.contains("light-mode") ? "dark_mode" : "light_mode";
});

const initialInputHeight = chatInput.scrollHeight;

chatInput.addEventListener("input", () => {   
    // Adjust the height of the input field dynamically based on its content
    chatInput.style.height =  `${initialInputHeight}px`;
    chatInput.style.height = `${chatInput.scrollHeight}px`;
});

chatInput.addEventListener("keydown", (e) => {
    // If the Enter key is pressed without Shift and the window width is larger 
    // than 800 pixels, handle the outgoing chat
    if (e.key === "Enter" && !e.shiftKey && window.innerWidth > 800) {
        e.preventDefault();
        handleOutgoingChat();
    }
});

loadDataFromLocalstorage();
sendButton.addEventListener("click", handleOutgoingChat);

Remember, your ChatGPT is not yet ready to generate chats based on prompts. To make it functional, you need to pay attention to a crucial detail in the code. Take a closer look, and you’ll notice that you have to paste an “OpenAI API key” into the API_KEY variable.

To get your API key, visit the following URL: https://platform.openai.com/account/api-keys. Once there, log in to your account, and you will be able to generate a free API key. To understand other things in the code. I recommend watching the tutorial video, reading the code comments, and experimenting with the code.

” Remember that when you sign up for OpenAI, you’ll get a free $5 credit for your API usage. If your account is older than 3 months or the credit runs out, you’ll need a paid account or create a new one with a new number to keep using the API. Your API usage and expiration date can be found on the account’s usage page.”

Conclusion and Final Words

Congratulations! You have successfully created a ChatGPT clone project using HTML, CSS, and vanilla JavaScript and integrated it with the OpenAI API. Now, you can engage in meaningful conversations and showcase your talent to friends and beyond.

I encourage you to continue improving your skills by diving into other exciting real-world projects such as JavaScript API projects, JavaScript games, Form validations, Image sliders, and more.

If you encounter any difficulties while creating your own ChatGPT or your code is not working as expected, you can download the source code files for this ChatGPT clone project for free by clicking the Download button. You can also view a live demo of it by clicking the View Live button.

Remember that after downloading the file, you’ll have to paste an “OpenAI API key” into the API_KEY variable in the script.js file. To get your API key, visit the following URL: https://platform.openai.com/account/api-keys. Once there, log in to your account, and you will be able to generate a free API key.

]]>
https://www.codingnepalweb.com/create-chatgpt-clone-html-css-javascript/feed/ 0
Create Functional Image Gallery in HTML CSS & JavaScript https://www.codingnepalweb.com/functional-image-gallery-html-css-javascript/ https://www.codingnepalweb.com/functional-image-gallery-html-css-javascript/#comments Tue, 04 Apr 2023 17:42:09 +0000 https://www.codingnepalweb.com/?p=4077 Create Functional Image Gallery in HTML CSS & JavaScript

If you’re a web designer or developer, you must have searched for copyright-free images for your projects on various websites. Pexels is one of the most popular sites for such images. But as a web developer, have you ever wanted to create a functional image gallery similar to Pexels?

In this blog post, I’ll show the steps for creating a fully-functional image gallery using HTML, CSS, and JavaScript. Not only will you learn the basics of DOM manipulation, event handling, and CSS styling, but you’ll also gain valuable experience working with APIs.

With this Pexels clone coding project, you can effortlessly search, view, and download any image you desire, all within seconds. The images are displayed in a stylish masonry layout which looks great on any device, from desktops to mobile phones.

If you’re excited to see a live demo of this image gallery, click here to check it out. For a full video tutorial on creating a functional image gallery using HTML, CSS, and JavaScript, you can watch the given YouTube video.

Video Tutorial of Functional Image Gallery in JavaScript

If you prefer visual learning, then the above video tutorial is a great resource for you. I highly recommend watching it because I go through each line of code in detail and provide comments to help you understand what’s happening at each step.

But if you prefer reading blog posts or want a quick summary of the steps involved in creating an image gallery, you can continue reading this post. By the end of this post, you will have a clear understanding of how to create your very own Pexels clone image gallery with HTML, CSS, and JavaScript.

Steps For Creating Image Gallery in JavaScript

To create a functional image gallery using HTML, CSS, and vanilla JavaScript, follow the given steps line by line:

  1. Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a script.js file. The file name must be script and its extension .js
  5. Download the images folder from Google Drive and put this folder inside the project folder. This static image is only used as a search section background.

To start, add the following HTML codes to your index.html file to create a basic layout for an image gallery. Note that the “ul” container is currently empty, but it will be filled with “li” elements (representing image cards) later using JavaScript code.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Image Gallery with JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css">
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="lightbox">
      <div class="wrapper">
        <header>
          <div class="photographer">
            <i class="uil uil-camera"></i>
            <span></span>
          </div>
          <div class="buttons">
            <i class="uil uil-import"></i>
            <i class="close-icon uil uil-times"></i>
          </div>
        </header>
        <div class="preview-img">
          <div class="img"><img src="" alt="preview-img"></div>
        </div>
      </div>
    </div>
    <section class="search">
      <img src="./images/search-img.jpg" alt="search-img">
      <div class="content">
        <h1>Image Gallery with JavaScript</h1>
        <p>Search and download any images within a second</p>
        <div class="search-box">
          <i class="uil uil-search"></i>
          <input type="text" placeholder="Search images">
        </div>
      </div>
    </section>
    <section class="gallery">
      <ul class="images"></ul>
      <button class="load-more">Load More</button>
    </section>

  </body>
</html>

Next, add the following CSS codes to your style.css file to give a basic look and feel to the image gallery. If you wish, you can customize it to your liking by changing the color, font, size, and other CSS properties in the file.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
.search {
  height: 40vh;
  display: flex;
  position: relative;
  align-items: center;
  justify-content: center;
}
.search::before, .search img, .lightbox {
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  position: absolute;
}
.search::before {
  content: "";
  z-index: 1;
  background: rgba(0,0,0,0.25);
}
.search img {
  object-fit: cover;
}
.search .content {
  z-index: 2;
  color: #fff;
  padding: 0 13px;
  text-align: center;
  position: relative;
}
.search h1 {
  font-size: 2.65rem;
  font-weight: 600;
}
.search p {
  margin-top: 8px;
  font-size: 1.5rem;
}
.search .search-box {
  height: 55px;
  margin: 45px 0;
  position: relative;
}
.search-box i {
  position: absolute;
  left: 20px;
  top: 50%;
  cursor: default;
  color: #8D8D8D;
  font-size: 1.4rem;
  transform: translateY(-50%);
}
.search-box input {
  width: 100%;
  height: 100%;
  outline: none;
  border: none;
  font-size: 1.1rem;
  padding-left: 55px;
  background: #fff;
  border-radius: 5px;
}
.search-box input::placeholder {
  color: #929292;
}
.search-box input:focus::placeholder {
  color: #bfbfbf;
}
.gallery {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.gallery .images {
  gap: 15px;
  max-width: 95%;
  margin-top: 40px;
  columns: 5 340px;
  list-style: none;
}
.gallery .images .card {
  display: flex;
  cursor: pointer;
  overflow: hidden;
  position: relative;
  margin-bottom: 14px;
  border-radius: 4px;
}
.gallery .images img {
  width: 100%;
  z-index: 2;
  position: relative;
}
.images .details {
  position: absolute;
  z-index: 4;
  width: 100%;
  bottom: -100px;
  display: flex;
  align-items: center;
  padding: 15px 20px;
  justify-content: space-between;
  transition: bottom 0.1s ease;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
}
.images li:hover .details {
  bottom: 0;
}
.photographer {
  color: #fff;
  display: flex;
  align-items: center;
}
.photographer i {
  font-size: 1.4rem;
  margin-right: 10px;
}
.photographer span {
  font-size: 1.05rem;
}
button, i {
  outline: none;
  border: none;
  cursor: pointer;
  border-radius: 5px;
  transition: 0.2s ease;
}
.details button {
  background: #fff;
  font-size: 1.1rem;
  padding: 3px 8px;
}
.details .download-btn:hover {
  background: #f2f2f2;
}
.gallery .load-more {
  color: #fff;
  background: #8A6CFF;
  margin: 50px 0;
  font-size: 1.2rem;
  padding: 12px 27px;
}
.gallery .load-more.disabled {
  opacity: 0.6;
  pointer-events: none;
}
.gallery .load-more:hover {
  background: #704dff;
}

.lightbox {
  z-index: 5;
  position: fixed;
  visibility: hidden;
  background: rgba(0,0,0,0.65);
}
.lightbox.show {
  visibility: visible;
}
.lightbox .wrapper {
  position: fixed;
  left: 50%;
  top: 50%;
  width: 100%;
  padding: 20px;
  max-width: 850px;
  background: #fff;
  border-radius: 6px;
  opacity: 0;
  pointer-events: none;
  transform: translate(-50%, -50%) scale(0.9);
  transition: transform 0.1s ease;
}
.lightbox.show .wrapper {
  opacity: 1;
  pointer-events: auto;
  transform: translate(-50%, -50%) scale(1);
}
.wrapper header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
header .photographer {
  color: #333;
}
header .photographer i {
  font-size: 1.7rem;
  cursor: auto;
}
header .photographer span {
  font-size: 1.2rem;
}
header .buttons i {
  height: 40px;
  width: 40px;
  display: inline-block;
  color: #fff;
  font-size: 1.2rem;
  line-height: 40px;
  text-align: center;
  background: #8A6CFF;
  border-radius: 4px;
  transition: 0.2s ease;
}
header .buttons i:first-child:hover {
  background: #704dff;
}
header .buttons i:last-child {
  margin-left: 10px;
  font-size: 1.25rem;
  background: #6C757D;
}
header .buttons i:last-child:hover {
  background: #5f666d;
}
.wrapper .preview-img {
  display: flex;
  justify-content: center;
  margin-top: 25px;
}
.preview-img .img {
  max-height: 65vh;
}
.preview-img img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

@media screen and (max-width: 688px) {
  .lightbox .wrapper {
    padding: 12px;
    max-width: calc(100% - 26px);
  }
  .wrapper .preview-img {
    margin-top: 15px;
  }
  header .buttons i:last-child {
    margin-left: 7px;
  }
  header .photographer span, .search p {
    font-size: 1.1rem;
  }
  .search h1 {
    font-size: 1.8rem;
  }
  .search .search-box {
    height: 50px;
    margin: 30px 0;
  }
  .gallery .images {
    max-width: 100%;
    padding: 0 13px;
    margin-top: 20px;
  }
  .images .details {
    bottom: 0px;
  }
  .gallery .load-more {
    padding: 10px 25px;
    font-size: 1.05rem;
  }
}

Finally, add the following JavaScript code to your script.js file to add functionality for searching, viewing, and downloading images from this gallery. This code will handle user actions and communicate with the Pexels API to retrieve and display images in the gallery.

const imageWrapper = document.querySelector(".images");
const searchInput = document.querySelector(".search input");
const loadMoreBtn = document.querySelector(".gallery .load-more");
const lightbox = document.querySelector(".lightbox");
const downloadImgBtn = lightbox.querySelector(".uil-import");
const closeImgBtn = lightbox.querySelector(".close-icon");

// API key, paginations, searchTerm variables
const apiKey = "PASTE-YOUR-API-KEY";
const perPage = 15;
let currentPage = 1;
let searchTerm = null;

const downloadImg = (imgUrl) => {
    // Converting received img to blob, creating its download link, & downloading it
    fetch(imgUrl).then(res => res.blob()).then(blob => {
        const a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = new Date().getTime();
        a.click();
    }).catch(() => alert("Failed to download image!"));
}

const showLightbox = (name, img) => {
    // Showing lightbox and setting img source, name and button attribute
    lightbox.querySelector("img").src = img;
    lightbox.querySelector("span").innerText = name;
    downloadImgBtn.setAttribute("data-img", img);
    lightbox.classList.add("show");
    document.body.style.overflow = "hidden";
}

const hideLightbox = () => {
    // Hiding lightbox on close icon click
    lightbox.classList.remove("show");
    document.body.style.overflow = "auto";
}

const generateHTML = (images) => {
    // Making li of all fetched images and adding them to the existing image wrapper
    imageWrapper.innerHTML += images.map(img =>
        `<li class="card">
            <img onclick="showLightbox('${img.photographer}', '${img.src.large2x}')" src="${img.src.large2x}" alt="img">
            <div class="details">
                <div class="photographer">
                    <i class="uil uil-camera"></i>
                    <span>${img.photographer}</span>
                </div>
                <button onclick="downloadImg('${img.src.large2x}');">
                    <i class="uil uil-import"></i>
                </button>
            </div>
        </li>`
    ).join("");
}

const getImages = (apiURL) => {
    // Fetching images by API call with authorization header
    searchInput.blur();
    loadMoreBtn.innerText = "Loading...";
    loadMoreBtn.classList.add("disabled");
    fetch(apiURL, {
        headers: { Authorization: apiKey }
    }).then(res => res.json()).then(data => {
        generateHTML(data.photos);
        loadMoreBtn.innerText = "Load More";
        loadMoreBtn.classList.remove("disabled");
    }).catch(() => alert("Failed to load images!"));
}

const loadMoreImages = () => {
    currentPage++; // Increment currentPage by 1
    // If searchTerm has some value then call API with search term else call default API
    let apiUrl = `https://api.pexels.com/v1/curated?page=${currentPage}&per_page=${perPage}`;
    apiUrl = searchTerm ? `https://api.pexels.com/v1/search?query=${searchTerm}&page=${currentPage}&per_page=${perPage}` : apiUrl;
    getImages(apiUrl);
}

const loadSearchImages = (e) => {
    // If the search input is empty, set the search term to null and return from here
    if (e.target.value === "") return searchTerm = null;
    // If pressed key is Enter, update the current page, search term & call the getImages
    if (e.key === "Enter") {
        currentPage = 1;
        searchTerm = e.target.value;
        imageWrapper.innerHTML = "";
        getImages(`https://api.pexels.com/v1/search?query=${searchTerm}&page=1&per_page=${perPage}`);
    }
}

getImages(`https://api.pexels.com/v1/curated?page=${currentPage}&per_page=${perPage}`);
loadMoreBtn.addEventListener("click", loadMoreImages);
searchInput.addEventListener("keyup", loadSearchImages);
closeImgBtn.addEventListener("click", hideLightbox);
downloadImgBtn.addEventListener("click", (e) => downloadImg(e.target.dataset.img));

In the code, you will notice a variable called apiKey. You need to get your own Pexels API key and insert it into this variable. You can get a free API key by visiting the official Pexels API documentation. Additionally, you will find a variable named perPage, which has a default value of 15. This means that every time the API is called, 15 new images will be fetched.

Conclusion and Final Words

Creating a functional image gallery using HTML, CSS, and JavaScript is an excellent project for beginners to learn about web development concepts such as DOM manipulation, event handling, CSS styling, and API usage in real-world projects.

With the knowledge and skills you’ve gained from this project, now it’s up to you to experiment with the code and take this image gallery to the next level. For more API-related coding projects, check out the blog on Top JavaScript APIs Projects for Beginners.

If you encounter any problems or your code is not working as expected, you can download the source code files for this image gallery for free. Click on the download button to get the zip file containing the project folder with source code files. Remember to paste your API key into the code.

 

]]>
https://www.codingnepalweb.com/functional-image-gallery-html-css-javascript/feed/ 1
How to Check Internet Connection in HTML CSS & JavaScript https://www.codingnepalweb.com/check-internet-connection-html-javascript/ https://www.codingnepalweb.com/check-internet-connection-html-javascript/#comments Fri, 13 Jan 2023 16:42:42 +0000 https://www.codingnepalweb.com/?p=3900 How to Check Internet Connection in HTML CSS & JavaScript

In today’s world, the internet is essential for many websites and applications to function properly. To provide a seamless experience for users, it’s important to check the internet connection and take the necessary actions.

In this blog post, we’ll show you how to check internet connection and display relevant notifications using HTML, CSS, and JavaScript. Whether you’re new to web development or an experienced developer, you’re sure to learn something new about detecting network status with plain JavaScript.

In this project, when the user’s device goes offline, there will be a displayed offline notification with a 10-second timer to reconnect. There will also be a “Reconnect Now” button that allows users to try reconnecting to the internet immediately. Once the user’s device is back online, the notification will change to “Restored Connection.”

Video Tutorial of Check Network Status in JavaScript

If you’re excited to see this project in action, you can click here to view a live demo of it. Additionally, if you prefer visual learning, you can watch a given YouTube video that shows how to check an internet connection using HTML, CSS, and JavaScript. Alternatively, you can continue reading this post for a written guide on the same topic.

Steps to Check Internet Connection in JavaScript

We’ll check the Internet connection and display the relevant notification using HTML, CSS, and JavaScript in 3 simple steps.

1. Setting up the project

In the initial step, we will create a new directory for our project. You can name it whatever you want, and inside this directory, create three files: index.html, style.css, and script.js. These files will contain the necessary HTML, CSS, and JavaScript code for checking the internet connection status.

2. Creating the notification

In the second step, we will create the layout and style the notification using HTML and CSS. Then, we will use JavaScript to check the device’s internet connection status.

In your index.html file, add the following HTML code to create the basic structure of the notification: The title, description, and icon name for this notification will be inserted by the JavaScript code.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Check Internet Connection | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Font Awesome CDN link for icons -->
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v3.0.6/css/line.css">
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="notification">
      <div class="content">
        <div class="wifi-icon"><i class=""></i></div>
        <div class="details">
          <h2 class="title"></h2>
          <p class="desc"></p>
          <button class="reconnect-btn">Reconnect Now</button>
        </div>
      </div>
    </div>

  </body>
</html>

In your style.css file, add the following CSS code to style the notification: If you want, you can change the font, size, color, and background of the notification by slightly modifying this code.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background: #E3F2FD;
}
.popup {
  position: absolute;
  left: 50%;
  top: -25%;
  visibility: hidden;
  width: 490px;
  border-radius: 5px;
  padding: 13px 17px 20px;
  background: #fff;
  display: flex;
  border-top: 3px solid #EA4D67;
  transform: translateX(-50%);
  box-shadow: 0 10px 25px rgba(52,87,220,0.1);
  transition: all 0.25s ease;
}
.popup.show {
  top: 0;
  visibility: visible;
}
.popup.online {
  border-color: #2ECC71;
}
.popup .icon i {
  width: 40px;
  height: 40px;
  display: flex;
  color: #fff;
  margin-right: 15px;
  font-size: 1.2rem;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #EA4D67;
}
.popup.online .icon i {
  background: #2ECC71;
}
.popup .title {
  font-size: 1.2rem;
}
.popup .desc {
  color: #474747;
  margin: 3px 0 10px;
  font-size: 1.04rem;
}
.popup .reconnect {
  border: none;
  outline: none;
  color: #fff;
  cursor: pointer;
  font-weight: 500;
  font-size: 0.95rem;
  padding: 8px 13px;
  border-radius: 4px;
  background: #5372F0;
}
.popup.online .reconnect {
  background: #bfbfbf;
  pointer-events: none;
}

@media screen and (max-width: 550px) {
  .popup {
    width: 100%;
    padding: 10px 15px 17px;
  }
}

Keep in mind that the notification won’t show on the page because we’ve added some styles to hide it, which will be controlled by JavaScript.

3. Checking the internet connection

In the final step, we will add the functionality to check the internet connection and display the relevant notification accordingly. To do this, add the following JavaScript code to your script.js file:

const popup = document.querySelector(".popup"),
wifiIcon = document.querySelector(".icon i"),
popupTitle = document.querySelector(".popup .title"),
popupDesc = document.querySelector(".desc"),
reconnectBtn = document.querySelector(".reconnect");

let isOnline = true, intervalId, timer = 10;

const checkConnection = async () => {
    try {
        // Try to fetch random data from the API. If the status code is between 
        // 200 and 300, the network connection is considered online 
        const response = await fetch("https://jsonplaceholder.typicode.com/posts");
        isOnline = response.status >= 200 && response.status < 300;
    } catch (error) {
        isOnline = false; // If there is an error, the connection is considered offline
    }
    timer = 10;
    clearInterval(intervalId);
    handlePopup(isOnline);
}

const handlePopup = (status) => {
    if(status) { // If the status is true (online), update icon, title, and description accordingly
        wifiIcon.className = "uil uil-wifi";
        popupTitle.innerText = "Restored Connection";
        popupDesc.innerHTML = "Your device is now successfully connected to the internet.";
        popup.classList.add("online");
        return setTimeout(() => popup.classList.remove("show"), 2000);
    }
    // If the status is false (offline), update the icon, title, and description accordingly
    wifiIcon.className = "uil uil-wifi-slash";
    popupTitle.innerText = "Lost Connection";
    popupDesc.innerHTML = "Your network is unavailable. We will attempt to reconnect you in <b>10</b> seconds.";
    popup.className = "popup show";

    intervalId = setInterval(() => { // Set an interval to decrease the timer by 1 every second
        timer--;
        if(timer === 0) checkConnection(); // If the timer reaches 0, check the connection again
        popup.querySelector(".desc b").innerText = timer;
    }, 1000);
}

// Only if isOnline is true, check the connection status every 3 seconds
setInterval(() => isOnline && checkConnection(), 3000);
reconnectBtn.addEventListener("click", checkConnection);

In the code, you can see that to check if the device has an internet connection or not, we send requests for data to an API every 3 seconds and check if they are successful. If the requests fail, it indicates that the device is offline, and we will display the notification with a 10-second timer to wait before rechecking the connection.

If you want to understand the specific functionality of a certain script code, you can read the comments on each line to gain more insight.

Conclusion and Final Words

By following the steps in this blog post, you’ve learned how to use HTML, CSS, and JavaScript to check the internet connection and display appropriate notifications to the user. However, keep in mind that there are alternative methods to check an internet connection, such as the JavaScript navigator.onLine method.

But the navigator.onLine method is not always reliable, as it only checks if a device has a connection to a network, not if the network can actually access the internet. So, a better approach would be to send a request for data to an API that you already know about.

If you encounter any problems or your code is not working as expected, you can download the source code files of this Internet checker project by clicking on the given download button. It’s free, and a zip file will be downloaded that contains the project folder with source code files.

 

]]>
https://www.codingnepalweb.com/check-internet-connection-html-javascript/feed/ 3
QR Code Scanner or Reader in HTML CSS & JavaScript https://www.codingnepalweb.com/qr-code-reader-html-javascript/ https://www.codingnepalweb.com/qr-code-reader-html-javascript/#comments Wed, 11 May 2022 08:27:05 +0000 https://www.codingnepalweb.com/?p=2424 QR Code Scanner or Reader in HTML CSS & JavaScript

Hey friends, today in this blog, you’ll learn how to create a QR Code Scanner or Reader in HTML CSS & JavaScript. If you’re looking for QR Code Generator App in JavaScript, here is a YouTube video or blog. Now, I’m going to create a QR Code Reader in JavaScript.

As you may know, a QR code scanner is a scanning device that is able to read QR codes. Most the phone has a built-in QR code scanner app.

In this blog, I’m not going to create a QR code scanner by the camera instead of this, in my QR code reader app, users can upload any QR code image and decode or extract the content from it, as you’ve seen in the image preview.

If you want to see a demo or full video tutorial of this QR code scanner or reader in JavaScript, you can watch the given YouTube video.

Video Tutorial of QR Code Reader in JavaScript

 
In the above video, you’ve seen the demo of the QR code reader and how I created it using HTML CSS & JavaScript. As seen in the video, I’ve used the QR server API to read QR codes of user-uploaded images.

Using fetch API of JavaScript, I sent the user’s uploaded QR code to the API, and API processed the code and responded back to the data. If you’re already familiar with the fetch method, you can easily understand the logic and codes of this QR code reader.

But, if you’re unfamiliar with this, I want you to learn the fetch method or watch the above YouTube video multiple times to understand it. In the video, I’ve explained these things.

If you like this QR code scanner or reader and want to get source codes, you can easily copy or download them from the bottom of this page. I recommend you to download the files instead of copy.

You might like this:

QR Code Reader in JavaScript [Source Codes]

To create a QR Code Scanner or Reader in JavaScript. First, you need to create three Files: HTML, CSS & JavaScript File. After creating these files just paste the given codes into your file. You can also download the source code files of this QR Code Reader App from the below download button.

First, create an HTML file with the name index.html and paste the given codes into your HTML file. Remember, you’ve to create a file with .html extension.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">  
    <title>QR Code Scanner or Reader | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Font Awesome CDN Link for Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
  </head>
  <body>
    <div class="wrapper">
      <form action="#">
        <input type="file" hidden>
        <img src="#" alt="qr-code">
        <div class="content">
          <i class="fas fa-cloud-upload"></i>
          <p>Upload QR Code to Read</p>
        </div>
      </form>
      <div class="details">
        <textarea spellcheck="false" disabled></textarea>
        <div class="buttons">
          <button class="close">Close</button>
          <button class="copy">Copy Text</button>
        </div>
      </div>
    </div>

    <script src="script.js"></script>
  </body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

/* Import Google Font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 0 10px;
  background: #E3F2FD;
}
.wrapper{
  height: 270px;
  width: 420px;
  border-radius: 7px;
  background: #0B85FF;
  padding: 30px 30px 35px;
  transition: height 0.2s ease;
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}
.wrapper.active{
  height: 525px;
}
.wrapper form{
  height: 210px;
  display: flex;
  cursor: pointer;
  user-select: none;
  text-align: center;
  border-radius: 7px;
  background: #fff;
  align-items: center;
  justify-content: center;
  transition: height 0.2s ease;
}
.wrapper.active form{
  height: 225px;
  pointer-events: none;
}
form img{
  display: none;
  max-width: 148px;
}
.wrapper.active form img{
  display: block;
}
.wrapper.active form .content{
  display: none;
}
form .content i{
  color: #0B85FF;
  font-size: 55px;
}
form .content p{
  color: #0B85FF;
  margin-top: 15px;
  font-size: 16px;
}
.wrapper .details{
  opacity: 0;
  margin-top: 25px;
  pointer-events: none;
}
.wrapper.active .details{
  opacity: 1;
  pointer-events: auto;
  transition: opacity 0.5s 0.05s ease;
}
.details textarea{
  width: 100%;
  height: 128px;
  outline: none;
  resize: none;
  color: #fff;
  font-size: 18px;
  background: none;
  border-radius: 5px;
  padding: 10px 15px;
  border: 1px solid #fff;
}
textarea::-webkit-scrollbar{
  width: 0px;
}
textarea:hover::-webkit-scrollbar{
  width: 5px;
}
textarea:hover::-webkit-scrollbar-track{
  background: none;
}
textarea:hover::-webkit-scrollbar-thumb{
  background: #fff;
  border-radius: 8px;
}
.details .buttons{
  display: flex;
  margin-top: 20px;
  align-items: center;
  justify-content: space-between;
}
.buttons button{
  height: 55px;
  outline: none;
  border: none;
  font-weight: 500;
  font-size: 16px;
  cursor: pointer;
  color: #0B85FF;
  border-radius: 5px;
  background: #fff;
  transition: transform 0.3s ease;
  width: calc(100% / 2 - 10px);
}
.buttons button:active{
  transform: scale(0.95);
}

@media (max-width: 450px) {
  .wrapper{
    padding: 25px;
    height: 260px;
  }
  .wrapper.active{
    height: 520px;
  }
}

Last, create a JavaScript file with the name script.js and paste the given codes in your JavaScript file. Remember, you’ve to create a file with .js extension.

const wrapper = document.querySelector(".wrapper"),
form = document.querySelector("form"),
fileInp = form.querySelector("input"),
infoText = form.querySelector("p"),
closeBtn = document.querySelector(".close"),
copyBtn = document.querySelector(".copy");

function fetchRequest(file, formData) {
    infoText.innerText = "Scanning QR Code...";
    fetch("http://api.qrserver.com/v1/read-qr-code/", {
        method: 'POST', body: formData
    }).then(res => res.json()).then(result => {
        result = result[0].symbol[0].data;
        infoText.innerText = result ? "Upload QR Code to Scan" : "Couldn't scan QR Code";
        if(!result) return;
        document.querySelector("textarea").innerText = result;
        form.querySelector("img").src = URL.createObjectURL(file);
        wrapper.classList.add("active");
    }).catch(() => {
        infoText.innerText = "Couldn't scan QR Code";
    });
}

fileInp.addEventListener("change", async e => {
    let file = e.target.files[0];
    if(!file) return;
    let formData = new FormData();
    formData.append('file', file);
    fetchRequest(file, formData);
});

copyBtn.addEventListener("click", () => {
    let text = document.querySelector("textarea").textContent;
    navigator.clipboard.writeText(text);
});

form.addEventListener("click", () => fileInp.click());
closeBtn.addEventListener("click", () => wrapper.classList.remove("active"));

That’s all, now you’ve successfully created a QR Code Scanner or Reader in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

 

]]>
https://www.codingnepalweb.com/qr-code-reader-html-javascript/feed/ 1
Build A Language Translator App in HTML CSS & JavaScript https://www.codingnepalweb.com/language-translator-app-html-css-javascript/ https://www.codingnepalweb.com/language-translator-app-html-css-javascript/#comments Sun, 24 Apr 2022 13:37:35 +0000 https://www.codingnepalweb.com/?p=2414 Build A Language Translator App in HTML CSS & JavaScript

Hey friends, today in this blog, you’ll learn how to Build A Language Translator App in HTML CSS & JavaScript. In the earlier blog, I shared how to Convert a Text To Speech in JavaScript, and now it’s time to create a Language Translator.

Language translator is a program that is used to translate text into multiple languages like Nepali, Hindi, Spanish, etc. In my language translator app, users can easily translate text into different languages, copy translated text, and convert text to speech. It is similar to Google Translate.

If you want to see a demo or full video tutorial of this language translator app, you can watch a given video or click here to see a live demo of this translator app.

Video Tutorial of Language Translator App in JavaScript

 

I hope you have seen a demo or video tutorial of this language translator app and know how I created it using HTML CSS & JavaScript. As you’ve seen, I used a free API to convert user-entered text into different languages.

This API is used only to convert text into other languages. Other things such as copying translated text and converting text to speech are done with JavaScript.

If you’re too beginner and don’t know about JavaScript array, fetch, and speech synthesis API, then the codes of this language translator might be hard to understand for you. So, before building this project, I suggest you learn these things or watch the above video 2 to 3 times to understand it because, in the video, I’ve explained these things in written comments.

If you liked this language translator app and want to get source code files, you can easily download them from the bottom of this page.

You might like this:

Language Translator App in JavaScript [Source Codes]

To build this Language Translator App in JavaScript. First, you need to create four Files: HTML, CSS & JavaScript Files. After creating these files just paste the given codes into your file. You can also download the source code files of this translator app from the below download button and I also recommend you to download the source codes files.

First, create an HTML file with the name index.html and paste the given codes into your HTML file. Remember, you’ve to create a file with .html extension.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">  
    <title>Language Translator | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Font Awesome CDN Link for Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
  </head>
  <body>
    <div class="container">
      <div class="wrapper">
        <div class="text-input">
          <textarea spellcheck="false" class="from-text" placeholder="Enter text"></textarea>
          <textarea spellcheck="false" readonly disabled class="to-text" placeholder="Translation"></textarea>
        </div>
        <ul class="controls">
          <li class="row from">
            <div class="icons">
              <i id="from" class="fas fa-volume-up"></i>
              <i id="from" class="fas fa-copy"></i>
            </div>
            <select></select>
          </li>
          <li class="exchange"><i class="fas fa-exchange-alt"></i></li>
          <li class="row to">
            <select></select>
            <div class="icons">
              <i id="to" class="fas fa-volume-up"></i>
              <i id="to" class="fas fa-copy"></i>
            </div>
          </li>
        </ul>
      </div>
      <button>Translate Text</button>
    </div>

    <script src="js/countries.js"></script>
    <script src="js/script.js"></script>

  </body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

/* Import Google Font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10px;
  min-height: 100vh;
  background: #5372F0;
}
.container{
  max-width: 690px;
  width: 100%;
  padding: 30px;
  background: #fff;
  border-radius: 7px;
  box-shadow: 0 10px 20px rgba(0,0,0,0.01);
}
.wrapper{
  border-radius: 5px;
  border: 1px solid #ccc;
}
.wrapper .text-input{
  display: flex;
  border-bottom: 1px solid #ccc;
}
.text-input .to-text{
  border-radius: 0px;
  border-left: 1px solid #ccc;
}
.text-input textarea{
  height: 250px;
  width: 100%;
  border: none;
  outline: none;
  resize: none;
  background: none;
  font-size: 18px;
  padding: 10px 15px;
  border-radius: 5px;
}
.text-input textarea::placeholder{
  color: #b7b6b6;
}
.controls, li, .icons, .icons i{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.controls{
  list-style: none;
  padding: 12px 15px;
}
.controls .row .icons{
  width: 38%;
}
.controls .row .icons i{
  width: 50px;
  color: #adadad;
  font-size: 14px;
  cursor: pointer;
  transition: transform 0.2s ease;
  justify-content: center;
}
.controls .row.from .icons{
  padding-right: 15px;
  border-right: 1px solid #ccc;
}
.controls .row.to .icons{
  padding-left: 15px;
  border-left: 1px solid #ccc;
}
.controls .row select{
  color: #333;
  border: none;
  outline: none;
  font-size: 18px;
  background: none;
  padding-left: 5px;
}
.text-input textarea::-webkit-scrollbar{
  width: 4px;
}
.controls .row select::-webkit-scrollbar{
  width: 8px;
}
.text-input textarea::-webkit-scrollbar-track,
.controls .row select::-webkit-scrollbar-track{
  background: #fff;
}
.text-input textarea::-webkit-scrollbar-thumb{
  background: #ddd;
  border-radius: 8px;
}
.controls .row select::-webkit-scrollbar-thumb{
  background: #999;
  border-radius: 8px;
  border-right: 2px solid #ffffff;
}
.controls .exchange{
  color: #adadad;
  cursor: pointer;
  font-size: 16px;
  transition: transform 0.2s ease;
}
.controls i:active{
  transform: scale(0.9);
}
.container button{
  width: 100%;
  padding: 14px;
  outline: none;
  border: none;
  color: #fff;
  cursor: pointer;
  margin-top: 20px;
  font-size: 17px;
  border-radius: 5px;
  background: #5372F0;
}

@media (max-width: 660px){
  .container{
    padding: 20px;
  }
  .wrapper .text-input{
    flex-direction: column;
  }
  .text-input .to-text{
    border-left: 0px;
    border-top: 1px solid #ccc;
  }
  .text-input textarea{
    height: 200px;
  }
  .controls .row .icons{
    display: none;
  }
  .container button{
    padding: 13px;
    font-size: 16px;
  }
  .controls .row select{
    font-size: 16px;
  }
  .controls .exchange{
    font-size: 14px;
  }
}

Third, create a JavaScript file with the name of countries.js and paste the given codes in your JavaScript file. Remember, you’ve to create a file with .js extension. In this file, we’re storing supported countries as an object.

const countries = {
    "am-ET": "Amharic",
    "ar-SA": "Arabic",
    "be-BY": "Bielarus",
    "bem-ZM": "Bemba",
    "bi-VU": "Bislama",
    "bjs-BB": "Bajan",
    "bn-IN": "Bengali",
    "bo-CN": "Tibetan",
    "br-FR": "Breton",
    "bs-BA": "Bosnian",
    "ca-ES": "Catalan",
    "cop-EG": "Coptic",
    "cs-CZ": "Czech",
    "cy-GB": "Welsh",
    "da-DK": "Danish",
    "dz-BT": "Dzongkha",
    "de-DE": "German",
    "dv-MV": "Maldivian",
    "el-GR": "Greek",
    "en-GB": "English",
    "es-ES": "Spanish",
    "et-EE": "Estonian",
    "eu-ES": "Basque",
    "fa-IR": "Persian",
    "fi-FI": "Finnish",
    "fn-FNG": "Fanagalo",
    "fo-FO": "Faroese",
    "fr-FR": "French",
    "gl-ES": "Galician",
    "gu-IN": "Gujarati",
    "ha-NE": "Hausa",
    "he-IL": "Hebrew",
    "hi-IN": "Hindi",
    "hr-HR": "Croatian",
    "hu-HU": "Hungarian",
    "id-ID": "Indonesian",
    "is-IS": "Icelandic",
    "it-IT": "Italian",
    "ja-JP": "Japanese",
    "kk-KZ": "Kazakh",
    "km-KM": "Khmer",
    "kn-IN": "Kannada",
    "ko-KR": "Korean",
    "ku-TR": "Kurdish",
    "ky-KG": "Kyrgyz",
    "la-VA": "Latin",
    "lo-LA": "Lao",
    "lv-LV": "Latvian",
    "men-SL": "Mende",
    "mg-MG": "Malagasy",
    "mi-NZ": "Maori",
    "ms-MY": "Malay",
    "mt-MT": "Maltese",
    "my-MM": "Burmese",
    "ne-NP": "Nepali",
    "niu-NU": "Niuean",
    "nl-NL": "Dutch",
    "no-NO": "Norwegian",
    "ny-MW": "Nyanja",
    "ur-PK": "Pakistani",
    "pau-PW": "Palauan",
    "pa-IN": "Panjabi",
    "ps-PK": "Pashto",
    "pis-SB": "Pijin",
    "pl-PL": "Polish",
    "pt-PT": "Portuguese",
    "rn-BI": "Kirundi",
    "ro-RO": "Romanian",
    "ru-RU": "Russian",
    "sg-CF": "Sango",
    "si-LK": "Sinhala",
    "sk-SK": "Slovak",
    "sm-WS": "Samoan",
    "sn-ZW": "Shona",
    "so-SO": "Somali",
    "sq-AL": "Albanian",
    "sr-RS": "Serbian",
    "sv-SE": "Swedish",
    "sw-SZ": "Swahili",
    "ta-LK": "Tamil",
    "te-IN": "Telugu",
    "tet-TL": "Tetum",
    "tg-TJ": "Tajik",
    "th-TH": "Thai",
    "ti-TI": "Tigrinya",
    "tk-TM": "Turkmen",
    "tl-PH": "Tagalog",
    "tn-BW": "Tswana",
    "to-TO": "Tongan",
    "tr-TR": "Turkish",
    "uk-UA": "Ukrainian",
    "uz-UZ": "Uzbek",
    "vi-VN": "Vietnamese",
    "wo-SN": "Wolof",
    "xh-ZA": "Xhosa",
    "yi-YD": "Yiddish",
    "zu-ZA": "Zulu"
}

Last, create a JavaScript file with the name of script.js and paste the given codes in your JavaScript file. Remember, you’ve to create a file with .js extension.

const fromText = document.querySelector(".from-text"),
toText = document.querySelector(".to-text"),
exchageIcon = document.querySelector(".exchange"),
selectTag = document.querySelectorAll("select"),
icons = document.querySelectorAll(".row i");
translateBtn = document.querySelector("button"),

selectTag.forEach((tag, id) => {
    for (let country_code in countries) {
        let selected = id == 0 ? country_code == "en-GB" ? "selected" : "" : country_code == "hi-IN" ? "selected" : "";
        let option = `<option ${selected} value="${country_code}">${countries[country_code]}</option>`;
        tag.insertAdjacentHTML("beforeend", option);
    }
});

exchageIcon.addEventListener("click", () => {
    let tempText = fromText.value,
    tempLang = selectTag[0].value;
    fromText.value = toText.value;
    toText.value = tempText;
    selectTag[0].value = selectTag[1].value;
    selectTag[1].value = tempLang;
});

fromText.addEventListener("keyup", () => {
    if(!fromText.value) {
        toText.value = "";
    }
});

translateBtn.addEventListener("click", () => {
    let text = fromText.value.trim(),
    translateFrom = selectTag[0].value,
    translateTo = selectTag[1].value;
    if(!text) return;
    toText.setAttribute("placeholder", "Translating...");
    let apiUrl = `https://api.mymemory.translated.net/get?q=${text}&langpair=${translateFrom}|${translateTo}`;
    fetch(apiUrl).then(res => res.json()).then(data => {
        toText.value = data.responseData.translatedText;
        data.matches.forEach(data => {
            if(data.id === 0) {
                toText.value = data.translation;
            }
        });
        toText.setAttribute("placeholder", "Translation");
    });
});

icons.forEach(icon => {
    icon.addEventListener("click", ({target}) => {
        if(!fromText.value || !toText.value) return;
        if(target.classList.contains("fa-copy")) {
            if(target.id == "from") {
                navigator.clipboard.writeText(fromText.value);
            } else {
                navigator.clipboard.writeText(toText.value);
            }
        } else {
            let utterance;
            if(target.id == "from") {
                utterance = new SpeechSynthesisUtterance(fromText.value);
                utterance.lang = selectTag[0].value;
            } else {
                utterance = new SpeechSynthesisUtterance(toText.value);
                utterance.lang = selectTag[1].value;
            }
            speechSynthesis.speak(utterance);
        }
    });
});

That’s all, now you’ve successfully built a Language Translator in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

 

]]>
https://www.codingnepalweb.com/language-translator-app-html-css-javascript/feed/ 22
QR Code Generator in HTML CSS & JavaScript https://www.codingnepalweb.com/qr-code-generator-html-css-javascript/ https://www.codingnepalweb.com/qr-code-generator-html-css-javascript/#comments Mon, 28 Mar 2022 16:27:59 +0000 https://www.codingnepalweb.com/?p=2400 QR Code Generator in HTML CSS & JavaScript

Hey friends, today in this blog, you’ll learn how to create a QR Code Generator in HTML CSS & JavaScript. In the earlier blog, I have shared how to create a Random Quote Generator in JavaScript, and now it’s time to make a QR Code Generator in JavaScript.

QR (Quick Response) codes are capable of storing lots of data, and users can easily access the information by scanning the QR code. In my QR Code Generator app, users can enter a text or URL to generate a QR code for it. It is a QR code generator app, not a QR code scanner.

If you’re feeling difficulty to understand what I’m saying or what this QR code generator looks like then you can watch a video tutorial of this QR code generator in JavaScript.

Video Tutorial of QR Code Generator in JavaScript

 

 
In the above video, you’ve seen the demo of a QR code generator and how I created it using HTML CSS & JavaScript. As you have seen, to generate a QR code of user inputs, I used the qrserver API. So, I believe you’ve understood the codes and concepts behind creating this QR app even if you’re a beginner at it.

If you liked this QR code generator and want to get source codes or files of it, you can easily get them from the bottom of this page.

But, if you’re a too beginner, I suggest you watch the above video two or three times and try to create it by yourself because in the video I’ve explained each JavaScript line with written comments that helps you to understand the codes more easily.

You might like this:

QR Code Generator in JavaScript [Source Codes]

To create QR Code Generator in JavaScript. First, you need to create three Files: HTML, CSS & JavaScript File. After creating these files just paste the given codes into your file. You can also download the source code files of this QR Code Generator App from the below download button.

First, create an HTML file with the name index.html and paste the given codes into your HTML file. Remember, you’ve to create a file with .html extension.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">  
    <title>QR Code Generator in JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <div class="wrapper">
      <header>
        <h1>QR Code Generator</h1>
        <p>Paste a url or enter text to create QR code</p>
      </header>
      <div class="form">
        <input type="text" spellcheck="false" placeholder="Enter text or url">
        <button>Generate QR Code</button>
      </div>
      <div class="qr-code">
        <img src="" alt="qr-code">
      </div>
    </div>

    <script src="script.js"></script>

  </body>
</html>

Second, create a CSS file with the name style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

/* Import Google Font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  padding: 0 10px;
  min-height: 100vh;
  align-items: center;
  background: #3498DB;
  justify-content: center;
}
.wrapper{
  height: 265px;
  max-width: 410px;
  background: #fff;
  border-radius: 7px;
  padding: 20px 25px 0;
  transition: height 0.2s ease;
  box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}
.wrapper.active{
  height: 530px;
}
header h1{
  font-size: 21px;
  font-weight: 500;
}
header p{
  margin-top: 5px;
  color: #575757;
  font-size: 16px;
}
.wrapper .form{
  margin: 20px 0 25px;
}
.form :where(input, button){
  width: 100%;
  height: 55px;
  border: none;
  outline: none;
  border-radius: 5px;
  transition: 0.1s ease;
}
.form input{
  font-size: 18px;
  padding: 0 17px;
  border: 1px solid #999;
}
.form input:focus{
  box-shadow: 0 3px 6px rgba(0,0,0,0.13);
}
.form input::placeholder{
  color: #999;
}
.form button{
  color: #fff;
  cursor: pointer;
  margin-top: 20px;
  font-size: 17px;
  background: #3498DB;
}
.qr-code{
  opacity: 0;
  display: flex;
  padding: 33px 0;
  border-radius: 5px;
  align-items: center;
  pointer-events: none;
  justify-content: center;
  border: 1px solid #ccc;
}
.wrapper.active .qr-code{
  opacity: 1;
  pointer-events: auto;
  transition: opacity 0.5s 0.05s ease;
}
.qr-code img{
  width: 170px;
}

@media (max-width: 430px){
  .wrapper{
    height: 255px;
    padding: 16px 20px;
  }
  .wrapper.active{
    height: 510px;
  }
  header p{
    color: #696969;
  }
  .form :where(input, button){
    height: 52px;
  }
  .qr-code img{
    width: 160px;
  }  
}

Last, create a JavaScript file with the name script.js and paste the given codes in your JavaScript file. Remember, you’ve to create a file with .js extension.

const wrapper = document.querySelector(".wrapper"),
qrInput = wrapper.querySelector(".form input"),
generateBtn = wrapper.querySelector(".form button"),
qrImg = wrapper.querySelector(".qr-code img");
let preValue;

generateBtn.addEventListener("click", () => {
    let qrValue = qrInput.value.trim();
    if(!qrValue || preValue === qrValue) return;
    preValue = qrValue;
    generateBtn.innerText = "Generating QR Code...";
    qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrValue}`;
    qrImg.addEventListener("load", () => {
        wrapper.classList.add("active");
        generateBtn.innerText = "Generate QR Code";
    });
});

qrInput.addEventListener("keyup", () => {
    if(!qrInput.value.trim()) {
        wrapper.classList.remove("active");
        preValue = "";
    }
});

That’s all, now you’ve successfully created a QR Code Generator in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

 

]]>
https://www.codingnepalweb.com/qr-code-generator-html-css-javascript/feed/ 11