Search Results for “game” – 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. Thu, 10 Aug 2023 17:42:30 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 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
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
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
Rock Paper Scissors Game in HTML CSS & JavaScript https://www.codingnepalweb.com/rock-paper-scissors-game-javascript/ https://www.codingnepalweb.com/rock-paper-scissors-game-javascript/#respond Sun, 26 Mar 2023 21:11:22 +0000 https://www.codingnepalweb.com/?p=4113 Rock Paper Scissors Game in HTML CSS & JavaScript

At least once in your life, you must have played the rock-paper-scissors game. Have you ever considered creating a rock-paper-scissors game using HTML, CSS, and Javascript?

Today in this blog, you will learn how to create a rock-paper-scissors game using HTML, CSS, and JavaScript. By the end, you will not only have a functional game, but you will also acquire an understanding of the game’s logic, error handling, and other related aspects. Recently I have provided a Number Guessing Game as well, I hope that it is also beneficial for you.

The rock-paper-scissors game’s interface, as depicted in the preview, will appear similar to the final product. The opponent you’ll be playing against in this game will be the CPU. Additionally, I have included some animations to enhance the gaming experience.

Video Tutorial of Rock Paper Scissors in JavaScript

As you have seen in the video tutorial of the rock-paper-scissors game how I created it in HTML CSS and JavaScript. I showed you how can we play this game with cpu.
I would recommend you watch the full video tutorial of this rock-paper-scissors game. By watching this instructional video you could create this game step by step with me. Additionally, I have comments on every line of JavaScript code to make you understand.

Steps for creating Rock-Paper-Scissors Game

To create a Rock-Paper-Scissors Game 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>JavaScript Game | Rock Paper Scissors</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <section class="container">
      <div class="result_field">
        <div class="result_images">
          <span class="user_result">
            <img src="images/rock.png" alt="" />
          </span>
          <span class="cpu_result">
            <img src="images/rock.png" alt="" />
          </span>
        </div>
        <div class="result">Let's Play!!</div>
      </div>

      <div class="option_images">
        <span class="option_image">
          <img src="images/rock.png" alt="" />
          <p>Rock</p>
        </span>
        <span class="option_image">
          <img src="images/paper.png" alt="" />
          <p>Paper</p>
        </span>
        <span class="option_image">
          <img src="images/scissors.png" alt="" />
          <p>Scissors</p>
        </span>
      </div>
    </section>

   <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: #f6f7fb;
}
::selection {
  color: #fff;
  background-color: #7d2ae8;
}
.container {
  padding: 2rem 7rem;
  border-radius: 14px;
  background: #fff;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
.result_images {
  display: flex;
  column-gap: 7rem;
}
.container.start .user_result {
  transform-origin: left;
  animation: userShake 0.7s ease infinite;
}
@keyframes userShake {
  50% {
    transform: rotate(10deg);
  }
}

.container.start .cpu_result {
  transform-origin: right;
  animation: cpuShake 0.7s ease infinite;
}
@keyframes cpuShake {
  50% {
    transform: rotate(-10deg);
  }
}
.result_images img {
  width: 100px;
}
.user_result img {
  transform: rotate(90deg);
}
.cpu_result img {
  transform: rotate(-90deg) rotateY(180deg);
}
.result {
  text-align: center;
  font-size: 2rem;
  color: #7d2ae8;
  margin-top: 1.5rem;
}

.option_image img {
  width: 50px;
}
.option_images {
  display: flex;
  align-items: center;
  margin-top: 2.5rem;
  justify-content: space-between;
}
.container.start .option_images {
  pointer-events: none;
}
.option_image {
  display: flex;
  flex-direction: column;
  align-items: center;
  opacity: 0.5;
  cursor: pointer;
  transition: opacity 0.3s ease;
}
.option_image:hover {
  opacity: 1;
}
.option_image.active {
  opacity: 1;
}
.option_image img {
  pointer-events: none;
}
.option_image p {
  color: #7d2ae8;
  font-size: 1.235rem;
  margin-top: 1rem;
  pointer-events: none;
}

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

// Get  to DOM elements
const gameContainer = document.querySelector(".container"),
  userResult = document.querySelector(".user_result img"),
  cpuResult = document.querySelector(".cpu_result img"),
  result = document.querySelector(".result"),
  optionImages = document.querySelectorAll(".option_image");

// Loop through each option image element
optionImages.forEach((image, index) => {
  image.addEventListener("click", (e) => {
    image.classList.add("active");

    userResult.src = cpuResult.src = "images/rock.png";
    result.textContent = "Wait...";

    // Loop through each option image again
    optionImages.forEach((image2, index2) => {
      // If the current index doesn't match the clicked index
      // Remove the "active" class from the other option images
      index !== index2 && image2.classList.remove("active");
    });

    gameContainer.classList.add("start");

    // Set a timeout to delay the result calculation
    let time = setTimeout(() => {
      gameContainer.classList.remove("start");

      // Get the source of the clicked option image
      let imageSrc = e.target.querySelector("img").src;
      // Set the user image to the clicked option image
      userResult.src = imageSrc;

      // Generate a random number between 0 and 2
      let randomNumber = Math.floor(Math.random() * 3);
      // Create an array of CPU image options
      let cpuImages = ["images/rock.png", "images/paper.png", "images/scissors.png"];
      // Set the CPU image to a random option from the array
      cpuResult.src = cpuImages[randomNumber];

      // Assign a letter value to the CPU option (R for rock, P for paper, S for scissors)
      let cpuValue = ["R", "P", "S"][randomNumber];
      // Assign a letter value to the clicked option (based on index)
      let userValue = ["R", "P", "S"][index];

      // Create an object with all possible outcomes
      let outcomes = {
        RR: "Draw",
        RP: "Cpu",
        RS: "User",
        PP: "Draw",
        PR: "User",
        PS: "Cpu",
        SS: "Draw",
        SR: "Cpu",
        SP: "User",
      };

      // Look up the outcome value based on user and CPU options
      let outComeValue = outcomes[userValue + cpuValue];

      // Display the result
      result.textContent = userValue === cpuValue ? "Match Draw" : `${outComeValue} Won!!`;
    }, 2500);
  });
});

If you face any difficulties while creating your Rock Paper Scissors Game or your code is not working as expected, you can download the source code files for this Rock Paper Scissors Game 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/rock-paper-scissors-game-javascript/feed/ 0
Number Guessing Game in HTML CSS & JavaScript https://www.codingnepalweb.com/create-game-html-css-javascript/ https://www.codingnepalweb.com/create-game-html-css-javascript/#respond Tue, 21 Mar 2023 21:11:21 +0000 https://www.codingnepalweb.com/?p=4114 Create Game in HTML CSS & JavaScript

You might have played various games, but were you aware that you can develop games using HTML, CSS, and JavaScript that can be played by both you and the computer or a bot?

Today in this blog post, I will teach you how to create a Game using HTML CSS, and JavaScript. Furthermore, I strongly believe that developing games is an excellent way to enhance your coding skills, as it requires using logic and problem-solving skills.

As you can see outlook at the image of the game that you will learn to create today. In this game, the computer or bot will randomly select a number that you will not know, and you have to guess the number based on the hints provided, with 10 chances to make the correct guess.

Video Tutorial of Number Guessing Game in JS

As you saw in this video tutorial of the number-guessing game. How I built a simple game in HTML CSS and JavaScript. As well as how we can play this game by guessing the exact number with hints.

I would highly recommend you watch the video tutorial of this game. I have tried to make you understand every line of code with comments. If you want to skip you may continue reading the blog.

Steps for Number Guessing Game in JavaScript

To create this Number Guessing Game, 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 Number Guessing 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>Game in HTML CSS & JavaScript</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="wrapper">
      <header>Guess a number from 1 to 100</header>
      <p class="guess"></p>
      <div class="input-field">
        <input type="number" />
        <button>Check</button>
      </div>
      <p>You have <span class="chances">10</span> chances</p>
    </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 {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #4a98f7;
}
.wrapper {
  padding: 30px 40px;
  border-radius: 12px;
  background: #fff;
  text-align: center;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
.wrapper header {
  font-size: 18px;
  font-weight: 400;
  color: #333;
}
.wrapper p {
  color: #333;
}
.wrapper .input-field {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin: 25px 0;
}
.input-field input,
.input-field button {
  height: 50px;
  width: calc(100% / 2 - 20px);
  outline: none;
  padding: 0 20px;
  border-radius: 8px;
  font-size: 18px;
}
.input-field input {
  text-align: center;
  color: #707070;
  width: 110px;
  border: 1px solid #aaa;
}
input::-webkit-inner-spin-button,
input::-webkit-outer-spin-button {
  display: none;
}
.input-field input:disabled {
  cursor: not-allowed;
}
.input-field button {
  border: none;
  background: #4a98f7;
  color: #fff;
  cursor: pointer;
  transition: 0.3s;
}
.input-field button:active {
  transform: scale(0.97);
}

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

// Get the DOM elements and initialize the game
const input = document.querySelector("input"),
  guess = document.querySelector(".guess"),
  checkButton = document.querySelector("button"),
  remainChances = document.querySelector(".chances");

// Set the focus on input field
input.focus();

let randomNum = Math.floor(Math.random() * 100);
chance = 10;

// Listen for the click event on the check button
checkButton.addEventListener("click", () => {
  // Decrement the chance variable on every click
  chance--;
  // Get the value from the input field
  let inputValue = input.value;
  // Check if the input value is equal to the random number
  if (inputValue == randomNum) {
    // Update guessed number, disable input, check button text and color.
    [guess.textContent, input.disabled] = ["Congratulations", true];
    [checkButton.textContent, guess.style.color] = ["Replay", "#333"];
    //Check if input value is > random number and within 1-99 range.
  } else if (inputValue > randomNum && inputValue < 100) {
    // Update the guess text and remaining chances
    [guess.textContent, remainChances.textContent] = ["Your guess is high", chance];
    guess.style.color = "#333";
    //Check if input value is < random number and within 1-99 range.
  } else if (inputValue < randomNum && inputValue > 0) {
    // Update the guessed number text and remaining chances
    [guess.textContent, remainChances.textContent] = ["Your guess is low", chance];
    guess.style.color = "#333";
    // If the input value is not within the range of 1 to 99
  } else {
    // Update the guessed number text, color and remaining chances
    [guess.textContent, remainChances.textContent] = ["Your number is invalid", chance];
    guess.style.color = "#DE0611";
  }
  // Check if the chance is zero
  if (chance == 0) {
    //Update check button, disable input, and clear input value.
    // Update guessed number text and color to indicate user loss.
    [checkButton.textContent, input.disabled, inputValue] = ["Replay", true, ""];
    [guess.textContent, guess.style.color] = ["You lost the game", "#DE0611"];
  }
  if (chance < 0) {
    window.location.reload();
  }
});

If you face any difficulties while creating your Number Guessing Game or your code is not working as expected, you can download the source code files for this Number Guessing Game 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/create-game-html-css-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
How to Create A Snake Game in HTML CSS & JavaScript https://www.codingnepalweb.com/create-snake-game-htm-css-javascript/ https://www.codingnepalweb.com/create-snake-game-htm-css-javascript/#comments Fri, 17 Feb 2023 11:20:52 +0000 https://www.codingnepalweb.com/?p=4020 Create A Snake Game in HTML CSS & JavaScript JavaScript Game Tutorial

Snake is a classic game that millions of people have played. Have you ever thought about creating your own Snake Game? Creating a Snake Game using HTML, CSS, and vanilla JavaScript is a fun and educational project that can improve your web development skills.

In this blog post, I’ll guide you through the steps of creating your own Snake Game from scratch. You can play this game on a PC using keyboard arrow keys or on a mobile device using touch-based arrow buttons.

If you’re excited to see how this snake game looks and works, click here to play it. For a full video tutorial on creating a snake game using HTML, CSS, and JavaScript, you can watch the given YouTube video.

Video Tutorial of Snake Game in JavaScript

 

Making a Snake Game is not only fun, but it can also help you develop problem-solving skills and the ability to break down complex problems into smaller ones. So, I highly recommend that you watch the above video tutorial to the end.

In the video, I tried to explain each line with comments and show which code does what in the game. But if you wish, you can skip the video tutorial and continue reading this post to create a snake game on your own.

Steps For Creating Snake Game in JavaScript

To create a snake game 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 game’s basic layout. The “play-board” container is empty now, but it will be filled with snake bodies and food elements later using JavaScript code.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Snake Game 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://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">
      <div class="game-details">
        <span class="score">Score: 0</span>
        <span class="high-score">High Score: 0</span>
      </div>
      <div class="play-board"></div>
      <div class="controls">
        <i data-key="ArrowLeft" class="fa-solid fa-arrow-left-long"></i>
        <i data-key="ArrowUp" class="fa-solid fa-arrow-up-long"></i>
        <i data-key="ArrowRight" class="fa-solid fa-arrow-right-long"></i>
        <i data-key="ArrowDown" class="fa-solid fa-arrow-down-long"></i>
      </div>
    </div>

  </body>
</html>

Next, add the following CSS codes to your style.css file to make the layout of the Snake game. Remember that control arrow keys are only shown on small devices, such as phones. If you prefer to display them on all devices, you can easily modify the media query code.

/* Import Google font */
@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;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #E3F2FD;
}
.wrapper {
  width: 65vmin;
  height: 70vmin;
  display: flex;
  overflow: hidden;
  flex-direction: column;
  justify-content: center;
  border-radius: 5px;
  background: #293447;
  box-shadow: 0 20px 40px rgba(52, 87, 220, 0.2);
}
.game-details {
  color: #B8C6DC;
  font-weight: 500;
  font-size: 1.2rem;
  padding: 20px 27px;
  display: flex;
  justify-content: space-between;
}
.play-board {
  height: 100%;
  width: 100%;
  display: grid;
  background: #212837;
  grid-template: repeat(30, 1fr) / repeat(30, 1fr);
}
.play-board .food {
  background: #FF003D;
}
.play-board .head {
  background: #60CBFF;
}

.controls {
  display: none;
  justify-content: space-between;
}
.controls i {
  padding: 25px 0;
  text-align: center;
  font-size: 1.3rem;
  color: #B8C6DC;
  width: calc(100% / 4);
  cursor: pointer;
  border-right: 1px solid #171B26;
}

@media screen and (max-width: 800px) {
  .wrapper {
    width: 90vmin;
    height: 115vmin;
  }
  .game-details {
    font-size: 1rem;
    padding: 15px 27px;
  }
  .controls {
    display: flex;
  }
  .controls i {
    padding: 15px 0;
    font-size: 1rem;
  }
}

Finally, add the following JavaScript code to your script.js file to add functionality for the snake game. This code will handle the logic behind the snake’s movement, eating food, updating the score, and detecting collisions with walls or its own body.

const playBoard = document.querySelector(".play-board");
const scoreElement = document.querySelector(".score");
const highScoreElement = document.querySelector(".high-score");
const controls = document.querySelectorAll(".controls i");

let gameOver = false;
let foodX, foodY;
let snakeX = 5, snakeY = 5;
let velocityX = 0, velocityY = 0;
let snakeBody = [];
let setIntervalId;
let score = 0;

// Getting high score from the local storage
let highScore = localStorage.getItem("high-score") || 0;
highScoreElement.innerText = `High Score: ${highScore}`;

const updateFoodPosition = () => {
    // Passing a random 1 - 30 value as food position
    foodX = Math.floor(Math.random() * 30) + 1;
    foodY = Math.floor(Math.random() * 30) + 1;
}

const handleGameOver = () => {
    // Clearing the timer and reloading the page on game over
    clearInterval(setIntervalId);
    alert("Game Over! Press OK to replay...");
    location.reload();
}

const changeDirection = e => {
    // Changing velocity value based on key press
    if(e.key === "ArrowUp" && velocityY != 1) {
        velocityX = 0;
        velocityY = -1;
    } else if(e.key === "ArrowDown" && velocityY != -1) {
        velocityX = 0;
        velocityY = 1;
    } else if(e.key === "ArrowLeft" && velocityX != 1) {
        velocityX = -1;
        velocityY = 0;
    } else if(e.key === "ArrowRight" && velocityX != -1) {
        velocityX = 1;
        velocityY = 0;
    }
}

// Calling changeDirection on each key click and passing key dataset value as an object
controls.forEach(button => button.addEventListener("click", () => changeDirection({ key: button.dataset.key })));

const initGame = () => {
    if(gameOver) return handleGameOver();
    let html = `<div class="food" style="grid-area: ${foodY} / ${foodX}"></div>`;

    // Checking if the snake hit the food
    if(snakeX === foodX && snakeY === foodY) {
        updateFoodPosition();
        snakeBody.push([foodY, foodX]); // Pushing food position to snake body array
        score++; // increment score by 1
        highScore = score >= highScore ? score : highScore;
        localStorage.setItem("high-score", highScore);
        scoreElement.innerText = `Score: ${score}`;
        highScoreElement.innerText = `High Score: ${highScore}`;
    }
    // Updating the snake's head position based on the current velocity
    snakeX += velocityX;
    snakeY += velocityY;
    
    // Shifting forward the values of the elements in the snake body by one
    for (let i = snakeBody.length - 1; i > 0; i--) {
        snakeBody[i] = snakeBody[i - 1];
    }
    snakeBody[0] = [snakeX, snakeY]; // Setting first element of snake body to current snake position

    // Checking if the snake's head is out of wall, if so setting gameOver to true
    if(snakeX <= 0 || snakeX > 30 || snakeY <= 0 || snakeY > 30) {
        return gameOver = true;
    }

    for (let i = 0; i < snakeBody.length; i++) {
        // Adding a div for each part of the snake's body
        html += `<div class="head" style="grid-area: ${snakeBody[i][1]} / ${snakeBody[i][0]}"></div>`;
        // Checking if the snake head hit the body, if so set gameOver to true
        if (i !== 0 && snakeBody[0][1] === snakeBody[i][1] && snakeBody[0][0] === snakeBody[i][0]) {
            gameOver = true;
        }
    }
    playBoard.innerHTML = html;
}

updateFoodPosition();
setIntervalId = setInterval(initGame, 100);
document.addEventListener("keyup", changeDirection);

In the code, you can see that the current speed of the snake is 100 milliseconds, which determines how quickly the snake moves on the game board. You can easily adjust this speed by changing the value in the “setInterval” function at the bottom of the code.

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.

Conclusion and Final Words

By following the steps in this blog post, you have successfully created a classic snake game using HTML, CSS, and JavaScript which you can play on any device browser. I hope this snake game project helps you understand DOM manipulation, problem-solving skills, and other web development skills.

If you enjoyed creating your Snake Game and learned something new, you can check out my other JavaScript Games such as Quiz, Memory Card, Tic Tac Toe, and many more. These games are not only enjoyable to create but also provide an excellent opportunity to practice and enhance your JavaScript skills.

If you encounter any problems or your code is not working as expected, you can download the source code files of this Snake Game project by clicking on 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/create-snake-game-htm-css-javascript/feed/ 1
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
PHP vs Node.js – Which is best for Backend Development? https://www.codingnepalweb.com/php-vs-nodejs-which-is-best-for-backend/ https://www.codingnepalweb.com/php-vs-nodejs-which-is-best-for-backend/#comments Tue, 27 Dec 2022 11:48:18 +0000 https://www.codingnepalweb.com/?p=3736 PHP vs Node.js Which is best for Backend Development

There are numerous programming languages available for backend development, but two of the most commonly used are PHP and Node.js. These languages are popular choices for building backend web applications and websites, but they each have their own unique set of strengths and weaknesses.

To help you decide which technology is the best fit for your backend development project, this blog will provide an overview of PHP and Node.js. We’ll cover what these languages are, what they are used for, and the critical differences between them.

By understanding the capabilities and features of each technology, you can make an informed decision about which one is the best fit for your specific project needs and requirements.

But before continuing this blog, there is also a lot of confusion among frontend developers when choosing the best framework for frontend development, if you’re one of them, this blog might be helpful to you: React vs Angular – Which is best for Frontend Development?

What is PHP, and what does it do?

What is PHP, and what does it do

PHP, which stands for “Hypertext Preprocessor,” is a server-side scripting language that is widely used for creating dynamic web applications and websites. It is executed on the server and generates HTML (HyperText Markup Language), which is then sent to the client’s web browser.

PHP was developed by Rasmus Lerdorf in 1994 and has since become a popular choice for building dynamic web pages. It is well-known for its ease of use, and it has a large ecosystem of frameworks such as Laravel, CodeIgniter, Symfony, etc., which offer a range of tools and features to help developers build robust and scalable web applications easily.

PHP has numerous advantages, some of which are listed below:

  • It is easy to learn and use even if you’re a newbie in backend development.
  • It has a large ecosystem of powerful libraries and frameworks available.
  • It is compatible with a wide range of platforms including Linux, and Windows.
  • It has built-in support for popular databases that make data easy to read and store.
  • It has many built-in security features such as input validation and sanitization.
  • It has a huge and active community of developers.

What is Node.js, and what does it do?

What is Node.js, and what does it do

Node.js is a JavaScript runtime environment that enables the execution of JavaScript code on the server side, outside of a web browser. It was developed by Ryan Dahl in 2009 and built using the V8 JavaScript engine, which is also used by the Chrome web browser.

Node.js is designed to be lightweight, efficient, and well-known for its fast performance and scalability. As a result, it is ideal for creating real-time web applications such as chat applications and online games. Node.js is also a cross-platform technology, which means it can be used on various operating systems, including Windows, macOS, and Linux.

Node.js has numerous advantages, some of which are listed below:

  • It is easy to learn and use, especially if you’re familiar with JavaScript.
  • It is efficient and well-suited for building real-time applications and APIs.
  • It uses an event-driven, non-blocking I/O model that makes it asynchronous.
  • It is a cross-platform technology that works on a variety of platforms.
  • It can be used for both the front-end and back-end of web development.

Differences between PHP and Node.js

There are several differences between PHP and Nod.js. But some key differences between them are pointed out below.

PHP Node.js
It is a server-side scripting language. It is a JavaScript runtime environment.
It uses a traditional synchronous programming model. It uses an event-driven, non-blocking I/O model.
It has a large ecosystem of libraries and frameworks. It has a more limited set of tools and libraries.
It is slower and less efficient than Node.js. It is faster and more efficient than PHP.
It is used for server-side rendering of web pages. It is used for building server-side applications and APIs.
It is used in collaboration with relational databases like MySQL. It works perfectly with NoSQL (not only SQL) databases like MongoDB.

Which should you use, PHP or Node.js?

As you are now aware, what are PHP and Node.js, their pros and cons, and the differences between them? The decision of which technology you should use will depend on your specific project requirements and the resources and skills that are available to you.

PHP can be the best choice if you are a newbie and want to build a simple, traditional web application or website because it is easy to learn and has a large number of frameworks. But if you are familiar with JavaScript and want to build real-time, high-performance web applications or APIs, then Node.js might be a better choice for you.

Ultimately, each technology has its own advantages and disadvantages. So, before selecting any of these technologies for your backend development, it is important to consider your project requirements, objectives, and your personal interests and skills.

If you found this blog useful, please consider sharing it with others to help them benefit as well. Thank you for your support and keep visiting our site.

]]>
https://www.codingnepalweb.com/php-vs-nodejs-which-is-best-for-backend/feed/ 5
10 Best JavaScript Frameworks to Use in 2023 https://www.codingnepalweb.com/10-best-javascript-frameworks-to-use-in-2023/ https://www.codingnepalweb.com/10-best-javascript-frameworks-to-use-in-2023/#respond Thu, 08 Dec 2022 21:11:21 +0000 https://www.codingnepalweb.com/?p=4132
10 Best JavaScript Frameworks to Use in 2023

JavaScript is the first choice for any developer who wants to create interactive and dynamic web applications. Plus, it is in demand for creating front-end development and mobile games.

However, there are a few types of JavaScript frameworks that come with unique features and benefits. The frameworks are a collection of different pre-written codes and other resources.

The frameworks provide consistency across different projects. Moreover, selecting the most popular framework for your project can be a tricky decision. Let’s dive deep and look at the 10 best JavaScript frameworks that are at the top of the developers’ list.

1. Angular

Angular
  • Angular is a popular JS framework that offers great features for single-page applications.
  • It allows for testing capabilities and DOM manipulation.
  • Plus, it offers data binding with architectural support.
  • It comes with dependency injection and performance.
  • Angular provides the authors with the opportunity to create bi-directional data binding.
  • It allows users to exchange data between views and apps.
Moreover, it enhances the development process of single-page applications through a component-based architecture. The components can be customized and reused.
Angular provides new developers with integrated libraries to test, elaborate, and make updates to their codes. You can hire Angular developer to learn more about the framework.

2. Vue.js

Vue.js
  • The framework was designed by former Google employee Evan You.
  • It is fast, lightweight, and comes with an extensive library of resources.
  • Moreover, you can get access to documentation and tutorials.
  • It offers a composition API and the reusing of different codes.
  • The framework offers a multi-root component feature.
  • The best part of the framework is that it handles complex workflows with ease. Apart from front-end support, it also provides complete access to back-end applications.
Additionally, it comes with routing capabilities and a server-side rendering engine. It requires minimum build-up time and includes a virtual DOM option. High-quality integration is the best feature of the platform.

3. React

React
  • React is also one of the popular JavaScript frameworks and is at the top of the list.
  • It is adept at creating different web applications.
  • It’s open source and free. Plus, you can access it through Github.
  • It offers two-way data binding with a component-based architecture.
Moreover, it comes with a virtual DOM and declarative UI. It offers different reusable components, depending on your business logic. It integrates with different front-end and back-end solutions. It comes with one direction of data flow: flux.
Additionally, it is an SEO-friendly JS framework. React is gaining massive popularity as it is being utilized for faster development.

4. Node.js

Node.js
  • Node runs in the runtime environment on the server side. Plus, it’s open source, free, and can run on different cross-platform platforms.
  • The best part about the framework is that it is simple to use and provides high performance.
  • It is highly scalable and completely event-driven.
  • It has a single-threaded feature and cross-platform scalability.
Node JS has large community support and can help new developers with the project. It works at a great speed outside of web browsers. With Node.JS, the developer will be able to create robust web applications.

5. Ember

Ember
  • The Ember JavaScript framework was created by Ember.
  • It is popular, free, and delivers quick results for web applications.
  • It receives support from thousands of developers around the world.
  • Ember offers a client-side rendering feature with URL support.
  • Additionally, it comes with a high-performance focus.
  • It provides a two-way data binding capability, making it super flexible and trustworthy.
  • It is adept at handling different complex UIs.
  • Some major brands, like Netflix and LinkedIn, use the Ember JS framework.
  • The only disadvantage is that it is difficult to learn and is biased.

6. Backbone

Backbone
  • Backbone is an open-source framework that helps to build user interfaces.
  • It is fast, reliable, flexible, lightweight, and simple to integrate with.
  • It offers easy API integration with event binding.
  • A developer can create single-page applications with assistance.
Additionally, you can use the framework to give definite structure to different web applications. It has a rich ecosystem of extensions and plugins that can be easily found on Github. It is mostly used by new companies for building client-side applications.

7. Meteor

Meteor
  • The framework can be used for cross-platform code and quick prototyping.
  • It is simple to comprehend and provides good flexibility.
  • You can develop apps with the single-page feature.
Moreover, it has a real-time app development feature and a supportive community.
  • As it’s free and open source, you don’t have to worry about the licensing part, as you can download the framework from Github.
  • The best part about the framework is that it has a simple learning curve.

8. Aurelia

Aurelia
  • The framework comes with extensive documentation and support, and the syntax is easy to read.
  • Being free and open source, it is specifically designed for modern front-end frameworks.
  • It acts as a great tool for developing cross-platform applications for any website.
  • It offers a reactive binding feature and an extensive ecosystem.
Moreover, it offers a simple testing feature that comes with a powerful dependency injection container. It offers unmatched extensibility, and you can create custom elements and control template generation and reactive binding types. The framework offers effortless coding and conventions.

9. Mithril

Mithril
  • Mithril is a lightweight framework with a simple learning curve.
  • Despite its limitations, it performs well in comparison to other frameworks.
  • It is a robust framework that offers faster performance.
Moreover, developers choose the framework for single-page applications. It provides routing utilities. It supports Firefox, Chrome, and other versions of browsers. It lets you integrate with third-party plugins and offers path handling.

10. Svelte

Svelte
  • It is an open-source framework that offers simplified solutions for development.
  • Developers can create fast and static web applications with Svelte.
Additionally, it is best suited as a compiler for developing different web UI components. That said, it does that without worrying about DOMs. The framework requires less coding, which means you can save precious time.

Conclusion

If you are just getting started with JavaScript, you can consider Angular, React, and Vue as popular choices. If you need to work on a complex project, you can choose Node.js. Moreover, it is significant to consider your project needs and the features required for app development. No matter which framework you choose, ensure that it supports good documentation.
If you’re new to the programming world, you may have heard these two most popular terms: “frontend” and “backend.” Read this blog Frontend vs Backend Development: What’s the Difference? to find out what these terms actually refer to in web development.
]]>
https://www.codingnepalweb.com/10-best-javascript-frameworks-to-use-in-2023/feed/ 0