JavaScript 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
Create A Responsive Image Slider in HTML CSS and JavaScript https://www.codingnepalweb.com/responsive-image-slider-html-css-javascript/ https://www.codingnepalweb.com/responsive-image-slider-html-css-javascript/#respond Mon, 11 Sep 2023 16:47:06 +0000 https://www.codingnepalweb.com/?p=5743 Create Responsive Image Slider in HTML CSS and JavaScript Image Slider in JavaScript

Image sliders have become an important component of websites, used to showcase multiple images in an engaging way. As a beginner web developer, creating an image slider can be a useful project to understand and improve your fundamental web development concepts, such as responsive designs, DOM manipulation, and JavaScript event listeners.

In this blog post, I will show you how to create a responsive image slider using HTML, CSS, and JavaScript. We will use vanilla JavaScript to create this slider without relying on external JavaScript libraries such as SwiperJs or Owl Carousel. This way, beginners can learn how these image sliders work and the code required to build them.

In this image slider, there are two buttons for sliding images: one for going back and one for moving forward. There is also a horizontal scrollbar that acts as a slider indicator and can be used to slide images by dragging it. This slider supports all major browsers like Chrome, Firefox, and Edge, as well as mobile or tablet devices.

Video Tutorial of Image Slider in 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 the process of creating your own image slider 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 image slider that is easy to customize and implement into your other projects.

Steps to Create Image Slider in HTML & JavaScript

To create a responsive image slider 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 all the images you’ll need for this image slider. You can also use your own images.

To start, add the following HTML codes to your index.html file. These codes include all essential HTML semantic tags, such as div, button, img, etc., for the image slider.

<!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>Image Slider in HTML CSS and JavaScript | CodingNepal</title>
    <!-- Google Fonts Link For Icons -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@48,400,0,0" />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="container">
      <div class="slider-wrapper">
        <button id="prev-slide" class="slide-button material-symbols-rounded">
          chevron_left
        </button>
        <ul class="image-list">
          <img class="image-item" src="images/img-1.jpg" alt="img-1" />
          <img class="image-item" src="images/img-2.jpg" alt="img-2" />
          <img class="image-item" src="images/img-3.jpg" alt="img-3" />
          <img class="image-item" src="images/img-4.jpg" alt="img-4" />
          <img class="image-item" src="images/img-5.jpg" alt="img-5" />
          <img class="image-item" src="images/img-6.jpg" alt="img-6" />
          <img class="image-item" src="images/img-7.jpg" alt="img-7" />
          <img class="image-item" src="images/img-8.jpg" alt="img-8" />
          <img class="image-item" src="images/img-9.jpg" alt="img-9" />
          <img class="image-item" src="images/img-10.jpg" alt="img-10" />
        </ul>
        <button id="next-slide" class="slide-button material-symbols-rounded">
          chevron_right
        </button>
      </div>
      <div class="slider-scrollbar">
        <div class="scrollbar-track">
          <div class="scrollbar-thumb"></div>
        </div>
      </div>
    </div>
  </body>
</html>

Next, add the following CSS codes to your style.css file to make your image slider beautiful. You can experiment with different CSS properties like colors, fonts, and backgrounds to give a personalized touch to your slider. If you load the web page in your browser, you can see your image slider with a scrollbar and an arrow button.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #f1f4fd;
}

.container {
  max-width: 1200px;
  width: 95%;
}

.slider-wrapper {
  position: relative;
}

.slider-wrapper .slide-button {
  position: absolute;
  top: 50%;
  outline: none;
  border: none;
  height: 50px;
  width: 50px;
  z-index: 5;
  color: #fff;
  display: flex;
  cursor: pointer;
  font-size: 2.2rem;
  background: #000;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transform: translateY(-50%);
}

.slider-wrapper .slide-button:hover {
  background: #404040;
}

.slider-wrapper .slide-button#prev-slide {
  left: -25px;
  display: none;
}

.slider-wrapper .slide-button#next-slide {
  right: -25px;
}

.slider-wrapper .image-list {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 18px;
  font-size: 0;
  list-style: none;
  margin-bottom: 30px;
  overflow-x: auto;
  scrollbar-width: none;
}

.slider-wrapper .image-list::-webkit-scrollbar {
  display: none;
}

.slider-wrapper .image-list .image-item {
  width: 325px;
  height: 400px;
  object-fit: cover;
}

.container .slider-scrollbar {
  height: 24px;
  width: 100%;
  display: flex;
  align-items: center;
}

.slider-scrollbar .scrollbar-track {
  background: #ccc;
  width: 100%;
  height: 2px;
  display: flex;
  align-items: center;
  border-radius: 4px;
  position: relative;
}

.slider-scrollbar:hover .scrollbar-track {
  height: 4px;
}

.slider-scrollbar .scrollbar-thumb {
  position: absolute;
  background: #000;
  top: 0;
  bottom: 0;
  width: 50%;
  height: 100%;
  cursor: grab;
  border-radius: inherit;
}

.slider-scrollbar .scrollbar-thumb:active {
  cursor: grabbing;
  height: 8px;
  top: -2px;
}

.slider-scrollbar .scrollbar-thumb::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  top: -10px;
  bottom: -10px;
}

/* Styles for mobile and tablets */
@media only screen and (max-width: 1023px) {
  .slider-wrapper .slide-button {
    display: none !important;
  }

  .slider-wrapper .image-list {
    gap: 10px;
    margin-bottom: 15px;
    scroll-snap-type: x mandatory;
  }

  .slider-wrapper .image-list .image-item {
    width: 280px;
    height: 380px;
  }

  .slider-scrollbar .scrollbar-thumb {
    width: 20%;
  }
}

Finally, add the following JavaScript code to your script.js file to make your image slider functional. This code includes event listeners like mouseup, mousemove, mousedown, click, and mathematical calculations to make the slider work as expected.

const initSlider = () => {
    const imageList = document.querySelector(".slider-wrapper .image-list");
    const slideButtons = document.querySelectorAll(".slider-wrapper .slide-button");
    const sliderScrollbar = document.querySelector(".container .slider-scrollbar");
    const scrollbarThumb = sliderScrollbar.querySelector(".scrollbar-thumb");
    const maxScrollLeft = imageList.scrollWidth - imageList.clientWidth;
    
    // Handle scrollbar thumb drag
    scrollbarThumb.addEventListener("mousedown", (e) => {
        const startX = e.clientX;
        const thumbPosition = scrollbarThumb.offsetLeft;
        const maxThumbPosition = sliderScrollbar.getBoundingClientRect().width - scrollbarThumb.offsetWidth;
        
        // Update thumb position on mouse move
        const handleMouseMove = (e) => {
            const deltaX = e.clientX - startX;
            const newThumbPosition = thumbPosition + deltaX;

            // Ensure the scrollbar thumb stays within bounds
            const boundedPosition = Math.max(0, Math.min(maxThumbPosition, newThumbPosition));
            const scrollPosition = (boundedPosition / maxThumbPosition) * maxScrollLeft;
            
            scrollbarThumb.style.left = `${boundedPosition}px`;
            imageList.scrollLeft = scrollPosition;
        }

        // Remove event listeners on mouse up
        const handleMouseUp = () => {
            document.removeEventListener("mousemove", handleMouseMove);
            document.removeEventListener("mouseup", handleMouseUp);
        }

        // Add event listeners for drag interaction
        document.addEventListener("mousemove", handleMouseMove);
        document.addEventListener("mouseup", handleMouseUp);
    });

    // Slide images according to the slide button clicks
    slideButtons.forEach(button => {
        button.addEventListener("click", () => {
            const direction = button.id === "prev-slide" ? -1 : 1;
            const scrollAmount = imageList.clientWidth * direction;
            imageList.scrollBy({ left: scrollAmount, behavior: "smooth" });
        });
    });

     // Show or hide slide buttons based on scroll position
    const handleSlideButtons = () => {
        slideButtons[0].style.display = imageList.scrollLeft <= 0 ? "none" : "flex";
        slideButtons[1].style.display = imageList.scrollLeft >= maxScrollLeft ? "none" : "flex";
    }

    // Update scrollbar thumb position based on image scroll
    const updateScrollThumbPosition = () => {
        const scrollPosition = imageList.scrollLeft;
        const thumbPosition = (scrollPosition / maxScrollLeft) * (sliderScrollbar.clientWidth - scrollbarThumb.offsetWidth);
        scrollbarThumb.style.left = `${thumbPosition}px`;
    }

    // Call these two functions when image list scrolls
    imageList.addEventListener("scroll", () => {
        updateScrollThumbPosition();
        handleSlideButtons();
    });
}

window.addEventListener("resize", initSlider);
window.addEventListener("load", initSlider);

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, creating a responsive image slider from scratch using HTML, CSS, and vanilla JavaScript is not only a valuable learning experience but also a practical addition to your web development skills. By following the steps in this post, you have successfully built a functional image slider, and you can now easily customize it according to your choice.

Feel free to experiment with different styles, transitions, and features to take your image slider to the next level. To further improve your web development, I recommend you try recreating other interactive images or card sliders available on this website.

If you encounter any problems while creating your image slider, you can download the source code files for this project for free by clicking the Download button. Additionally, you can view a live demo of it by clicking the View Live button.

]]>
https://www.codingnepalweb.com/responsive-image-slider-html-css-javascript/feed/ 0
Build A Hangman Game in HTML CSS and JavaScript https://www.codingnepalweb.com/build-hangman-game-html-javascript/ https://www.codingnepalweb.com/build-hangman-game-html-javascript/#respond Fri, 21 Jul 2023 18:16:51 +0000 https://www.codingnepalweb.com/?p=5678 Build A Hangman Game in HTML CSS and JavaScript

Hangman is the classic word-guessing game you’ve likely enjoyed playing. But as a beginner web developer, have you ever thought about building your own Hangman game? Building a hangman game is not only fun and engaging but also provides an excellent opportunity to enhance your web development and problem-solving skills.

If you’re unfamiliar, Hangman is a word-guessing game where players try to guess all the letters of a randomly generated word within a given number of tries. There is also a hangman illustration that will progressively appear on the gallows for each incorrect guess.

In this beginner-friendly blog post, I’ll show you how to build a Hangman game in HTML, CSS, and JavaScript. By creating this game, you’ll gain practical experience and dive into essential concepts of web development, such as DOM manipulation, event handling, conditional statements, array usage, and many more.

Video Tutorial of Hangman Game HTML & JavaScript

If you enjoy learning through video tutorials, the above YouTube video is an excellent resource. In the video, I’ve explained each line of code and provided informative comments to make the process of building your own Hangman game beginner-friendly and easy to follow.

However, if you like reading blog posts or want a step-by-step guide for building this game, you can continue reading this post. By the end of this post, you’ll have your own Hangman game that you can play or show off to your friends.

Steps to Build Hangman Game in HTML & JavaScript

To build a Hangman game 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 scripts folder with word-list.js and script.js files. The extension of the files must be .js and files should be inside the scripts folder.
  5. Download and place the Images folder in your project directory. This folder includes the necessary images and gifs for the game.

To start, add the following HTML codes to your index.html file. These codes include essential HTML elements, such as a modal box and a container for the game. Using JavaScript later, we’ll add or modify these elements and randomize game letters, hints, and keyboard keys.

<!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>Hangman Game JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <script src="scripts/word-list.js" defer></script>
    <script src="scripts/script.js" defer></script>
</head>
<body>
    <div class="game-modal">
        <div class="content">
            <img src="#" alt="gif">
            <h4>Game Over!</h4>
            <p>The correct word was: <b>rainbow</b></p>
            <button class="play-again">Play Again</button>
        </div>
    </div>
    <div class="container">
        <div class="hangman-box">
            <img src="#" draggable="false" alt="hangman-img">
            <h1>Hangman Game</h1>
        </div>
        <div class="game-box">
            <ul class="word-display"></ul>
            <h4 class="hint-text">Hint: <b></b></h4>
            <h4 class="guesses-text">Incorrect guesses: <b></b></h4>
            <div class="keyboard"></div>
        </div>
    </div>
</body>
</html>

Next, add the following CSS codes to your style.css file to apply visual styling to your game: color, font, border, background, etc. Now, if you load the web page in your browser, you will see the Hangman game with its various styled elements. You can play around with colors, fonts, borders, backgrounds, and more to give your Hangman game a unique and appealing look.

/* Importing 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 {
    display: flex;
    padding: 0 10px;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    background: #5E63BA;
}
.container {
    display: flex;
    width: 850px;
    gap: 70px;
    padding: 60px 40px;
    background: #fff;
    border-radius: 10px;
    align-items: flex-end;
    justify-content: space-between;
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}
.hangman-box img {
    user-select: none;
    max-width: 270px;
}
.hangman-box h1 {
    font-size: 1.45rem;
    text-align: center;
    margin-top: 20px;
    text-transform: uppercase;
}
.game-box .word-display {
    gap: 10px;
    list-style: none;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}
.word-display .letter {
    width: 28px;
    font-size: 2rem;
    text-align: center;
    font-weight: 600;
    margin-bottom: 40px;
    text-transform: uppercase;
    border-bottom: 3px solid #000;
}
.word-display .letter.guessed {
    margin: -40px 0 35px;
    border-color: transparent;
}
.game-box h4 {
    text-align: center;
    font-size: 1.1rem;
    font-weight: 500;
    margin-bottom: 15px;
}
.game-box h4 b {
    font-weight: 600;
}
.game-box .guesses-text b {
    color: #ff0000;
}
.game-box .keyboard {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
    margin-top: 40px;
    justify-content: center;
}
:where(.game-modal, .keyboard) button {
    color: #fff;
    border: none;
    outline: none;
    cursor: pointer;
    font-size: 1rem;
    font-weight: 600;
    border-radius: 4px;
    text-transform: uppercase;
    background: #5E63BA;
}
.keyboard button {
    padding: 7px;
    width: calc(100% / 9 - 5px);
}
.keyboard button[disabled] {
    pointer-events: none;
    opacity: 0.6;
}
:where(.game-modal, .keyboard) button:hover {
    background: #8286c9;
}
.game-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    pointer-events: none;
    background: rgba(0,0,0,0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    padding: 0 10px;
    transition: opacity 0.4s ease;
}
.game-modal.show {
    opacity: 1;
    pointer-events: auto;
    transition: opacity 0.4s 0.4s ease;
}
.game-modal .content {
    padding: 30px;
    max-width: 420px;
    width: 100%;
    border-radius: 10px;
    background: #fff;
    text-align: center;
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}
.game-modal img {
    max-width: 130px;
    margin-bottom: 20px;
}
.game-modal img[src="images/victory.gif"] {
    margin-left: -10px;
}
.game-modal h4 {
    font-size: 1.53rem;
}
.game-modal p {
    font-size: 1.15rem;
    margin: 15px 0 30px;
    font-weight: 500;
}
.game-modal p b {
    color: #5E63BA;
    font-weight: 600;
}
.game-modal button {
    padding: 12px 23px;
}

@media (max-width: 782px) {
    .container {
        flex-direction: column;
        padding: 30px 15px;
        align-items: center;
    }
    .hangman-box img {
        max-width: 200px;
    }
    .hangman-box h1 {
        display: none;
    }
    .game-box h4 {
        font-size: 1rem;
    }
    .word-display .letter {
        margin-bottom: 35px;
        font-size: 1.7rem;
    }
    .word-display .letter.guessed {
        margin: -35px 0 25px;
    }
    .game-modal img {
        max-width: 120px;
    }
    .game-modal h4 {
        font-size: 1.45rem;
    }
    .game-modal p {
        font-size: 1.1rem;
    }
    .game-modal button {
        padding: 10px 18px;
    }
}

Next, add the following JavaScript code to your word-list.js file: This script includes a list of various words along with corresponding hints. Feel free to expand this list to make your Hangman game even more enjoyable and challenging for players.

const wordList = [
    {
        word: "guitar",
        hint: "A musical instrument with strings."
    },
    {
        word: "oxygen",
        hint: "A colorless, odorless gas essential for life."
    },
    {
        word: "mountain",
        hint: "A large natural elevation of the Earth's surface."
    },
    {
        word: "painting",
        hint: "An art form using colors on a surface to create images or expression."
    },
    {
        word: "astronomy",
        hint: "The scientific study of celestial objects and phenomena."
    },
    {
        word: "football",
        hint: "A popular sport played with a spherical ball."
    },
    {
        word: "chocolate",
        hint: "A sweet treat made from cocoa beans."
    },
    {
        word: "butterfly",
        hint: "An insect with colorful wings and a slender body."
    },
    {
        word: "history",
        hint: "The study of past events and human civilization."
    },
    {
        word: "pizza",
        hint: "A savory dish consisting of a round, flattened base with toppings."
    },
    {
        word: "jazz",
        hint: "A genre of music characterized by improvisation and syncopation."
    },
    {
        word: "camera",
        hint: "A device used to capture and record images or videos."
    },
    {
        word: "diamond",
        hint: "A precious gemstone known for its brilliance and hardness."
    },
    {
        word: "adventure",
        hint: "An exciting or daring experience."
    },
    {
        word: "science",
        hint: "The systematic study of the structure and behavior of the physical and natural world."
    },
    {
        word: "bicycle",
        hint: "A human-powered vehicle with two wheels."
    },
    {
        word: "sunset",
        hint: "The daily disappearance of the sun below the horizon."
    },
    {
        word: "coffee",
        hint: "A popular caffeinated beverage made from roasted coffee beans."
    },
    {
        word: "dance",
        hint: "A rhythmic movement of the body often performed to music."
    },
    {
        word: "galaxy",
        hint: "A vast system of stars, gas, and dust held together by gravity."
    },
    {
        word: "orchestra",
        hint: "A large ensemble of musicians playing various instruments."
    },
    {
        word: "volcano",
        hint: "A mountain or hill with a vent through which lava, rock fragments, hot vapor, and gas are ejected."
    },
    {
        word: "novel",
        hint: "A long work of fiction, typically with a complex plot and characters."
    },
    {
        word: "sculpture",
        hint: "A three-dimensional art form created by shaping or combining materials."
    },
    {
        word: "symphony",
        hint: "A long musical composition for a full orchestra, typically in multiple movements."
    },
    {
        word: "architecture",
        hint: "The art and science of designing and constructing buildings."
    },
    {
        word: "ballet",
        hint: "A classical dance form characterized by precise and graceful movements."
    },
    {
        word: "astronaut",
        hint: "A person trained to travel and work in space."
    },
    {
        word: "waterfall",
        hint: "A cascade of water falling from a height."
    },
    {
        word: "technology",
        hint: "The application of scientific knowledge for practical purposes."
    },
    {
        word: "rainbow",
        hint: "A meteorological phenomenon that is caused by reflection, refraction, and dispersion of light."
    },
    {
        word: "universe",
        hint: "All existing matter, space, and time as a whole."
    },
    {
        word: "piano",
        hint: "A musical instrument played by pressing keys that cause hammers to strike strings."
    },
    {
        word: "vacation",
        hint: "A period of time devoted to pleasure, rest, or relaxation."
    },
    {
        word: "rainforest",
        hint: "A dense forest characterized by high rainfall and biodiversity."
    },
    {
        word: "theater",
        hint: "A building or outdoor area in which plays, movies, or other performances are staged."
    },
    {
        word: "telephone",
        hint: "A device used to transmit sound over long distances."
    },
    {
        word: "language",
        hint: "A system of communication consisting of words, gestures, and syntax."
    },
    {
        word: "desert",
        hint: "A barren or arid land with little or no precipitation."
    },
    {
        word: "sunflower",
        hint: "A tall plant with a large yellow flower head."
    },
    {
        word: "fantasy",
        hint: "A genre of imaginative fiction involving magic and supernatural elements."
    },
    {
        word: "telescope",
        hint: "An optical instrument used to view distant objects in space."
    },
    {
        word: "breeze",
        hint: "A gentle wind."
    },
    {
        word: "oasis",
        hint: "A fertile spot in a desert where water is found."
    },
    {
        word: "photography",
        hint: "The art, process, or practice of creating images by recording light or other electromagnetic radiation."
    },
    {
        word: "safari",
        hint: "An expedition or journey, typically to observe wildlife in their natural habitat."
    },
    {
        word: "planet",
        hint: "A celestial body that orbits a star and does not produce light of its own."
    },
    {
        word: "river",
        hint: "A large natural stream of water flowing in a channel to the sea, a lake, or another such stream."
    },
    {
        word: "tropical",
        hint: "Relating to or situated in the region between the Tropic of Cancer and the Tropic of Capricorn."
    },
    {
        word: "mysterious",
        hint: "Difficult or impossible to understand, explain, or identify."
    },
    {
        word: "enigma",
        hint: "Something that is mysterious, puzzling, or difficult to understand."
    },
    {
        word: "paradox",
        hint: "A statement or situation that contradicts itself or defies intuition."
    },
    {
        word: "puzzle",
        hint: "A game, toy, or problem designed to test ingenuity or knowledge."
    },
    {
        word: "whisper",
        hint: "To speak very softly or quietly, often in a secretive manner."
    },
    {
        word: "shadow",
        hint: "A dark area or shape produced by an object blocking the light."
    },
    {
        word: "secret",
        hint: "Something kept hidden or unknown to others."
    },
    {
        word: "curiosity",
        hint: "A strong desire to know or learn something."
    },
    {
        word: "unpredictable",
        hint: "Not able to be foreseen or known beforehand; uncertain."
    },
    {
        word: "obfuscate",
        hint: "To confuse or bewilder someone; to make something unclear or difficult to understand."
    },
    {
        word: "unveil",
        hint: "To make known or reveal something previously secret or unknown."
    },
    {
        word: "illusion",
        hint: "A false perception or belief; a deceptive appearance or impression."
    },
    {
        word: "moonlight",
        hint: "The light from the moon."
    },
    {
        word: "vibrant",
        hint: "Full of energy, brightness, and life."
    },
    {
        word: "nostalgia",
        hint: "A sentimental longing or wistful affection for the past."
    },
    {
        word: "brilliant",
        hint: "Exceptionally clever, talented, or impressive."
    },
];

Finally, add the following JavaScript code to your script.js file. This script code will be responsible for the game’s logic, including generating a random word, managing user input, keeping track of guessed letters, checking for correct guesses, and updating the hangman’s visual representation as the game progresses.

const wordDisplay = document.querySelector(".word-display");
const guessesText = document.querySelector(".guesses-text b");
const keyboardDiv = document.querySelector(".keyboard");
const hangmanImage = document.querySelector(".hangman-box img");
const gameModal = document.querySelector(".game-modal");
const playAgainBtn = gameModal.querySelector("button");

// Initializing game variables
let currentWord, correctLetters, wrongGuessCount;
const maxGuesses = 6;

const resetGame = () => {
    // Ressetting game variables and UI elements
    correctLetters = [];
    wrongGuessCount = 0;
    hangmanImage.src = "images/hangman-0.svg";
    guessesText.innerText = `${wrongGuessCount} / ${maxGuesses}`;
    wordDisplay.innerHTML = currentWord.split("").map(() => `<li class="letter"></li>`).join("");
    keyboardDiv.querySelectorAll("button").forEach(btn => btn.disabled = false);
    gameModal.classList.remove("show");
}

const getRandomWord = () => {
    // Selecting a random word and hint from the wordList
    const { word, hint } = wordList[Math.floor(Math.random() * wordList.length)];
    currentWord = word; // Making currentWord as random word
    document.querySelector(".hint-text b").innerText = hint;
    resetGame();
}

const gameOver = (isVictory) => {
    // After game complete.. showing modal with relevant details
    const modalText = isVictory ? `You found the word:` : 'The correct word was:';
    gameModal.querySelector("img").src = `images/${isVictory ? 'victory' : 'lost'}.gif`;
    gameModal.querySelector("h4").innerText = isVictory ? 'Congrats!' : 'Game Over!';
    gameModal.querySelector("p").innerHTML = `${modalText} <b>${currentWord}</b>`;
    gameModal.classList.add("show");
}

const initGame = (button, clickedLetter) => {
    // Checking if clickedLetter is exist on the currentWord
    if(currentWord.includes(clickedLetter)) {
        // Showing all correct letters on the word display
        [...currentWord].forEach((letter, index) => {
            if(letter === clickedLetter) {
                correctLetters.push(letter);
                wordDisplay.querySelectorAll("li")[index].innerText = letter;
                wordDisplay.querySelectorAll("li")[index].classList.add("guessed");
            }
        });
    } else {
        // If clicked letter doesn't exist then update the wrongGuessCount and hangman image
        wrongGuessCount++;
        hangmanImage.src = `images/hangman-${wrongGuessCount}.svg`;
    }
    button.disabled = true; // Disabling the clicked button so user can't click again
    guessesText.innerText = `${wrongGuessCount} / ${maxGuesses}`;

    // Calling gameOver function if any of these condition meets
    if(wrongGuessCount === maxGuesses) return gameOver(false);
    if(correctLetters.length === currentWord.length) return gameOver(true);
}

// Creating keyboard buttons and adding event listeners
for (let i = 97; i <= 122; i++) {
    const button = document.createElement("button");
    button.innerText = String.fromCharCode(i);
    keyboardDiv.appendChild(button);
    button.addEventListener("click", (e) => initGame(e.target, String.fromCharCode(i)));
}

getRandomWord();
playAgainBtn.addEventListener("click", getRandomWord);

That’s all! To understand JavaScript code better, I recommend watching the above video tutorial, paying close attention to the code comments, and experimenting with the code.

Conclusion and Final Words

In conclusion, building a Hangman game from scratch using HTML, CSS, and JavaScript is an enjoyable and rewarding experience that can strengthen your web development and problem-solving skills. I believe that by following the steps in this post, you’ve successfully built your very own Hangman game.

Remember to experiment and customize your game to add personal touches and make it even more engaging. To continue improving your skills, I recommend exploring my blog post on How to Build Snake Game in HTML, CSS, and JavaScript.

If you encounter any problems while building your Hangman game, you can download the source code files for this game 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/build-hangman-game-html-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 A Draggable Card Slider in HTML CSS & JavaScript https://www.codingnepalweb.com/draggable-card-slider-html-css-javascript/ https://www.codingnepalweb.com/draggable-card-slider-html-css-javascript/#respond Mon, 08 May 2023 14:22:32 +0000 https://www.codingnepalweb.com/?p=5117 Create A Draggable Card Slider in HTML CSS & JavaScript

Sliders have become a crucial part of web design, used to showcase content or images in an engaging and interactive way. As a beginner, creating a card slider can help you develop fundamental web development concepts such as DOM manipulation, responsive designs, and JavaScript event listeners.

These concepts are vital for front-end developers to understand and can be applied to various web development projects. So in this blog post, we will show you how to create a responsive draggable card slider in HTML, CSS, and JavaScript, which can be used to display images, products, user profiles, and other content.

In order to truly understand how a draggable card slider works, we won’t be using any external JavaScript libraries such as SwiperJs or Owl Carousel. Instead, we’ll be creating the slider from scratch using pure vanilla JavaScript, HTML, and CSS. However, if you prefer using a library-based slider, you can check out our other slider blogs.

In our draggable card slider, the user can slide cards by dragging them or using the left or right buttons. It also includes infinite scrolling and autoplay functionality and works on touch-enabled devices like phones.

Video Tutorial of Draggable Card Slider 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 explanatory comments to make the code easy to understand and follow, especially for beginners.

However, if you prefer reading blog posts or want a quick summary of the steps involved in creating a card slider, you can continue reading this post. By the end of this post, you will have a good understanding of how to create a draggable card slider with HTML, CSS, and JavaScript.

Steps To Create Draggable Card Slider in JavaScript

To create a draggable card or image slider 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 folder has all the images that will be used for this slider.

To start, add the following HTML codes to your index.html file to create a basic layout for our card slider. This code includes a ul element to hold all of the li elements, which represent each card in the slider. Additionally, the code includes next and previous icons for navigation through the slider.

<!DOCTYPE html>
<!-- Website - www.codingnepalweb.com -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Infinite Card Slider JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Fontawesome Link for Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="wrapper">
      <i id="left" class="fa-solid fa-angle-left"></i>
      <ul class="carousel">
        <li class="card">
          <div class="img"><img src="images/img-1.jpg" alt="img" draggable="false"></div>
          <h2>Blanche Pearson</h2>
          <span>Sales Manager</span>
        </li>
        <li class="card">
          <div class="img"><img src="images/img-2.jpg" alt="img" draggable="false"></div>
          <h2>Joenas Brauers</h2>
          <span>Web Developer</span>
        </li>
        <li class="card">
          <div class="img"><img src="images/img-3.jpg" alt="img" draggable="false"></div>
          <h2>Lariach French</h2>
          <span>Online Teacher</span>
        </li>
        <li class="card">
          <div class="img"><img src="images/img-4.jpg" alt="img" draggable="false"></div>
          <h2>James Khosravi</h2>
          <span>Freelancer</span>
        </li>
        <li class="card">
          <div class="img"><img src="images/img-5.jpg" alt="img" draggable="false"></div>
          <h2>Kristina Zasiadko</h2>
          <span>Bank Manager</span>
        </li>
        <li class="card">
          <div class="img"><img src="images/img-6.jpg" alt="img" draggable="false"></div>
          <h2>Donald Horton</h2>
          <span>App Designer</span>
        </li>
      </ul>
      <i id="right" class="fa-solid fa-angle-right"></i>
    </div>

  </body>
</html>

Next, add the following CSS codes to your style.css file to style the cards and position the next and previous icons. You can customize this code to your liking by adjusting the color, font, size, and other CSS properties. Once you’ve added the CSS code, you should see three cards displayed on your browser screen.

/* 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 {
  display: flex;
  padding: 0 35px;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: linear-gradient(to left top, #031A9A, #8B53FF);
}
.wrapper {
  max-width: 1100px;
  width: 100%;
  position: relative;
}
.wrapper i {
  top: 50%;
  height: 50px;
  width: 50px;
  cursor: pointer;
  font-size: 1.25rem;
  position: absolute;
  text-align: center;
  line-height: 50px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 3px 6px rgba(0,0,0,0.23);
  transform: translateY(-50%);
  transition: transform 0.1s linear;
}
.wrapper i:active{
  transform: translateY(-50%) scale(0.85);
}
.wrapper i:first-child{
  left: -22px;
}
.wrapper i:last-child{
  right: -22px;
}
.wrapper .carousel{
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: calc((100% / 3) - 12px);
  overflow-x: auto;
  scroll-snap-type: x mandatory;
  gap: 16px;
  border-radius: 8px;
  scroll-behavior: smooth;
  scrollbar-width: none;
}
.carousel::-webkit-scrollbar {
  display: none;
}
.carousel.no-transition {
  scroll-behavior: auto;
}
.carousel.dragging {
  scroll-snap-type: none;
  scroll-behavior: auto;
}
.carousel.dragging .card {
  cursor: grab;
  user-select: none;
}
.carousel :where(.card, .img) {
  display: flex;
  justify-content: center;
  align-items: center;
}
.carousel .card {
  scroll-snap-align: start;
  height: 342px;
  list-style: none;
  background: #fff;
  cursor: pointer;
  padding-bottom: 15px;
  flex-direction: column;
  border-radius: 8px;
}
.carousel .card .img {
  background: #8B53FF;
  height: 148px;
  width: 148px;
  border-radius: 50%;
}
.card .img img {
  width: 140px;
  height: 140px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #fff;
}
.carousel .card h2 {
  font-weight: 500;
  font-size: 1.56rem;
  margin: 30px 0 5px;
}
.carousel .card span {
  color: #6A6D78;
  font-size: 1.31rem;
}

@media screen and (max-width: 900px) {
  .wrapper .carousel {
    grid-auto-columns: calc((100% / 2) - 9px);
  }
}

@media screen and (max-width: 600px) {
  .wrapper .carousel {
    grid-auto-columns: 100%;
  }
}

Finally, add the following JavaScript code to your script.js file to make the cards draggable, autoplayable, and create an infinite slider.

const wrapper = document.querySelector(".wrapper");
const carousel = document.querySelector(".carousel");
const firstCardWidth = carousel.querySelector(".card").offsetWidth;
const arrowBtns = document.querySelectorAll(".wrapper i");
const carouselChildrens = [...carousel.children];

let isDragging = false, isAutoPlay = true, startX, startScrollLeft, timeoutId;

// Get the number of cards that can fit in the carousel at once
let cardPerView = Math.round(carousel.offsetWidth / firstCardWidth);

// Insert copies of the last few cards to beginning of carousel for infinite scrolling
carouselChildrens.slice(-cardPerView).reverse().forEach(card => {
    carousel.insertAdjacentHTML("afterbegin", card.outerHTML);
});

// Insert copies of the first few cards to end of carousel for infinite scrolling
carouselChildrens.slice(0, cardPerView).forEach(card => {
    carousel.insertAdjacentHTML("beforeend", card.outerHTML);
});

// Scroll the carousel at appropriate postition to hide first few duplicate cards on Firefox
carousel.classList.add("no-transition");
carousel.scrollLeft = carousel.offsetWidth;
carousel.classList.remove("no-transition");

// Add event listeners for the arrow buttons to scroll the carousel left and right
arrowBtns.forEach(btn => {
    btn.addEventListener("click", () => {
        carousel.scrollLeft += btn.id == "left" ? -firstCardWidth : firstCardWidth;
    });
});

const dragStart = (e) => {
    isDragging = true;
    carousel.classList.add("dragging");
    // Records the initial cursor and scroll position of the carousel
    startX = e.pageX;
    startScrollLeft = carousel.scrollLeft;
}

const dragging = (e) => {
    if(!isDragging) return; // if isDragging is false return from here
    // Updates the scroll position of the carousel based on the cursor movement
    carousel.scrollLeft = startScrollLeft - (e.pageX - startX);
}

const dragStop = () => {
    isDragging = false;
    carousel.classList.remove("dragging");
}

const infiniteScroll = () => {
    // If the carousel is at the beginning, scroll to the end
    if(carousel.scrollLeft === 0) {
        carousel.classList.add("no-transition");
        carousel.scrollLeft = carousel.scrollWidth - (2 * carousel.offsetWidth);
        carousel.classList.remove("no-transition");
    }
    // If the carousel is at the end, scroll to the beginning
    else if(Math.ceil(carousel.scrollLeft) === carousel.scrollWidth - carousel.offsetWidth) {
        carousel.classList.add("no-transition");
        carousel.scrollLeft = carousel.offsetWidth;
        carousel.classList.remove("no-transition");
    }

    // Clear existing timeout & start autoplay if mouse is not hovering over carousel
    clearTimeout(timeoutId);
    if(!wrapper.matches(":hover")) autoPlay();
}

const autoPlay = () => {
    if(window.innerWidth < 800 || !isAutoPlay) return; // Return if window is smaller than 800 or isAutoPlay is false
    // Autoplay the carousel after every 2500 ms
    timeoutId = setTimeout(() => carousel.scrollLeft += firstCardWidth, 2500);
}
autoPlay();

carousel.addEventListener("mousedown", dragStart);
carousel.addEventListener("mousemove", dragging);
document.addEventListener("mouseup", dragStop);
carousel.addEventListener("scroll", infiniteScroll);
wrapper.addEventListener("mouseenter", () => clearTimeout(timeoutId));
wrapper.addEventListener("mouseleave", autoPlay);

If you look at the code carefully, everything is explained in the comments. You can stop the autoplay feature by setting the isAutoPlay global variable to false, adjust the autoplay delay duration, and modify other features to customize the slider to your preferences.

Conclusion and Final Words

By following the steps given in this blog post, I hope you were able to create a custom draggable card slider using HTML, CSS, and JavaScript. By creating the slider from scratch, you gain a deeper understanding of how sliders work and can customize the slider to meet your specific needs.

Now, you can use this knowledge to create different interactive web projects to expand your web development skillset even further. If you wish, you can view this blog post on Functional Image Gallery in HTML, CSS, and JavaScript. In this gallery, users can search, view, and download any image within a second.

If you face any difficulties while creating your own card slider or your code is not working as expected, you can download the source code files for this card slider for free by clicking on the download button, and you can also view a live demo of this card slider by clicking on the view live button.

View Live Demo

 

]]>
https://www.codingnepalweb.com/draggable-card-slider-html-css-javascript/feed/ 0
Build A Gradient Color Generator in HTML CSS & JavaScript https://www.codingnepalweb.com/gradient-color-generator-html-javascript/ https://www.codingnepalweb.com/gradient-color-generator-html-javascript/#respond Wed, 22 Mar 2023 08:32:26 +0000 https://www.codingnepalweb.com/?p=4053 Build A Gradient Color Generator in HTML CSS & JavaScript Gradient Generator in JavaScript

As a web developer, you must have visited different sites to generate a gradient background color for your project. But have you ever felt the desire to create your own beautiful gradient generator from scratch?

In this blog post, I’ll show the steps for building a gradient color generator using HTML, CSS, and JavaScript. This project is perfect for beginners who want to learn more about web development concepts such as DOM manipulation, event handling, and CSS styling.

In this gradient generator, you can easily create different gradient backgrounds by randomly generating colors or selecting your preferred colors. You can also copy the CSS color code for your generated gradient with a single click.

If you’re excited to see a demo of a gradient generator in action, click here to check it out. For a full video tutorial on creating a gradient color generator using HTML, CSS, and JavaScript, you can watch the given YouTube video.

Video Tutorial of Gradient Color Generator in JavaScript

 
If you prefer visual learning, then the above video tutorial is a great resource for you. In this video, I’ve explained each line of code in detail with 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 a gradient generator, you can continue reading this post. By the end of this post, you will have a good understanding of how to create a gradient color generator in HTML, CSS, and JavaScript on your own from scratch.

Steps For Creating Gradient Generator in JavaScript

To create a gradient color generator using HTML, CSS, and 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

To start, add the following HTML codes to your index.html file to create a basic structure for a gradient color generator.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Gradient Color Generator in 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>
    <div class="wrapper">
      <div class="gradient-box"></div>
      <div class="row options">
        <div class="column direction">
          <p>Direction</p>
          <div class="select-box">
            <select>
              <option value="to top">Top</option>
              <option value="to right top">Right top</option>
              <option value="to right">Right</option>
              <option value="to right bottom">Right bottom</option>
              <option value="to bottom">Bottom</option>
              <option value="to left bottom">Left bottom</option>
              <option value="to left">Left</option>
              <option value="to left top" selected>Left top</option>
            </select>
          </div>
        </div>
        <div class="column palette">
          <p>Colors</p>
          <div class="colors">
            <input type="color" value="#5665E9">
            <input type="color" value="#A271F8">
          </div>
        </div>
      </div>
      <textarea class="row" disabled>background-image: linear-gradient(to left top, #977DFE,  #6878FF);</textarea>
      <div class="row buttons">
        <button class="refresh">Refresh Colors</button>
        <button class="copy">Copy Code</button>
      </div>
    </div>
        
  </body>
</html>

Next, add the following CSS codes to your style.css file to style and make the gradient generator visually appealing. If you wish, you can customize it to your liking by changing the color, font, size, and other 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;
}
body {
  padding: 0 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #8A6CFF;
}
.wrapper {
  width: 450px;
  padding: 25px;
  background: #fff;
  border-radius: 7px;
  box-shadow: 0 15px 30px rgba(0,0,0,0.06);
}
.wrapper .gradient-box {
  height: 220px;
  width: 100%;
  border-radius: 7px;
  background: linear-gradient(to left top, #5665E9, #A271F8);
}
.wrapper .row {
  display: flex;
  margin: 20px 0;
  justify-content: space-between;
}
.options p {
  font-size: 1.1rem;
  margin-bottom: 8px;
}
.row :where(.column, button) {
  width: calc(100% / 2 - 12px);
}
.options .select-box {
  border-radius: 5px;
  padding: 10px 15px;
  border: 1px solid #aaa;
}
.select-box select {
  width: 100%;
  border: none;
  outline: none;
  font-size: 1.12rem;
  background: none;
}
.options .palette {
  margin-left: 60px;
}
.palette input {
  height: 41px;
  width: calc(100% / 2 - 20px);
}
.palette input:last-child {
  margin-left: 6px;
}
.wrapper textarea {
  width: 100%;
  color: #333;
  font-size: 1.05rem;
  resize: none;
  padding: 10px 15px;
  border-radius: 5px;
  border: 1px solid #ccc;
}
.buttons button {
  padding: 15px 0;
  border: none;
  outline: none;
  color: #fff;
  margin: 0 0 -15px;
  font-size: 1.09rem;
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s ease;
}
.buttons .refresh {
  background: #6C757D;
}
.buttons .refresh:hover {
  background: #5f666d;
}
.buttons .copy {
  background: #8A6CFF;
}
.buttons .copy:hover {
  background: #704dff;
}

@media screen and (max-width: 432px) {
  .wrapper {
    padding: 25px 20px;
  }
  .row :where(.column, button) {
    width: calc(100% / 2 - 8px);
  }
  .options .select-box {
    padding: 8px 15px;
  }
  .options .palette  {
    margin-left: 40px;
  }
  .options .colors {
    display: flex;
    justify-content: space-between;
  }
  .palette input {
    width: calc(100% / 2 - 5px);
  }
  .palette input:last-child {
    margin-left: 0;
  }
}

Finally, add the following JavaScript code to your script.js file to add functionality for the gradient generator: To understand the code more deeply, you can watch the above YouTube video tutorial or read the comments within the code and experiment with it.

const gradientBox = document.querySelector(".gradient-box");
const selectMenu = document.querySelector(".select-box select");
const colorInputs = document.querySelectorAll(".colors input");
const textarea = document.querySelector("textarea");
const refreshBtn = document.querySelector(".refresh");
const copyBtn = document.querySelector(".copy");

const getRandomColor = () => {
    // Generating a random color in hexadecimal format. Example: #5665E9
    const randomHex = Math.floor(Math.random() * 0xffffff).toString(16);
    return `#${randomHex}`;
}

const generateGradient = (isRandom) => {
    if(isRandom) { // If isRandom is true, update the colors inputs value with random color
        colorInputs[0].value = getRandomColor();
        colorInputs[1].value = getRandomColor();
    }
    // Creating a gradient string using the select menu value with color input values
    const gradient = `linear-gradient(${selectMenu.value}, ${colorInputs[0].value}, ${colorInputs[1].value})`;
    gradientBox.style.background = gradient;
    textarea.value = `background: ${gradient};`;
}

const copyCode = () => {
    // Copying textarea value and updating the copy button text
    navigator.clipboard.writeText(textarea.value);
    copyBtn.innerText = "Code Copied";
    setTimeout(() => copyBtn.innerText = "Copy Code", 1600);
}

colorInputs.forEach(input => {
    // Calling generateGradient function on each color input clicks
    input.addEventListener("input", () => generateGradient(false));
});

selectMenu.addEventListener("change", () => generateGradient(false));
refreshBtn.addEventListener("click", () => generateGradient(true));
copyBtn.addEventListener("click", copyCode);

Conclusion and Final Words

By following the steps in this blog post, you have successfully built a Gradient Color Generator using HTML, CSS, and JavaScript. With the knowledge and skills you’ve gained from this project, you can now customize the code to suit your unique needs.

Creating a color palette generator is another great way to improve your web development skills. So, don’t forget to check out this blog on the Random Color Palette Generator in JavaScript.

If you encounter any problems or your code is not working as expected, you can download the source code files of this gradient color generator for free. Click on the download button to get the zip file containing the project folder with source code files.

 

]]>
https://www.codingnepalweb.com/gradient-color-generator-html-javascript/feed/ 0
10 Easy JavaScript Games for Beginners with Source Code https://www.codingnepalweb.com/best-javascript-games-for-beginners/ https://www.codingnepalweb.com/best-javascript-games-for-beginners/#comments Fri, 24 Feb 2023 17:14:49 +0000 https://www.codingnepalweb.com/?p=4028 10 Easy JavaScript Games for Beginners with Source Code

Are you looking for a fun and engaging way to learn JavaScript? Creating games is a great way to learn the language and gain experience with programming concepts such as logic, algorithms, and problem-solving skills.

In this blog post, I will share the 10 Easy to Build JavaScript Games for Beginners. Each game on this list is simple but challenging enough to help you learn new JavaScript concepts. So, whether you’re a beginner or an experienced developer, learning to code games with JavaScript is a rewarding experience.

To make your learning process easier, each game is built with HTML, CSS, and vanilla JavaScript which means no external libraries or frameworks are used. I’ve also provided the source code and a video tutorial for all the games on this list.

You can easily reference these resources for guidance if you encounter any problems. So, let’s not waste more time and dive right into the game list!

1. Memory Card Game

Build A Memory Card Game in HTML CSS & JavaScript

Memory Card is a beginner-friendly game that you can create using HTML, CSS, and JavaScript. In this game, 16 cards are placed randomly on the screen, and each pair of cards has the same image. The objective of the game is to find all the matching pairs by clicking on the cards.

There’s no time limit to finding the matching cards, so players can take their time and focus on improving their memory. Creating this game is a great way to practice different JavaScript concepts, including event listeners, loops, arrays, and others.

2. Typing Speed Test Game

Typing Speed Test Game in HTML CSS & JavaScript

You may have tested your typing speed on different typing speed test websites. In this game, users have 60 seconds to type as many characters as possible and can check their WPM, CPM, accuracy, and more. Users can even erase their incorrect characters or go back using the backspace key.

Creating this game is a good way to improve your problem-solving skills and gain a better understanding of JavaScript concepts such as manipulating the DOM, handling event listeners, and creating user-friendly designs.

3. Hangman Game with Illustration

Hangman is the classic word-guessing game you’ve likely enjoyed playing. In this game, players try to guess all the letters of a randomly generated word within a given number of tries. There is also a hangman illustration that will progressively appear on the gallows for each incorrect guess.

Building a Hangman game from scratch using HTML, CSS, and JavaScript is an enjoyable and rewarding experience that can strengthen your web development and problem-solving skills.

Build A Hangman Game in HTML CSS and JavaScript

4. Quiz Game with Timer

Quiz Game with Timer using JavaScript

Quiz is a very popular game that every beginner tries to create using JavaScript. In this game, the users will be asked multiple questions with options and must choose the correct one within 15 seconds. Ultimately, the user score will be shown based on correct answers only.

Creating a Quiz game can help you understand various JavaScript concepts, including manipulating the DOM, using setInterval, working with arrays of objects, writing functions, and using loops. Moreover, this game project can also provide you with valuable experience in HTML and CSS, which can help you in web development.

5. Word Scramble Game

Word Scramble Game in HTML CSS & JavaScript Word Game in JavaScript

Word scramble is an easy word game you can create as a beginner. In this game, players must unscramble a set of letters to form a word within a given time limit of 30 seconds. And to make the game a little easier, users also get a hint about the word they are trying to guess.

By creating this word game, you can gain hands-on experience with essential JavaScript concepts, including arrays, objects, functions, DOM manipulation, string manipulation, event listeners, and conditional statements.

6. Tic Tac Toe Game

Tic Tac Toe Game in JavaScript

Tic Tac Toe is a well-known game that you can build to improve your JavaScript skills. In this game, the player needs to get three of the same symbol in a row, either horizontally, vertically, or diagonally, to win. The second player in this game is the bot, which plays automatically after each player’s turn.

Creating a Tic Tac Toe game can help you develop critical thinking and problem-solving abilities. You’ll learn many important JavaScript concepts, such as DOM manipulation, conditional statements, functions, arrays, event listeners, and more.

It can be a fun way to learn and apply these fundamental concepts while also improving your understanding of game development.

7. Number Guessing Game

Number Guessing Game HTML CSS JavaScript

Random number guessing is an easy game to create that every beginner must try. This game involves the computer or bot selecting a random number that you have to guess correctly. The game provides hints to help you along the way, and you have ten chances to make the correct guess.

It’s a simple but enjoyable game that can help you learn the basics of JavaScript programming, game logic, CSS styling, and more.

8. Word Guessing Game

Word Guessing Game in HTML CSS & JavaScript

Word guessing is the second-word game on this list that you can create as a beginner. In this game, the user has to guess all the letters of a randomly generated word within a specified number of tries. The game provides hints to help make the guessing process easier.

This word game helps you learn how to use JavaScript concepts like setInterval, DOM manipulation, arrays, objects, etc. to create an engaging and interactive game that keeps users engaged and entertained.

9. Rock Paper Scissors Game

Rock Paper Scissors Game HTML CSS JavaScript

Rock, Paper, Scissors is a game that’s widely enjoyed by beginner developers who want to build a simple game. In this game, you’ll play against a bot or computer, and the rules are straightforward: rock beats scissors, scissors beat paper, and paper beats rock.

It’s an excellent game project to work on if you want to develop your skills while creating an entertaining game. You’ll have fun while learning essential programming concepts that can be applied to other projects in the future.

10. Classic Snake Game

Create A Snake Game in HTML CSS & JavaScript JavaScript Game Tutorial

Snake is a classic arcade game that many of us played as children. But now you can create your own version of the game using JavaScript. In this game, players must guide the snake to eat food that appears randomly on the board. The game will end if the snake hits a wall or its own body.

What makes this game even more exciting is that users can play it on a PC using keyboard arrow keys or on a mobile device using touch-based arrow buttons.

Creating a snake game helps you improve problem-solving skills and logical thinking. You’ll also gain a deep understanding of programming concepts like loops, arrays, conditional statements, DOM manipulation, and game loops.

Conclusion and Final Words

In conclusion, these JavaScript games offer a great opportunity for beginners to improve their coding and problem-solving skills. From a memory card to the snake, these game projects cover various aspects of web and game development, including HTML, CSS, and JavaScript.

Choose a game that interests you and get ready to code. I recommended that you try creating these projects on your own rather than simply copying the source code. So, you’ll gain hands-on experience with essential programming concepts that can help you develop a strong foundation for future projects.

Furthermore, you can check out my Top 10 JavaScript Projects for Beginners to get extra coding projects to learn. Remember, practice is key when it comes to coding, so keep coding and experimenting with new ideas to improve your skills. Happy Coding!

]]>
https://www.codingnepalweb.com/best-javascript-games-for-beginners/feed/ 3
Top 10 JavaScript Projects for Beginners with Source Code https://www.codingnepalweb.com/10-javascript-projects-for-beginners/ https://www.codingnepalweb.com/10-javascript-projects-for-beginners/#respond Sun, 05 Feb 2023 12:33:37 +0000 https://www.codingnepalweb.com/?p=4010 10 Best JavaScript Projects with Free Source Code JavaScript Projects for Beginners

Are you a beginner in JavaScript and looking to level up your skills to the next level? Building coding projects is a great way to do that. It is a fun and challenging experience that will help you improve your JavaScript knowledge and understanding of web development.

In this blog post, I will showcase the Top 10 Best JavaScript Projects for Beginners. Each project on this list is simple and challenging enough to help you learn new JavaScript concepts and techniques that will make your web development journey easier.

To make things even easier for you, each project is built with plain vanilla JavaScript—no external libraries or frameworks are required. I’ve also provided the source code and a video tutorial link for each project. So, if you ever get stuck, you can easily reference these resources for guidance.

No matter whether you’re a beginner or an experienced developer, you are sure to find something interesting to work on. So let’s dive in and start the project list.

1. Random Color Palette Generator

Create A Random Color Palette Generator in HTML CSS & JavaScript

Random Color Palette Generator is a simple and beginner-friendly project you can create as a JavaScript developer. In this color generator tool, users can click on the “Refresh Palette” button to generate a new set of random colors with their hex color code.

Users can also easily copy the hex color code by clicking on the corresponding color card. Creating this project will help you learn important JavaScript concepts such as manipulating the DOM, working with loops, handling events, and creating user-friendly designs.

2. Typing Speed Test Game

Typing Speed Test Game in HTML CSS & JavaScript

As a beginner JavaScript developer, the Typing Speed Test is an engaging and fun project to build. In this game, the maximum typing time is 60 seconds, and once the user begins typing, the result will be displayed at the bottom of the screen, including time, mistakes, WPM, and CPM.

Not only is this game enjoyable to build and play, but it also helps you to better understand DOM (Document Object Model) manipulation, enhance your creativity, and develop important problem-solving skills.

3. Language Translator Web Application

Build A Language Translator App in HTML CSS & JavaScript

Language Translator is a multi-featured, API-based project. In this translator app, users can easily translate text into various languages (Nepali, Hindi, Spanish), copy translated text, and pronounce the text with text-to-speech technology. It’s similar to Google Translate, but now you can build your own with JavaScript!

Building this API-based project will give you a deep understanding of important concepts like the Fetch API, DOM manipulation, TTS (Text to Speech), Copy to Clipboard functionality, and many other things.

4. Sticky Notes App with Local Storage

Notes App in HTML CSS & JavaScript

A simple but effective project for beginning JavaScript developers is the Sticky Notes app with CRUD operations. This app allows users to easily add, edit, and delete notes, which are then stored in the browser’s local storage using pure JavaScript. This means that even if the user refreshes the page or closes the tab, their notes will still be there.

Creating this note app is a great way to learn and understand various JavaScript fundamentals, such as CRUD (create, read, update, and delete) operations, local storage, and the JavaScript Date object.

If you don’t want to create the Notes app or have already created it, you can try to create a To-Do List with local storage.

5. Random Password Generator

Random Password Generator in HTML CSS & JavaScript Password Generator in JavaScript

Creating a Random Password Generator with JavaScript is a great beginner-friendly project that will help you understand the basics of DOM manipulation, applying logic to real-world projects and other important JavaScript fundamentals.

In this password generator, users can generate random passwords by customizing their preferred settings, such as lowercase, uppercase, number, etc. There is also a password strength meter that indicates the strength of the user’s generated password. And last, the user can copy their generated password to the clipboard.

6. Simple Word Guessing Game

Word Guessing Game in HTML CSS & JavaScript

The Word Guessing Game is a simple and perfect game project for beginners to start with. The objective of the game is to guess all the letters of a randomly generated word within a given number of tries. The game provides hints to help make the guessing process easier.

By creating this word game, you’ll get hands-on experience with important JavaScript concepts like Arrays, Objects, DOM manipulation, setInterval, and many more things needed to create a game or other project.

If you’re looking for a similar project, why not check out the Word Scramble Game in JavaScript?

7. Virtual Playable Piano

Build A Playable PIANO in HTML CSS & JavaScript Piano in JavaScript

Virtual Playable Piano is a fun and engaging JavaScript project you can build to improve your coding skills. Users can play various tunes on this piano by clicking on the keys or using the keyboard keys. They can also adjust the volume and show or hide shortcut keys on the piano.

Building this piano project will give you an opportunity to understand important concepts such as DOM manipulation, event handling, and more. So, why not bring your love for music and coding together with this exciting project?

8. Drawing or Painting App

Build A Drawing or Paint App in HTML CSS & JavaScript Drawing App in JavaScript

This Drawing or Painting App is a JavaScript project designed for intermediate-level developers. With this app, users can draw various shapes with their desired colors, erase their drawings, and save their drawings as images directly on their PC with a single click.

This project is built using HTML5 canvas and various canvas methods and properties, so it’s recommended to have a basic understanding of canvas before starting this project.

By working on this drawing app, you’ll gain a deeper understanding of HTML5 canvas, which will be helpful for building other canvas-based projects in the future.

9. Color Picker Chrome Extension

Create Color Picker Chrome Extension in HTML CSS & JavaScript

Color Picker Chrome Extension is a useful and educational project that you can create as a JavaScript developer. In this color picker, users can easily pick any color on the screen, view a history of picked colors, and copy or clear them with a single click.

Creating a color picker extension can help you practice your skills in web development and get a better understanding of how Chrome extensions are created with plain HTML, CSS, and JavaScript.

10. Basic Image Editor

Build An Image Editor in HTML CSS & JavaScript

This image editor is another canvas-based JavaScript project on this list that you can build as an intermediate JavaScript developer. In this image editor, users can apply different filters to the image, like grayscale, inversion, saturation, and brightness adjustment. They can also rotate or flip the images and download the edited images with a single click.

Building this image editor gives you an opportunity to learn about CSS filters, HTML5 canvas, and various JavaScript functions and methods. Keep in mind that HTML5 canvas is only used to download the filtered image.

Conclusion and Final Words

In conclusion, these JavaScript projects offer a great opportunity for web developers to improve their coding skills. Whether you’re a beginner or an intermediate developer, these projects can challenge you and help you expand your knowledge of JavaScript.

From a color palette generator to an image editor, these projects cover various aspects of web development and HTML5. So, choose a project that interests you, get ready to code, and enjoy the learning experience. It’s recommended that you try building these projects on your own, rather than simply copying the source code.

If you haven’t found a project that catches your interest, you can check out this list of additional ten JavaScript projects. They are sure to offer you new and exciting challenges.

]]>
https://www.codingnepalweb.com/10-javascript-projects-for-beginners/feed/ 0
Create Random Color Palette Generator in HTML CSS & JavaScript https://www.codingnepalweb.com/color-palette-generator-html-css-javascript/ https://www.codingnepalweb.com/color-palette-generator-html-css-javascript/#comments Thu, 26 Jan 2023 17:21:45 +0000 https://www.codingnepalweb.com/?p=4002 Create A Random Color Palette Generator in HTML CSS & JavaScript

Creating a color palette generator is a great way to improve your web development skills. Not only is it an engaging project, but it also helps you learn important concepts such as manipulating the DOM, working with loops, handling events, and creating user-friendly designs.

This blog post will show you how to Create A Random Color Palette Generator in HTML, CSS, and JavaScript. Users can click on the “Refresh Palette” button in this color palette generator to generate a new set of random colors with their hex color code. They can also easily copy the hex color code by clicking on the corresponding color card.

By the end of this blog post, you’ll have a functional color palette generator that you can use for your own projects or even make live on the Internet. If you’re excited to see how this project looks and works, you can click here to view a live demo of it.

Video Tutorial of Color Palette Generator in JavaScript

 
I hope you enjoyed the demo of this color palette generator and were able to understand how it was created using HTML, CSS, and JavaScript. In the video, I explained the codes with written comments to make them easier to understand, and I believe it worked.

If you haven’t seen the video yet, you can continue reading this post to learn how to create a color palette generator step-by-step by yourself. Otherwise, you can go to the bottom of this page to copy or download the source code and files for this project.

Steps to Create Color Palette Generator in JavaScript

To create a random color palette generator using HTML, CSS, and 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

To start, add the following HTML codes to your index.html file to create the basic layout of the project. The “ul” container is empty now, but it will be filled with “li” elements (representing colors) later using JavaScript code.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Color Palette Generator | 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>
    <ul class="container"></ul>
    <button class="refresh-btn">Refresh Palette</button>
  </body>
</html>

Next, add the following CSS codes to your style.css file to make the layout look better. These codes will style the layout and give it a visually appealing appearance.

/* Import Google font */
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;500;600&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Open Sans', sans-serif;
}
body {
  background: #E3F2FD;
}
.container {
  margin: 20px;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
.container .color {
  margin: 12px;
  padding: 7px;
  list-style: none;
  cursor: pointer;
  text-align: center;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 10px 25px rgba(52,87,220,0.08);
  transition: all 0.3s ease;
}
.container .color:active {
  transform: scale(0.95);
}
.color .rect-box {
  width: 185px;
  height: 188px;
  border-radius: 4px;
}
.color:hover .rect-box {
  filter: brightness(107%);
}
.color .hex-value {
  display: block;
  color: #444;
  user-select: none;
  font-weight: 500;
  font-size: 1.15rem;
  margin: 12px 0 8px;
  text-transform: uppercase;
}
.refresh-btn {
  position: fixed;
  left: 50%;
  bottom: 40px;
  color: #fff;
  cursor: pointer;
  outline: none;
  font-weight: 500;
  font-size: 1.1rem;
  border-radius: 5px;
  background: #8A6CFF;
  padding: 13px 20px;
  border: 2px solid #fff;
  transform: translateX(-50%);
  box-shadow: 0 15px 30px rgba(52,87,220,0.2);
  transition: all 0.3s ease;
}
.refresh-btn:hover {
  background: #704dff;
}

@media screen and (max-width: 500px) {
  .container {
    margin: 10px;
  }
  .container .color {
    margin: 8px;
    padding: 5px;
    width: calc(100% / 2 - 20px);
  }
  .color .rect-box {
    width: 100%;
    height: 148px;
  }
  .color .hex-value {
    font-size: 1.05rem;
  }
  .refresh-btn {
    font-size: 1rem;
  }
}

Finally, add the following JavaScript code to your script.js file to add functionality for creating random color cards with a hex color value and copying them with a single click.

const container = document.querySelector(".container");
const refreshBtn = document.querySelector(".refresh-btn");

const maxPaletteBoxes = 32;

const generatePalette = () => {
    container.innerHTML = ""; // clearing the container
    for (let i = 0; i < maxPaletteBoxes; i++) {
        // generating a random hex color code
        let randomHex = Math.floor(Math.random() * 0xffffff).toString(16);
        randomHex = `#${randomHex.padStart(6, "0")}`;
        
        // creating a new 'li' element and inserting it to the container
        const color = document.createElement("li");
        color.classList.add("color");
        color.innerHTML = `<div class="rect-box" style="background: ${randomHex}"></div>
                           <span class="hex-value">${randomHex}</span>`;
        // adding click event to current li element to copy the color
        color.addEventListener("click", () => copyColor(color, randomHex));
        container.appendChild(color);
    }
}
generatePalette();

const copyColor = (elem, hexVal) => {
    const colorElement = elem.querySelector(".hex-value");
    // Copying the hex value, updating the text to copied, 
    // and changing text back to original hex value after 1 second
    navigator.clipboard.writeText(hexVal).then(() => {
        colorElement.innerText = "Copied";
        setTimeout(() => colorElement.innerText = hexVal, 1000);
    }).catch(() => alert("Failed to copy the color code!")); // showing alert if color can't be copied
}

refreshBtn.addEventListener("click", generatePalette);

This code will generate 32 random color cards every time the button is clicked. However, you can change the “maxPaletteBoxes” value to increase or decrease the number of cards generated. To understand the code more deeply, read the comments in the code and experiment with it.

Conclusion and Final Words

By following the steps in this blog post, you have successfully created a random color palette generator using HTML, CSS, and JavaScript. Now it’s up to you to experiment with the code and make it more useful.

If you encounter any problems or your code is not working as expected, you can download the source code files of this Color Generator 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/color-palette-generator-html-css-javascript/feed/ 1