JavaScript Project – 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. Wed, 17 May 2023 07:09:56 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 Text to Speech Converter in HTML CSS & JavaScript https://www.codingnepalweb.com/text-speech-converter-html-css-javascript/ https://www.codingnepalweb.com/text-speech-converter-html-css-javascript/#respond Mon, 24 Apr 2023 21:11:22 +0000 https://www.codingnepalweb.com/?p=4109 Text to Speech Converter in HTML CSS & JavaScript

Creating a project that converts any text into speech could be an interesting and skill-pushing project while learning HTML CSS & JavaScript

Today in this blog you will learn to build a Text-to-Speech Converter using HTML CSS & JavaScript. This converter will convert any text that will be typed in the input field. Recently I have provided a blog on how can we build a Calculator in HTML CSS & JavaScript, I believe that project will be also beneficial for you.

Tutorial of Text to Speech Converter in HTML CSS & JS

As you have seen in this video tutorial of Text to speech converters. This converts any text into speech. If you want to add a voice option and accent in this Text to Speech Converter then you can visit the link also I have created a blog on language translator.

I would highly recommend you to watch the given video tutorial of Text to Speech Converter which helps you to create this project easily step by step. Also, I have tried to explain every code by doing comments on it.

Steps for Creating a Text-to-Speech Converter in JavaScript

To create a Text-to-Speech Converter 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

Once you create these files, paste the given codes into the specified files. If you don’t want to do these then scroll down and download all the source code files of the Calculator, by clicking on the given download button.

First, paste the following codes into your index.html file.

<!DOCTYPE html>
<!-- Coding By CodingNepal - codingnepalweb.com -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Text to Speech Converter</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <header>Text to Speech Converter</header>
      <textarea placeholder="Enter text"></textarea>
      <button>Convert to Speech</button>
    </div>

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

Second, paste the following codes into your style.css file.

/* Import Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #87a5f8;
}
.container {
  position: relative;
  max-width: 350px;
  width: 100%;
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
header {
  font-size: 18px;
  color: #333;
  font-weight: 500;
  text-align: center;
}
textarea {
  width: 100%;
  height: 180px;
  border-radius: 8px;
  margin: 20px 0;
  padding: 10px 15px;
  resize: none;
  outline: none;
  border: 1px solid #aaa;
}
button {
  width: 100%;
  padding: 14px 0;
  border: none;
  border-radius: 8px;
  color: #fff;
  background: #6e93f7;
  cursor: pointer;
  transition: all 0.3s ease;
}
button:hover {
  background: #4070f4;
}

Third, paste the following codes into your script.js file.

const textarea = document.querySelector("textarea");
const button = document.querySelector("button");
let isSpeaking = true;

const textToSpeech = () => {
  const synth = window.speechSynthesis;
  const text = textarea.value;

  if (!synth.speaking && text) {
    const utternace = new SpeechSynthesisUtterance(text);
    synth.speak(utternace);
  }

  if (text.length > 50) {
    if (synth.speaking && isSpeaking) {
      button.innerText = "Pause";
      synth.resume();
      isSpeaking = false;
    } else {
      button.innerText = "Resume";
      synth.pause();
      isSpeaking = true;
    }
  } else {
    isSpeaking = false;
    button.innerText = "Speaking";
  }

  setInterval(() => {
    if (!synth.speaking && !isSpeaking) {
      isSpeaking = true;
      button.innerText = "Convert to Speech";
    }
  });
};

button.addEventListener("click", textToSpeech);

If you face any difficulties while creating your Text to Speech Converter or your code is not working as expected, you can download the source code files for this Text to Speech Converter 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/text-speech-converter-html-css-javascript/feed/ 0
Make Calculator in HTML CSS & JavaScript https://www.codingnepalweb.com/calculator-html-css-javascript/ https://www.codingnepalweb.com/calculator-html-css-javascript/#respond Mon, 17 Apr 2023 21:11:22 +0000 https://www.codingnepalweb.com/?p=4110 Make Calculator in HTML CSS & JavaScript

Creating a calculator can be a challenging and intricate task, and it is something that many web developers aspire to accomplish during their journey in web development. However, it is possible to create a functional calculator by utilizing HTML, CSS, and JavaScript.

Today in this blog you will learn to create a Responsive Calculator in HTML CSS & JavaScript. This calculator will do every calculation like division, multiplication, addition, subtraction, and many more. Recently I created a Website with Login & Signup Form I believe you will also help to enhance your web development skills.

Video Tutorial of Calculator in HTML CSS & JavaScript

 

As you saw in the video tutorial on the Calculator. This calculator did all the mathematical equations also it has some validation features like the operator buttons did not work until you type numbers.

I would highly recommend you watch the full video tutorial of this calculator. In the video tutorial, I tried to make you understand every line of code by commenting.

Steps for Creating a Calculator in HTML CSS & JavaScript

To create a working calculator 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

Once you create these files, paste the given codes into the specified files. If you don’t want to do these then scroll down and download all the source code files of the Calculator, by clicking on the given download button.

First, paste the following codes into your index.html file.

<!DOCTYPE html>
<!-- Coding By CodingNepal - codingnepalweb.com -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Calculator in HTML CSS & JavaScript</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <input type="text" class="display" />

      <div class="buttons">
        <button class="operator" data-value="AC">AC</button>
        <button class="operator" data-value="DEL">DEL</button>
        <button class="operator" data-value="%">%</button>
        <button class="operator" data-value="/">/</button>

        <button data-value="7">7</button>
        <button data-value="8">8</button>
        <button data-value="9">9</button>
        <button class="operator" data-value="*">*</button>

        <button data-value="4">4</button>
        <button data-value="5">5</button>
        <button data-value="6">6</button>
        <button class="operator" data-value="-">-</button>

        <button data-value="1">1</button>
        <button data-value="2">2</button>
        <button data-value="3">3</button>
        <button class="operator" data-value="+">+</button>

        <button data-value="0">0</button>
        <button data-value="00">00</button>
        <button data-value=".">.</button>
        <button class="operator" data-value="=">=</button>
      </div>
    </div>

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

Second, paste the following codes into your style.css file.

/* Import Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e0e3eb;
}
.container {
  position: relative;
  max-width: 300px;
  width: 100%;
  border-radius: 12px;
  padding: 10px 20px 20px;
  background: #fff;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);
}
.display {
  height: 80px;
  width: 100%;
  outline: none;
  border: none;
  text-align: right;
  margin-bottom: 10px;
  font-size: 25px;
  color: #000e1a;
  pointer-events: none;
}
.buttons {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(4, 1fr);
}
.buttons button {
  padding: 10px;
  border-radius: 6px;
  border: none;
  font-size: 20px;
  cursor: pointer;
  background-color: #eee;
}
.buttons button:active {
  transform: scale(0.99);
}
.operator {
  color: #2f9fff;
}

Third, paste the following codes into your script.js file.

const display = document.querySelector(".display");
const buttons = document.querySelectorAll("button");
const specialChars = ["%", "*", "/", "-", "+", "="];
let output = "";

//Define function to calculate based on button clicked.
const calculate = (btnValue) => {
  display.focus();
  if (btnValue === "=" && output !== "") {
    //If output has '%', replace with '/100' before evaluating.
    output = eval(output.replace("%", "/100"));
  } else if (btnValue === "AC") {
    output = "";
  } else if (btnValue === "DEL") {
    //If DEL button is clicked, remove the last character from the output.
    output = output.toString().slice(0, -1);
  } else {
    //If output is empty and button is specialChars then return
    if (output === "" && specialChars.includes(btnValue)) return;
    output += btnValue;
  }
  display.value = output;
};

//Add event listener to buttons, call calculate() on click.
buttons.forEach((button) => {
  //Button click listener calls calculate() with dataset value as argument.
  button.addEventListener("click", (e) => calculate(e.target.dataset.value));
});

That’s all, now you’ve successfully created a Calculator. If you face any difficulties while creating your calculator or your code is not working as expected, you can download the source code files for this calculator 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/calculator-html-css-javascript/feed/ 0
Create Functional Image Gallery in HTML CSS & JavaScript https://www.codingnepalweb.com/functional-image-gallery-html-css-javascript/ https://www.codingnepalweb.com/functional-image-gallery-html-css-javascript/#comments Tue, 04 Apr 2023 17:42:09 +0000 https://www.codingnepalweb.com/?p=4077 Create Functional Image Gallery in HTML CSS & JavaScript

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

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

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

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

Video Tutorial of Functional Image Gallery in JavaScript

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

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

Steps For Creating Image Gallery in JavaScript

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

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

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

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

  </body>
</html>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Conclusion and Final Words

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

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

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

 

]]>
https://www.codingnepalweb.com/functional-image-gallery-html-css-javascript/feed/ 1
How to create Pagination in HTML CSS & JavaScript https://www.codingnepalweb.com/how-to-create-pagination-in-html-css-javascript/ https://www.codingnepalweb.com/how-to-create-pagination-in-html-css-javascript/#respond Mon, 03 Apr 2023 09:06:40 +0000 https://www.codingnepalweb.com/?p=4112 How to create Pagination in HTML CSS & JavaScript

You may have seen at the end of the website that there is a pagination section that is used to jump to the next webpage of the website. Did you know we can create that pagination using HTML CSS & JavaScript?

Today in this blog, you will learn how to create pagination using HTML CSS, and JavaScript. In addition to the pagination, there will be button validation and animations included as well. If you want to enhance your coding skills then I would like to recommend my latest blog on Rock Paper & Scissors Game.

Video Tutorial of Pagination in HTML CSS & JavaScript

 
As you saw in the video tutorial how can we create an Animated Pagination in HTML CSS & JavaScript step by step? We were able to move any number by clicking on the number or by using the arrow button.

I would highly recommend you watch the video tutorial to create this pagination because it will be easier for you to build this pagination step by step. Also, I have tried to explain every code with the comments.

Steps for creating Pagination in HTML CSS & JavaScript

To create a Pagination 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

Once you create these files, paste the given codes into the specified files. If you don’t want to do these then scroll down and download all the source code files of the Rock-Paper-Scissors Game, by clicking on the given download button.

First, paste the following codes into your index.html file.

<!DOCTYPE html>
<!-- Coding By CodingNepal - codingnepalweb.com -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>Pagination in HTML CSS & JavaScript</title>
    <link rel="stylesheet" href="style.css" />
    <!-- Fontawesome CDN Link -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" />
  </head>
  <body>
    <div class="container">
      <button class="button" id="startBtn" disabled>
        <i class="fa-solid fa-angles-left"></i>
      </button>
      <button class="button prevNext" id="prev" disabled>
        <i class="fa-solid fa-angle-left"></i>
      </button>

      <div class="links">
        <a href="#" class="link active">1</a>
        <a href="#" class="link">2</a>
        <a href="#" class="link">3</a>
        <a href="#" class="link">4</a>
        <a href="#" class="link">5</a>
      </div>

      <button class="button prevNext" id="next">
        <i class="fa-solid fa-angle-right"></i>
      </button>
      <button class="button" id="endBtn">
        <i class="fa-solid fa-angles-right"></i>
      </button>
    </div>

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

Second, paste the following codes into your style.css file.

/* Import Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  height: 100vh;
  background: #4070f4;
}
body,
.container,
.button,
.links,
.link {
  display: flex;
  align-items: center;
  justify-content: center;
}
.container {
  padding: 20px;
  border-radius: 8px;
  column-gap: 12px;
  background: #fff;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
.button {
  border: none;
}
.button i {
  pointer-events: none;
}
.button:disabled {
  color: #b3b3b3;
  pointer-events: none;
}
.button,
.link {
  height: 45px;
  width: 45px;
  font-size: 20px;
  color: #666666;
  background-color: #f2f2f2;
  border-radius: 6px;
  cursor: pointer;
}
.links {
  column-gap: 12px;
}
.link {
  font-weight: 500;
  text-decoration: none;
}
.button:hover,
.link:hover {
  color: #fff;
  background: #4070f4;
}
.link.active {
  color: #fff;
  background: #4070f4;
}

Third, paste the following codes into your script.js file.

// Selecting DOM elements
const startBtn = document.querySelector("#startBtn"),
  endBtn = document.querySelector("#endBtn"),
  prevNext = document.querySelectorAll(".prevNext"),
  numbers = document.querySelectorAll(".link");

// Setting an initial step
let currentStep = 0;

// Function to update the button states
const updateBtn = () => {
  // If we are at the last step
  if (currentStep === 4) {
    endBtn.disabled = true;
    prevNext[1].disabled = true;
  } else if (currentStep === 0) {
    // If we are at the first step
    startBtn.disabled = true;
    prevNext[0].disabled = true;
  } else {
    endBtn.disabled = false;
    prevNext[1].disabled = false;
    startBtn.disabled = false;
    prevNext[0].disabled = false;
  }
};

// Add event listeners to the number links
numbers.forEach((number, numIndex) => {
  number.addEventListener("click", (e) => {
    e.preventDefault();
    // Set the current step to the clicked number link
    currentStep = numIndex;
    // Remove the "active" class from the previously active number link
    document.querySelector(".active").classList.remove("active");
    // Add the "active" class to the clicked number link
    number.classList.add("active");
    updateBtn(); // Update the button states
  });
});

// Add event listeners to the "Previous" and "Next" buttons
prevNext.forEach((button) => {
  button.addEventListener("click", (e) => {
    // Increment or decrement the current step based on the button clicked
    currentStep += e.target.id === "next" ? 1 : -1;
    numbers.forEach((number, numIndex) => {
      // Toggle the "active" class on the number links based on the current step
      number.classList.toggle("active", numIndex === currentStep);
      updateBtn(); // Update the button states
    });
  });
});

// Add event listener to the "Start" button
startBtn.addEventListener("click", () => {
  // Remove the "active" class from the previously active number link
  document.querySelector(".active").classList.remove("active");
  // Add the "active" class to the first number link
  numbers[0].classList.add("active");
  currentStep = 0;
  updateBtn(); // Update the button states
  endBtn.disabled = false;
  prevNext[1].disabled = false;
});

// Add event listener to the "End" button
endBtn.addEventListener("click", () => {
  // Remove the "active" class from the previously active number link
  document.querySelector(".active").classList.remove("active");
  // Add the "active" class to the last number link
  numbers[4].classList.add("active");
  currentStep = 4;
  updateBtn(); // Update the button states
  startBtn.disabled = false;
  prevNext[0].disabled = false;
});

That’s all, now you’ve successfully created a project on Pagination. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It’s free and a zip file containing the project folder with source code files will be downloaded.

 

]]>
https://www.codingnepalweb.com/how-to-create-pagination-in-html-css-javascript/feed/ 0
Build Analog Clock in HTML CSS & JavaScript https://www.codingnepalweb.com/build-clock-html-css-javascript/ https://www.codingnepalweb.com/build-clock-html-css-javascript/#respond Sat, 11 Mar 2023 21:11:21 +0000 https://www.codingnepalweb.com/?p=4115 Build Analog Clock in HTML CSS & JavaScript

Creating an analog clock using HTML, CSS, and JavaScript is an excellent way to improve your coding skills and gain valuable experience in web development.

Today in this blog, you will discover the process of building an Analog Clock in HTML, CSS, and JavaScript. Additionally, I will provide guidance on how to integrate dark and light mode options into the clock’s functionality. An intriguing aspect of the dark and light modes is that the selected theme will persist even if the page is refreshed or the file is reopened.

The analog clock that we will construct will have a user interface design that is identical to the image provided. Furthermore, all of the HTML, CSS, and JavaScript code that I will utilize to construct this clock will be made accessible to you.

Video tutorial of Analog Clock in HTML CSS & JavaScript

In this video tutorial, I have endeavored to make the code easy to comprehend for everyone by keeping it neat and straightforward. Furthermore, I have provided explanations for all of the code using comments.

I strongly suggest that you watch the video tutorial to build this Analog Clock using HTML, CSS, and JavaScript. However, if you prefer to skip the video tutorial, you may proceed with reading the blog.

Steps for creating Analog Clock

To create Analog Clock, 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

Once you create these files, paste the given codes into the specified files. If you don’t want to do these then scroll down and download the Analog Clock by clicking on the given download button.

First, paste the following codes into your index.html file.

<!DOCTYPE html>
<!-- Coding By CodingNepal - codingnepalweb.com -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Analog Clock JavaScript</title>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="container">
      <div class="clock">
        <label style="--i: 1"><span>1</span></label>
        <label style="--i: 2"><span>2</span></label>
        <label style="--i: 3"><span>3</span></label>
        <label style="--i: 4"><span>4</span></label>
        <label style="--i: 5"><span>5</span></label>
        <label style="--i: 6"><span>6</span></label>
        <label style="--i: 7"><span>7</span></label>
        <label style="--i: 8"><span>8</span></label>
        <label style="--i: 9"><span>9</span></label>
        <label style="--i: 10"><span>10</span></label>
        <label style="--i: 11"><span>11</span></label>
        <label style="--i: 12"><span>12</span></label>

        <div class="indicator">
          <span class="hand hour"></span>
          <span class="hand minute"></span>
          <span class="hand second"></span>
        </div>
      </div>

      <div class="mode-switch">Dark Mode</div>
    </div>
  </body>
</html>

Second, paste the following codes into your style.css file.

/* Import Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
:root {
  --primary-color: #f6f7fb;
  --white-color: #fff;
  --black-color: #18191a;
  --red-color: #e74c3c;
}
body {
  display: flex;
  min-height: 100vh;
  align-items: center;
  justify-content: center;
  background: var(--primary-color);
}
body.dark {
  --primary-color: #242526;
  --white-color: #18191a;
  --black-color: #fff;
  --red-color: #e74c3c;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 60px;
}
.container .clock {
  display: flex;
  height: 400px;
  width: 400px;
  border-radius: 50%;
  align-items: center;
  justify-content: center;
  background: var(--white-color);
  box-shadow: 0 15px 25px rgba(0, 0, 0, 0.1), 0 25px 45px rgba(0, 0, 0, 0.1);
  position: relative;
}
.clock label {
  position: absolute;
  inset: 20px;
  text-align: center;
  transform: rotate(calc(var(--i) * (360deg / 12)));
}
.clock label span {
  display: inline-block;
  font-size: 30px;
  font-weight: 600;
  color: var(--black-color);
  transform: rotate(calc(var(--i) * (-360deg / 12)));
}
.container .indicator {
  position: absolute;
  height: 10px;
  width: 10px;
  display: flex;
  justify-content: center;
}
.indicator::before {
  content: "";
  position: absolute;
  height: 100%;
  width: 100%;
  border-radius: 50%;
  z-index: 100;
  background: var(--black-color);
  border: 4px solid var(--red-color);
}
.indicator .hand {
  position: absolute;
  height: 130px;
  width: 4px;
  bottom: 0;
  border-radius: 25px;
  transform-origin: bottom;
  background: var(--red-color);
}
.hand.minute {
  height: 120px;
  width: 5px;
  background: var(--black-color);
}
.hand.hour {
  height: 100px;
  width: 8px;
  background: var(--black-color);
}
.mode-switch {
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 22px;
  font-weight: 400;
  display: inline-block;
  color: var(--white-color);
  background: var(--black-color);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

Third, paste the following codes into your script.js file.

// Get references to DOM elements
const body = document.querySelector("body"),
  hourHand = document.querySelector(".hour"),
  minuteHand = document.querySelector(".minute"),
  secondHand = document.querySelector(".second"),
  modeSwitch = document.querySelector(".mode-switch");

// check if the mode is already set to "Dark Mode" in localStorage
if (localStorage.getItem("mode") === "Dark Mode") {
  // add "dark" class to body and set modeSwitch text to "Light Mode"
  body.classList.add("dark");
  modeSwitch.textContent = "Light Mode";
}

// add a click event listener to modeSwitch
modeSwitch.addEventListener("click", () => {
  // toggle the "dark" class on the body element
  body.classList.toggle("dark");
  // check if the "dark" class is currently present on the body element
  const isDarkMode = body.classList.contains("dark");
  // set modeSwitch text based on "dark" class presence
  modeSwitch.textContent = isDarkMode ? "Light Mode" : "Dark Mode";
  // set localStorage "mode" item based on "dark" class presence
  localStorage.setItem("mode", isDarkMode ? "Dark Mode" : "Light Mode");
});

const updateTime = () => {
  // Get current time and calculate degrees for clock hands
  let date = new Date(),
    secToDeg = (date.getSeconds() / 60) * 360,
    minToDeg = (date.getMinutes() / 60) * 360,
    hrToDeg = (date.getHours() / 12) * 360;

  // Rotate the clock hands to the appropriate degree based on the current time
  secondHand.style.transform = `rotate(${secToDeg}deg)`;
  minuteHand.style.transform = `rotate(${minToDeg}deg)`;
  hourHand.style.transform = `rotate(${hrToDeg}deg)`;
};

// call updateTime to set clock hands every second
setInterval(updateTime, 1000);

//call updateTime function on page load
updateTime();

That’s all, now you’ve successfully created a project on Analog Clock. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It’s free and a zip file containing the project folder with source code files will be downloaded.

 

]]>
https://www.codingnepalweb.com/build-clock-html-css-javascript/feed/ 0
Drag and Drop Sortable List using HTML CSS & JavaScript https://www.codingnepalweb.com/drag-and-drop-sortable-list-html-javascript/ https://www.codingnepalweb.com/drag-and-drop-sortable-list-html-javascript/#respond Sat, 04 Mar 2023 13:14:37 +0000 https://www.codingnepalweb.com/?p=4046 Drag and Drop Sortable List in HTML CSs & JavaScript Draggable List in JavaScript

Drag and drop sortable lists are a widely used UI element allowing users to reorder items by dragging and dropping them on a desired position. This functionality can be found in many web applications, like task managers and e-commerce websites.

In this blog post, you’ll learn how to create Drag and Drop Sortable Lists using HTML, CSS, and JavaScript. Remember, we’ll not use any external JavaScript library to create this sortable list, so you’ll get a deeper understanding of DOM manipulation, event handling, array manipulation, and more.

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

Video Tutorial of Drag and Drop Sortable List JavaScript

 
If you prefer visual learning, then the video tutorial is a great resource for you. Each line of code is explained in detail with comments to help you understand what’s happening at each step.

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

Steps For Creating Drag & Drop Sortable List JavaScript

To create a drag and drop sortable list 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
  5. Download the images folder from Google Drive and put this folder inside the project folder.

To start, add the following HTML codes to your index.html file to create the draggable, sortable list items: I’ve added six list items, but you can add as many as you want.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Drag and Drop Sortable List | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css">
    <script src="script.js" defer></script>
  </head>
  <body>
    <ul class="sortable-list">
      <li class="item" draggable="true">
        <div class="details">
          <img src="images/img-1.jpg">
          <span>Kristina Zasiadko</span>
        </div>
        <i class="uil uil-draggabledots"></i>
      </li>
      <li class="item" draggable="true">
        <div class="details">
          <img src="images/img-2.jpg">
          <span>Gabriel Wilson</span>
        </div>
        <i class="uil uil-draggabledots"></i>
      </li>
      <li class="item" draggable="true">
        <div class="details">
          <img src="images/img-3.jpg">
          <span>Ronelle Cesicon</span>
        </div>
        <i class="uil uil-draggabledots"></i>
      </li>
      <li class="item" draggable="true">
        <div class="details">
          <img src="images/img-4.jpg">
          <span>James Khosravi</span>
        </div>
        <i class="uil uil-draggabledots"></i>
      </li>
      <li class="item" draggable="true">
        <div class="details">
          <img src="images/img-5.jpg">
          <span>Annika Hayden</span>
        </div>
        <i class="uil uil-draggabledots"></i>
      </li>
      <li class="item" draggable="true">
        <div class="details">
          <img src="images/img-6.jpg">
          <span>Donald Horton</span>
        </div>
        <i class="uil uil-draggabledots"></i>
      </li>
    </ul>

  </body>
</html>

Next, add the following CSS codes to your style.css file to style the list items and make it easier to use. If you wish, feel free to 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 {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #595DB8;
}
.sortable-list {
  width: 425px;
  padding: 25px;
  background: #fff;
  border-radius: 7px;
  padding: 30px 25px 20px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}
.sortable-list .item {
  list-style: none;
  display: flex;
  cursor: move;
  background: #fff;
  align-items: center;
  border-radius: 5px;
  padding: 10px 13px;
  margin-bottom: 11px;
  /* box-shadow: 0 2px 4px rgba(0,0,0,0.06); */
  border: 1px solid #ccc;
  justify-content: space-between;
}
.item .details {
  display: flex;
  align-items: center;
}
.item .details img {
  height: 43px;
  width: 43px;
  pointer-events: none;
  margin-right: 12px;
  object-fit: cover;
  border-radius: 50%;
}
.item .details span {
  font-size: 1.13rem;
}
.item i {
  color: #474747;
  font-size: 1.13rem;
}
.item.dragging {
  opacity: 0.6;
}
.item.dragging :where(.details, i) {
  opacity: 0;
}

Finally, add the following JavaScript code to your script.js file to add drag and drop functionality to the sortable list: 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 sortableList = document.querySelector(".sortable-list");
const items = sortableList.querySelectorAll(".item");

items.forEach(item => {
    item.addEventListener("dragstart", () => {
        // Adding dragging class to item after a delay
        setTimeout(() => item.classList.add("dragging"), 0);
    });
    // Removing dragging class from item on dragend event
    item.addEventListener("dragend", () => item.classList.remove("dragging"));
});

const initSortableList = (e) => {
    e.preventDefault();
    const draggingItem = document.querySelector(".dragging");
    // Getting all items except currently dragging and making array of them
    let siblings = [...sortableList.querySelectorAll(".item:not(.dragging)")];

    // Finding the sibling after which the dragging item should be placed
    let nextSibling = siblings.find(sibling => {
        return e.clientY <= sibling.offsetTop + sibling.offsetHeight / 2;
    });

    // Inserting the dragging item before the found sibling
    sortableList.insertBefore(draggingItem, nextSibling);
}

sortableList.addEventListener("dragover", initSortableList);
sortableList.addEventListener("dragenter", e => e.preventDefault());

It’s important to note that the script code for creating the drag and drop sortable list will only work on devices with a mouse. If you want to enable touch functionality, you’ll need to add touch event listeners as well.

If you’re not familiar with touch event listeners and want to learn more about how to use them, you can check out this blog post on creating a draggable image slider using touch event listeners in JavaScript. It will help you understand how to add dragging functionality to touch devices.

Conclusion and Final Words

By following the steps in this blog post, you have successfully created Drag and Drop Sortable List using HTML, CSS, and JavaScript. Now it’s up to you to modify the code to suit your needs and make it more touch-friendly.

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

 

]]>
https://www.codingnepalweb.com/drag-and-drop-sortable-list-html-javascript/feed/ 0
OTP Verification Form in HTML CSS & JavaScript https://www.codingnepalweb.com/otp-verification-form-html-css-javascript/ https://www.codingnepalweb.com/otp-verification-form-html-css-javascript/#respond Tue, 20 Dec 2022 21:11:21 +0000 https://www.codingnepalweb.com/?p=4128 OTP Verification Form in HTML CSS & JavaScript

If you are seeking a form that is designed for verifying one-time passwords and want to learn how to create it in HTML CSS & JavaScript then this blog could meet you demands.

In this blog you will learn to How to create OTP Verification Form in HTML CSS & JavaScript. You will learn how to structure the form and input fields using HTML, how to style the form and input fields using CSS, and how to handle the form submission and verify the OTP using JavaScript. In the recent blog I have created Star Rating System I hove that will also help to enhance you coding skills.

An OTP (one-time password) form is a type of form used to verify the identity of a user by requiring them to enter a unique code that is sent to their email or phone number. OTPs are commonly used as a security measure to prevent unauthorized access to sensitive information or accounts.

Have a look on the given image of our OTP Verification Form. As you can see in this form we wil have one icon at top, text, five input fields and a button. To watch the demo of this project and create this OTP Form step by step you can watch the given video tutorial.

Video Tutorial | OTP Form in HTML CSS & JavaScript

In the video tutorial on creating an OTP verification form, you may have noticed that the form initially appeared with all input fields and the submit button disabled, except for the first input field, which was already focused. As the user entered numbers into the first field, the focus automatically moved to the next field, and so on until all fields were filled.

Once all fields were completed, the submit button became active and could be clicked to submit the form. This process helps to ensure that the user correctly enters the OTP and allows for a smooth and efficient user experience.

I hope that you are now able to create an OTP verification form using HTML, CSS, and JavaScript. If you are still experiencing any challenges, I have provided the source code that I used to create this form for your reference.

You May Like This:

OTP Verification Form in HTML CSS & JS [Source Code]

To create OTP Verification Form in HTML CSS & 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

Once you create these files, paste the given codes into the specified files. If you don’t want to do these then scroll down and download the OTP Verification Form in HTML CSS & JavaScript by clicking on the given download button.

First, paste the following codes into your index.html file.

<!DOCTYPE html>
<!-- Coding By CodingNepal - codingnepalweb.com -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>OTP Verification Form</title>
    <link rel="stylesheet" href="style.css" />
    <!-- Boxicons CSS -->
    <link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet" />
   <script src="script.js" defer></script>
  </head>
  <body>
    <div class="container">
      <header>
        <i class="bx bxs-check-shield"></i>
      </header>
      <h4>Enter OTP Code</h4>
      <form action="#">
        <div class="input-field">
          <input type="number" />
          <input type="number" disabled />
          <input type="number" disabled />
          <input type="number" disabled />
        </div>
        <button>Verify OTP</button>
      </form>
    </div>
  </body>
</html>

Second, paste the following codes into your style.css file.

/* Import Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #4070f4;
}
:where(.container, form, .input-field, header) {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.container {
  background: #fff;
  padding: 30px 65px;
  border-radius: 12px;
  row-gap: 20px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
.container header {
  height: 65px;
  width: 65px;
  background: #4070f4;
  color: #fff;
  font-size: 2.5rem;
  border-radius: 50%;
}
.container h4 {
  font-size: 1.25rem;
  color: #333;
  font-weight: 500;
}
form .input-field {
  flex-direction: row;
  column-gap: 10px;
}
.input-field input {
  height: 45px;
  width: 42px;
  border-radius: 6px;
  outline: none;
  font-size: 1.125rem;
  text-align: center;
  border: 1px solid #ddd;
}
.input-field input:focus {
  box-shadow: 0 1px 0 rgba(0, 0, 0, 0.1);
}
.input-field input::-webkit-inner-spin-button,
.input-field input::-webkit-outer-spin-button {
  display: none;
}
form button {
  margin-top: 25px;
  width: 100%;
  color: #fff;
  font-size: 1rem;
  border: none;
  padding: 9px 0;
  cursor: pointer;
  border-radius: 6px;
  pointer-events: none;
  background: #6e93f7;
  transition: all 0.2s ease;
}
form button.active {
  background: #4070f4;
  pointer-events: auto;
}
form button:hover {
  background: #0e4bf1;
}

Third, paste the following codes into your script.js file.

 const inputs = document.querySelectorAll("input"),
  button = document.querySelector("button");

// iterate over all inputs
inputs.forEach((input, index1) => {
  input.addEventListener("keyup", (e) => {
    // This code gets the current input element and stores it in the currentInput variable
    // This code gets the next sibling element of the current input element and stores it in the nextInput variable
    // This code gets the previous sibling element of the current input element and stores it in the prevInput variable
    const currentInput = input,
      nextInput = input.nextElementSibling,
      prevInput = input.previousElementSibling;

    // if the value has more than one character then clear it
    if (currentInput.value.length > 1) {
      currentInput.value = "";
      return;
    }
    // if the next input is disabled and the current value is not empty
    //  enable the next input and focus on it
    if (nextInput && nextInput.hasAttribute("disabled") && currentInput.value !== "") {
      nextInput.removeAttribute("disabled");
      nextInput.focus();
    }

    // if the backspace key is pressed
    if (e.key === "Backspace") {
      // iterate over all inputs again
      inputs.forEach((input, index2) => {
        // if the index1 of the current input is less than or equal to the index2 of the input in the outer loop
        // and the previous element exists, set the disabled attribute on the input and focus on the previous element
        if (index1 <= index2 && prevInput) {
          input.setAttribute("disabled", true);
          input.value = "";
          prevInput.focus();
        }
      });
    }
    //if the fourth input( which index number is 3) is not empty and has not disable attribute then
    //add active class if not then remove the active class.
    if (!inputs[3].disabled && inputs[3].value !== "") {
      button.classList.add("active");
      return;
    }
    button.classList.remove("active");
  });
});

//focus the first input which index is 0 on window load
window.addEventListener("load", () => inputs[0].focus());

If you face any difficulties while creating your OTP Verification Form or your code is not working as expected, you can download the source code files for this OTP Verification Form  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/otp-verification-form-html-css-javascript/feed/ 0
Star Rating in HTML CSS & JavaScript https://www.codingnepalweb.com/star-rating-html-css-javascript-2/ https://www.codingnepalweb.com/star-rating-html-css-javascript-2/#respond Fri, 16 Dec 2022 21:11:21 +0000 https://www.codingnepalweb.com/?p=4129 Star Rating in HTML CSS & JavaScript

If you are looking for the Star Rating System and want to create it in HTML CSS & JavaScript then this blog could meet your demand.

In this blog, you will learn how to create a star rating system using HTML, CSS, and JavaScript. The instructions included in the post can help you build a system that allows users to rate something by selecting a certain number of stars. Recently I have provided a blog on Creating Dark & Light Mode I hope that will also help to enhance your HTML and CSS skills.

Typically, a star rating system consists of a set of stars that are displayed on a website or application, and users can select a certain number of stars to represent their rating. It is widely used to allow users to provide feedback or to rate items such as products, movies, or restaurants.

Have a look at the given image of our star rating system. Basically, in this star rating system, you will get changing the color of the stars when the user clicks on them and store the user’s rating.

If you would like to watch the demo of this Star Rating System and want to create it step by step in HTML CSS & JavaScript, then you can watch the video tutorial which is given below.

 Video Tutorial | Star Rating in HTML CSS & JavaScript

In the video tutorial, you saw that there were initially five light-colored stars displayed on the screen. When I clicked on one of the stars, it changed to a yellow color, and the stars that came before it also changed to yellow. This demonstrates how the star rating system can be made dynamic by using JavaScript to update the appearance of the stars in real time based on user input.

I hope that the information and examples provided in this discussion have helped you understand how to create a star rating system using HTML, CSS, and JavaScript. If you are having trouble building the system on your own, and don’t want to watch the video tutorial then use the source code provided below to help you.

You May Like This:

Star Rating in HTML CSS & JavaScript [Source Code]

To create Star Rating in HTML CSS & 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

Once you create these files, paste the given codes into the specified files. If you don’t want to do these then scroll down and download the Star Rating in HTML CSS & JavaScript by clicking on the given download button.

First, paste the following codes into your index.html file.

<!DOCTYPE html>
<!-- Coding By CodingNepal - codingnepalweb.com -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-pUA-Compatible" content="ie=edge" />
    <title>Star Rating in HTML CSS & JavaScript</title>
    <link rel="stylesheet" href="style.css" />
    <!-- Fontawesome CDN Link -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" />
   <script src="script.js" defer></script>
  </head>
  <body>
    <div class="rating-box">
      <header>How was your experience?</header>
      <div class="stars">
        <i class="fa-solid fa-star"></i>
        <i class="fa-solid fa-star"></i>
        <i class="fa-solid fa-star"></i>
        <i class="fa-solid fa-star"></i>
        <i class="fa-solid fa-star"></i>
      </div>
    </div>
  </body>
</html>

Second, paste the following codes into your style.css file.

/* Import Google font - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(45deg, #ffd195, #ffb283);
}
.rating-box {
  position: relative;
  background: #fff;
  padding: 25px 50px 35px;
  border-radius: 25px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);
}
.rating-box header {
  font-size: 22px;
  color: #dadada;
  font-weight: 500;
  margin-bottom: 20px;
  text-align: center;
}
.rating-box .stars {
  display: flex;
  align-items: center;
  gap: 25px;
}
.stars i {
  color: #e6e6e6;
  font-size: 35px;
  cursor: pointer;
  transition: color 0.2s ease;
}
.stars i.active {
  color: #ff9c1a;
}

Third, paste the following codes into your script.js file.

 // Select all elements with the "i" tag and store them in a NodeList called "stars"
const stars = document.querySelectorAll(".stars i");

// Loop through the "stars" NodeList
stars.forEach((star, index1) => {
  // Add an event listener that runs a function when the "click" event is triggered
  star.addEventListener("click", () => {
    // Loop through the "stars" NodeList Again
    stars.forEach((star, index2) => {
      // Add the "active" class to the clicked star and any stars with a lower index
      // and remove the "active" class from any stars with a higher index
      index1 >= index2 ? star.classList.add("active") : star.classList.remove("active");
    });
  });
});
If you face any difficulties while creating your Star Rating System or your code is not working as expected, you can download the source code files for this Star Rating System 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/star-rating-html-css-javascript-2/feed/ 0
Create Popup Cookies Consent Box in HTML CSS & JavaScript https://www.codingnepalweb.com/popup-cookies-consent-box-html-css-javascript/ https://www.codingnepalweb.com/popup-cookies-consent-box-html-css-javascript/#respond Tue, 15 Nov 2022 21:11:20 +0000 https://www.codingnepalweb.com/?p=4146 Create Popup Cookies Consent Box in HTML CSS & JavaScript

Did you know how to set a cookie on the website with the basic HTML, CSS, and JavaScript codes and, what cookies are? If not, then this blog is written for you.

Today’s blog will teach you how to Create a Pop-Up Cookie Consent Box in HTML CSS and JavaScript with setting the cookie for some interval of time, even if you only know the basics of JavaScript, you will be able to create and set cookies. Recently I have uploaded how to Create Responsive Search Bar in HTML CSS & JavaScript I hope you will like it.

Cookies are text files that are sent to your browser by a website you visit. They assist the website in remembering information about your visit, which can both make it simpler for you to return to the site and increase its usefulness to you.

Have a look at the given image of our Cookies Consent Box. As you can see on the cookie Box, there are cookie icons and heading text at the top, and underneath that there is some informational text about cookies and accept and decline buttons. This cookies box will appear on loaded webpages, and you will be asked whether you want to accept or decline cookies.

To see the real demo of this Cookies Consent Box how it pops out, what happens when you click on the decline or accept buttons, and what time the cookies will be set. Also, by watching the given video tutorial, you will get to know how all the HTML CSS and JavaScript work behind this Popup Cookie Consent Box.

 Cookies Consent Box in HTML CSS & JavaScript | Video Tutorial

 

I have provided all the HTML CSS and JavaSCript codes that I have used to create this Cookies Consent Box. Before getting into the source code files, You have to know some important thing that I did in the video tutorial of this cookie box.

As you have seen in the video tutorial, with the wepage loaded our Cookies Consent Box appeared. When I clicked on the cookie decline button it got disappeared until the wepage got refreshed. When I clicked on the cookie accept, the cookie massage set for one month. Bascially till a month that cookies consent box will not appear, after a month our cookies will be expired and the cookie consent box will appear again.

I hope by reading the blog and watching the video tutorial you got to know  how to Create Popup Cookies Consent Box in HTML CSS & JavaScript with setting the cookie. If you are wondering to get all the source code file of this cookies consent box, it is provided below.

You May Like This:

Cookies Consent Box in HTML CSS & JavaScript [Source Code]

To create Popup Cookies Consent Box in HTML CSS & 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

Once you create these files, paste the given codes into the specified files. If you don’t want to do these then scroll down and download the Cookies Consent Box in HTML CSS & JavaScript by clicking on the given download button.

First, paste the following codes into your index.html file.

<!DOCTYPE html>
<!-- Coding By CodingNepal - codingnepalweb.com -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>Popup Cookie Consent Box</title>
    <link rel="stylesheet" href="style.css" />
    <!-- Boxicons CSS -->
    <link href="https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css" rel="stylesheet" />
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="wrapper">
      <header>
        <i class="bx bx-cookie"></i>
        <h2>Cookies Consent</h2>
      </header>

      <div class="data">
        <p>This website use cookies to help you have a superior and more relevant browsing experience on the website. <a href="#"> Read more...</a></p>
      </div>

      <div class="buttons">
        <button class="button" id="acceptBtn">Accept</button>
        <button class="button" id="declineBtn">Decline</button>
      </div>
    </div>
  </body>
</html>

Second, paste the following codes into your style.css file.

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

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  min-height: 100vh;
  background-color: #4070f4;
}
.wrapper {
  position: fixed;
  bottom: 50px;
  right: -370px;
  max-width: 345px;
  width: 100%;
  background: #fff;
  border-radius: 8px;
  padding: 15px 25px 22px;
  transition: right 0.3s ease;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
.wrapper.show {
  right: 20px;
}
.wrapper header {
  display: flex;
  align-items: center;
  column-gap: 15px;
}
header i {
  color: #4070f4;
  font-size: 32px;
}
header h2 {
  color: #4070f4;
  font-weight: 500;
}
.wrapper .data {
  margin-top: 16px;
}
.wrapper .data p {
  color: #333;
  font-size: 16px;
}
.data p a {
  color: #4070f4;
  text-decoration: none;
}
.data p a:hover {
  text-decoration: underline;
}
.wrapper .buttons {
  margin-top: 16px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.buttons .button {
  border: none;
  color: #fff;
  padding: 8px 0;
  border-radius: 4px;
  background: #4070f4;
  cursor: pointer;
  width: calc(100% / 2 - 10px);
  transition: all 0.2s ease;
}
.buttons #acceptBtn:hover {
  background-color: #034bf1;
}
#declineBtn {
  border: 2px solid #4070f4;
  background-color: #fff;
  color: #4070f4;
}
#declineBtn:hover {
  background-color: #4070f4;
  color: #fff;
}

Third, paste the following codes into your script.js file.

const cookieBox = document.querySelector(".wrapper"),
  buttons = document.querySelectorAll(".button");

const executeCodes = () => {
  //if cookie contains codinglab it will be returned and below of this code will not run
  if (document.cookie.includes("codinglab")) return;
  cookieBox.classList.add("show");

  buttons.forEach((button) => {
    button.addEventListener("click", () => {
      cookieBox.classList.remove("show");

      //if button has acceptBtn id
      if (button.id == "acceptBtn") {
        //set cookies for 1 month. 60 = 1 min, 60 = 1 hours, 24 = 1 day, 30 = 30 days
        document.cookie = "cookieBy= codinglab; max-age=" + 60 * 60 * 24 * 30;
      }
    });
  });
};

//executeCodes function will be called on webpage load
window.addEventListener("load", executeCodes);

That’s all, now you’ve successfully created a project on Popup Cookies Consent Box in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It’s free and a zip file containing the project folder with source code files will be downloaded.

 

]]>
https://www.codingnepalweb.com/popup-cookies-consent-box-html-css-javascript/feed/ 0
Build A Currency Converter App in HTML CSS & JavaScript https://www.codingnepalweb.com/currency-converter-app-in-html-javascript/ https://www.codingnepalweb.com/currency-converter-app-in-html-javascript/#comments Wed, 01 Sep 2021 14:39:24 +0000 https://www.codingnepalweb.com/?p=2245 Build A Currency Converter App in HTML CSS & JavaScript

Hey friends, today in this blog, you’ll learn how to Build A Currency Converter App in HTML CSS & JavaScript. In the earlier blog, I have shared how to Build A Weather App in JavaScript, and not it’s time to create a currency converter using pure JavaScript.

In this app (Currency Converter in JavaScript), you can enter your amount and convert your currency to a different country’s currency. You can’t leave the amount field blank or enter 0 as an amount. If you do it, then “1” will be filled automatically in the amount field.

You can also easily exchange or reverse the two countries’ currency by clicking on the exchange icon. If you didn’t understand, then you can watch a demo or video tutorial of this project (JavaScript Currency Converter).

Video Tutorial of Currency Converter in JavaScript

 
In the video, you have seen the demo video of this currency converter and how I created it using HTML CSS & JavaScript. I tried to explain the main JavaScript line by written comments. I hope you liked this project and also understood the codes.

If you liked this JavaScript Currency Converter and want to get source codes or files, then you can get it from the bottom of this page. But before you go to copy-paste codes or download source files, let’s understand the main code and concepts behind creating this project.

Codes & Concepts Behind JavaScript Currency Converter App

In the JavaScript file (country-list.js), I stored all possible country code and their currency code as an object. Then in the script.js file, first, I created an options tag and added those currency codes inside each option tag using for-in loop and inserted these tags inside the select tag.

After this, I created a function and got the user-entered amount. Then I sent a get request to an exchange rate API by passing the user selected “from” currency code. API returned an object of the all-country currency conversion rate of the user-selected “from” currency.

First, I got the user selected “to” currency conversion rate, and then I calculate it with the user-entered amount and show it in the exchange rate text. Once it’s done, for swapping the currency codes, I just reversed the “from” currency to “to” currency and then call the function. For flags, I used countryflags.io API to show the user-selected country flag.

You might like this:

Currency Converter App in JavaScript [Source Codes]

To create this project (Currency Converter in JavaScript). First, you need to create four Files: HTML, CSS & JavaScript Files. After creating these files just paste the following codes into your file. You can also download the source code files of this Currency Converter from the given download button.

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

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Currency Converter App in JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- FontAweome CDN Link for Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
  </head>
  <body>
    <div class="wrapper">
      <header>Currency Converter</header>
      <form action="#">
        <div class="amount">
          <p>Enter Amount</p>
          <input type="text" value="1">
        </div>
        <div class="drop-list">
          <div class="from">
            <p>From</p>
            <div class="select-box">
              <img src="https://flagcdn.com/48x36/us.png" alt="flag">
              <select> <!-- Options tag are inserted from JavaScript --> </select>
            </div>
          </div>
          <div class="icon"><i class="fas fa-exchange-alt"></i></div>
          <div class="to">
            <p>To</p>
            <div class="select-box">
              <img src="https://flagcdn.com/48x36/np.png" alt="flag">
              <select> <!-- Options tag are inserted from JavaScript --> </select>
            </div>
          </div>
        </div>
        <div class="exchange-rate">Getting exchange rate...</div>
        <button>Get Exchange Rate</button>
      </form>
    </div>

    <script src="js/country-list.js"></script>
    <script src="js/script.js"></script>

  </body>
</html>

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

/* Import Google Font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 0 10px;
  background: #675AFE;
}
::selection{
  color: #fff;
  background: #675AFE;
}
.wrapper{
  width: 370px;
  padding: 30px;
  border-radius: 7px;
  background: #fff;
  box-shadow: 7px 7px 20px rgba(0, 0, 0, 0.05);
}
.wrapper header{
  font-size: 28px;
  font-weight: 500;
  text-align: center;
}
.wrapper form{
  margin: 40px 0 20px 0;
}
form :where(input, select, button){
  width: 100%;
  outline: none;
  border-radius: 5px;
  border: none;
}
form p{
  font-size: 18px;
  margin-bottom: 5px;
}
form input{
  height: 50px;
  font-size: 17px;
  padding: 0 15px;
  border: 1px solid #999;
}
form input:focus{
  padding: 0 14px;
  border: 2px solid #675AFE;
}
form .drop-list{
  display: flex;
  margin-top: 20px;
  align-items: center;
  justify-content: space-between;
}
.drop-list .select-box{
  display: flex;
  width: 115px;
  height: 45px;
  align-items: center;
  border-radius: 5px;
  justify-content: center;
  border: 1px solid #999;
}
.select-box img{
  max-width: 21px;
}
.select-box select{
  width: auto;
  font-size: 16px;
  background: none;
  margin: 0 -5px 0 5px;
}
.select-box select::-webkit-scrollbar{
  width: 8px;
}
.select-box select::-webkit-scrollbar-track{
  background: #fff;
}
.select-box select::-webkit-scrollbar-thumb{
  background: #888;
  border-radius: 8px;
  border-right: 2px solid #ffffff;
}
.drop-list .icon{
  cursor: pointer;
  margin-top: 30px;
  font-size: 22px;
}
form .exchange-rate{
  font-size: 17px;
  margin: 20px 0 30px;
}
form button{
  height: 52px;
  color: #fff;
  font-size: 17px;
  cursor: pointer;
  background: #675AFE;
  transition: 0.3s ease;
}
form button:hover{
  background: #4534fe;
}

Third, create a JavaScript file with the name of country-list.js and paste the given codes in your JavaScript file. Remember, you’ve to create a file with .js extension. In this file, we’ll store all country code and their currency code.

let country_list = {
    "AED" : "AE",
    "AFN" : "AF",
    "XCD" : "AG",
    "ALL" : "AL",
    "AMD" : "AM",
    "ANG" : "AN",
    "AOA" : "AO",
    "AQD" : "AQ",
    "ARS" : "AR",
    "AUD" : "AU",
    "AZN" : "AZ",
    "BAM" : "BA",
    "BBD" : "BB",
    "BDT" : "BD",
    "XOF" : "BE",
    "BGN" : "BG",
    "BHD" : "BH",
    "BIF" : "BI",
    "BMD" : "BM",
    "BND" : "BN",
    "BOB" : "BO",
    "BRL" : "BR",
    "BSD" : "BS",
    "NOK" : "BV",
    "BWP" : "BW",
    "BYR" : "BY",
    "BZD" : "BZ",
    "CAD" : "CA",
    "CDF" : "CD",
    "XAF" : "CF",
    "CHF" : "CH",
    "CLP" : "CL",
    "CNY" : "CN",
    "COP" : "CO",
    "CRC" : "CR",
    "CUP" : "CU",
    "CVE" : "CV",
    "CYP" : "CY",
    "CZK" : "CZ",
    "DJF" : "DJ",
    "DKK" : "DK",
    "DOP" : "DO",
    "DZD" : "DZ",
    "ECS" : "EC",
    "EEK" : "EE",
    "EGP" : "EG",
    "ETB" : "ET",
    "EUR" : "FR",
    "FJD" : "FJ",
    "FKP" : "FK",
    "GBP" : "GB",
    "GEL" : "GE",
    "GGP" : "GG",
    "GHS" : "GH",
    "GIP" : "GI",
    "GMD" : "GM",
    "GNF" : "GN",
    "GTQ" : "GT",
    "GYD" : "GY",
    "HKD" : "HK",
    "HNL" : "HN",
    "HRK" : "HR",
    "HTG" : "HT",
    "HUF" : "HU",
    "IDR" : "ID",
    "ILS" : "IL",
    "INR" : "IN",
    "IQD" : "IQ",
    "IRR" : "IR",
    "ISK" : "IS",
    "JMD" : "JM",
    "JOD" : "JO",
    "JPY" : "JP",
    "KES" : "KE",
    "KGS" : "KG",
    "KHR" : "KH",
    "KMF" : "KM",
    "KPW" : "KP",
    "KRW" : "KR",
    "KWD" : "KW",
    "KYD" : "KY",
    "KZT" : "KZ",
    "LAK" : "LA",
    "LBP" : "LB",
    "LKR" : "LK",
    "LRD" : "LR",
    "LSL" : "LS",
    "LTL" : "LT",
    "LVL" : "LV",
    "LYD" : "LY",
    "MAD" : "MA",
    "MDL" : "MD",
    "MGA" : "MG",
    "MKD" : "MK",
    "MMK" : "MM",
    "MNT" : "MN",
    "MOP" : "MO",
    "MRO" : "MR",
    "MTL" : "MT",
    "MUR" : "MU",
    "MVR" : "MV",
    "MWK" : "MW",
    "MXN" : "MX",
    "MYR" : "MY",
    "MZN" : "MZ",
    "NAD" : "NA",
    "XPF" : "NC",
    "NGN" : "NG",
    "NIO" : "NI",
    "NPR" : "NP",
    "NZD" : "NZ",
    "OMR" : "OM",
    "PAB" : "PA",
    "PEN" : "PE",
    "PGK" : "PG",
    "PHP" : "PH",
    "PKR" : "PK",
    "PLN" : "PL",
    "PYG" : "PY",
    "QAR" : "QA",
    "RON" : "RO",
    "RSD" : "RS",
    "RUB" : "RU",
    "RWF" : "RW",
    "SAR" : "SA",
    "SBD" : "SB",
    "SCR" : "SC",
    "SDG" : "SD",
    "SEK" : "SE",
    "SGD" : "SG",
    "SKK" : "SK",
    "SLL" : "SL",
    "SOS" : "SO",
    "SRD" : "SR",
    "STD" : "ST",
    "SVC" : "SV",
    "SYP" : "SY",
    "SZL" : "SZ",
    "THB" : "TH",
    "TJS" : "TJ",
    "TMT" : "TM",
    "TND" : "TN",
    "TOP" : "TO",
    "TRY" : "TR",
    "TTD" : "TT",
    "TWD" : "TW",
    "TZS" : "TZ",
    "UAH" : "UA",
    "UGX" : "UG",
    "USD" : "US",
    "UYU" : "UY",
    "UZS" : "UZ",
    "VEF" : "VE",
    "VND" : "VN",
    "VUV" : "VU",
    "YER" : "YE",
    "ZAR" : "ZA",
    "ZMK" : "ZM",
    "ZWD" : "ZW"
}

Last, create a JavaScript file with the name of script.js and paste the given codes in your JavaScript file. You’ve to create a file with .js extension and remember you have to pass your API key in the API URL otherwise this currency converter won’t work and it returns “something went wrong” error. You can get this key from the official ExchageRateAPI site for free.

const dropList = document.querySelectorAll("form select"),
fromCurrency = document.querySelector(".from select"),
toCurrency = document.querySelector(".to select"),
getButton = document.querySelector("form button");

for (let i = 0; i < dropList.length; i++) {
    for(let currency_code in country_list){
        let selected = i == 0 ? currency_code == "USD" ? "selected" : "" : currency_code == "NPR" ? "selected" : "";
        let optionTag = `<option value="${currency_code}" ${selected}>${currency_code}</option>`;
        dropList[i].insertAdjacentHTML("beforeend", optionTag);
    }
    dropList[i].addEventListener("change", e =>{
        loadFlag(e.target);
    });
}

function loadFlag(element){
    for(let code in country_list){
        if(code == element.value){
            let imgTag = element.parentElement.querySelector("img");
            imgTag.src = `https://flagcdn.com/48x36/${country_list[code].toLowerCase()}.png`;
        }
    }
}

window.addEventListener("load", ()=>{
    getExchangeRate();
});

getButton.addEventListener("click", e =>{
    e.preventDefault();
    getExchangeRate();
});

const exchangeIcon = document.querySelector("form .icon");
exchangeIcon.addEventListener("click", ()=>{
    let tempCode = fromCurrency.value;
    fromCurrency.value = toCurrency.value;
    toCurrency.value = tempCode;
    loadFlag(fromCurrency);
    loadFlag(toCurrency);
    getExchangeRate();
})

function getExchangeRate(){
    const amount = document.querySelector("form input");
    const exchangeRateTxt = document.querySelector("form .exchange-rate");
    let amountVal = amount.value;
    if(amountVal == "" || amountVal == "0"){
        amount.value = "1";
        amountVal = 1;
    }
    exchangeRateTxt.innerText = "Getting exchange rate...";
    let url = `https://v6.exchangerate-api.com/v6/YOUR-API-KEY/latest/${fromCurrency.value}`;
    fetch(url).then(response => response.json()).then(result =>{
        let exchangeRate = result.conversion_rates[toCurrency.value];
        let totalExRate = (amountVal * exchangeRate).toFixed(2);
        exchangeRateTxt.innerText = `${amountVal} ${fromCurrency.value} = ${totalExRate} ${toCurrency.value}`;
    }).catch(() =>{
        exchangeRateTxt.innerText = "Something went wrong";
    });
}

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

After extracting the file, open the JavaScript file and pass your API key in the API URL. You can get this key from the official ExchageRateAPI site for free. You can also use any other site API for this project. If you do so then you have to modify the JavaScript codes accordingly.

 

]]>
https://www.codingnepalweb.com/currency-converter-app-in-html-javascript/feed/ 42