Mr. Ochoa's
Simple JavaScript Examples


Hi! Check out these JavaScript examples.


Temperature Conversion

Cat Breed Selector


Number Guessing Game



Animations by Animatelo


//Number Guessing Game JavaScript Code (minus animations)
const gameDIV = document.getElementById("numberGuessingGame");
const gameButton = '<button type="button" onclick="playGame()">Click to Play</button>';
document.addEventListener('DOMContentLoaded', () => { gameDIV.innerHTML = gameButton; });
function playGame() {
    const limit = 7;
    gameDIV.innerHTML = (`
    <input type="number" id="guess" min="1" max="100" placeholder="Guess">
    <button type="button" id="check">Check</button><br>
    <h3 id="heading">Guess the number from 1 to 100<br>in ${limit} tries or less.</h3>
    <button type="button" id="playAgain">Play Again?</button>
    <button type="button" id="close">Close</button>
    `);
    const heading = document.getElementById("heading");
    heading.style.color = 'mediumaquamarine';
    const guessInput = document.getElementById("guess");
    const checkButton = document.getElementById("check");
    const playAgainButton = document.getElementById("playAgain");
    const close = document.getElementById("close");
    const answer = (Math.floor(Math.random() * 100) + 1);
    let attempts = 0;
    attemptMeter.value = 0;
    guessInput.addEventListener("keypress", function (event) {
        if (event.key === "Enter") {
            event.preventDefault();
            checkButton.click();
        };
    });
    checkButton.addEventListener("click", () => {
        if (guessInput.value) { checkNumber(Number(guessInput.value)) };
    });
    function checkNumber(guessNumber) {
        attempts++;
        if (attempts < limit || guessNumber == answer) {
            const leftAttempts = limit - attempts;
            if (guessNumber < answer) {
                heading.innerText = `Too low. Try again.\nAttempts Left: ${leftAttempts}`;
                heading.style.color = 'cornflowerblue';
            } else if (guessNumber > answer) {
                heading.innerText = `Too high. Try again.\nAttempts Left: ${leftAttempts}`;
                heading.style.color = 'palevioletred';
            } else {
                const tries = (attempts === 1) ? 'try' : 'tries';
                heading.innerText = `${answer} is correct\nin only ${attempts} ${tries}!`;
                heading.style.color = 'gold';
                disableCheckButton();
            };
        } else {
            heading.innerText = `You've reached the limit.\nThe number was ${answer}.`;
            heading.style.color = 'orchid';
            disableCheckButton();
        };
    };
    function disableCheckButton() {
        checkButton.disabled = true;
        checkButton.style.opacity = '0.5';
    };
    playAgainButton.onclick = function () { playGame() };
    close.addEventListener("click", () => { gameDIV.innerHTML = gameButton });
};
            

Also, check out these Arduino tutorials.