SLC | S22W1 : Create Website :Voice-Activated Investment: Lesson #1 - Exploring Dynamic Web Features and Speech Recognition

in hive-185836 •  7 months ago 

Topic

Today we are going to learn how we can create a website that can be controlled by voice and changes by speaking.
First we will learn what the structure of HTML is.
It's evening now. I'll do my self-verification on Steemit by tomorrow.
The rest of the HTML title and body tags are not included because Steemit doesn't allow them, so I removed them.

The simple structure for html

01.code

<!DOCTYPE html>
html lang="en"
<head>
    html charset="UTF-8">
    html name="viewport" content="width=device-width, initial-scale=1.0">
    title>Document</title>
</head>
<body>
    
</body>
</html>

02.code


<!DOCTYPE html>
html lang="en">
<head>
  html charset="UTF-8">
  html name="viewport" content="width=device-width, initial-scale=1.0">
  title>Earn Daily Returns</title>
  <style
    /* Styles will go here */
  </style>
</head>
<body>
  (html comment removed:  Main Content will go here )
</body>
</html>

See what is used in this code.

  • * : This is the declaration that defines the document as HTML5.
  • html lang="en">: Specifies that the language of the document is English.

  • html charset="UTF-8">: Defines the character encoding to ensure the page can support various symbols.

  • html name="viewport">: Ensures the page is responsive on different devices.

  • title>: Specifies the title that appears in the browser tab.

  • <style: Placeholder for the CSS styling rules.

*<body: Contains the visible content of the page.


In the second part of this we will learn CSS styling.

03.code
The Body and Container


body {
  margin: 0;
  font-family: Arial, sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  transition: background-color 0.5s ease;
  background-color: #1c1c1c;
  color: white;
  overflow: hidden;
  position: relative;
}

.container {
  text-align: center;
  max-width: 600px;
  padding: 20px;
  background-color: rgba(0, 0, 0, 0.8);
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
}

Let's see what we have done in this.

  • body styling: This centers everything in the middle of the screen and sets the background color to dark. It also enables smooth transitions when changing the background color.
  • container styling: This applies a dark translucent background, some padding, and a rounded border to the main content box.

Now we improve this code to give heading text and buttons

h1 {
  font-size: 2.5em;
  color: #ff8c00;
  margin-bottom: 20px;
}

p {
  font-size: 1.2em;
  color: #dcdcdc;
  margin-bottom: 20px;
}

.cta-button {
  background-color: #ff8c00;
  color: white;
  padding: 15px 30px;
  font-size: 1.5em;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin-top: 20px;
}


We also write this down so that it is easier for you to understand.

  • h1 styling: This gives the heading a bright orange color and larger font size for visibility.
  • p styling: The paragraph is styled with a slightly gray color and appropriate margin.
  • cta-button styling: The call-to-action button is designed to stand out with a bright orange color, white text, and a hover effect.

In the third part we will learn: JavaScript Logic - Adding Interactivity

How will we handle commands via voice?:Lets see

const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const statusDiv = document.getElementById("status");

if (SpeechRecognition) {
  const recognition = new SpeechRecognition();
  recognition.continuous = true;
  recognition.lang = "en-US";

  recognition.onresult = function (event) {
    const transcript = event.results[event.results.length - 1][0].transcript.toLowerCase();
    console.log("Heard:", transcript);

    if (transcript.includes("invest") || transcript.includes("investment")) {
      const newColor = getRandomColor();
      document.body.style.backgroundColor = newColor;
      statusDiv.textContent = "Background color changed.";
    }
  };
  
  recognition.start();
}


This is important for you to learn and I think it will take you a little time to learn.

  • In this, we have put some commands that we will speak through voice and everything will be changed. You can see it in the code. I will also give you the full code at the end so that you can compile it and see it.
  • Speech Recognition: This sets up the Speech Recognition API, enabling the browser to listen to commands like "invest" and change the background color dynamically.

Watch this and understand this.

Toggle Visibility of Text Take a close look at this code to see how it works.


function toggleVisibility() {
  const introText = document.getElementById("introText");
  introText.style.display = introText.style.display === "none" ? "block" : "none";
}


You can see how this function works and what its benefits are.

  • Toggle Visibility: A function that hides or shows the introductory text when a specific voice command is detected.

Now we will write a code that will bring up the calculator via voice command and make the calculator disappear via voice command. Investment Calculator

Investment Calculator

function calculate() {
  const investment = parseFloat(document.getElementById("investment").value);
  if (isNaN(investment) || investment <= 0) {
    document.getElementById("result").textContent = "Please enter a valid investment amount.";
    return;
  }
  const dailyProfit = (investment * (dailyRate / 100)).toFixed(2);
  const monthlyProfit = (investment + investment * (dailyRate / 100) * 30).toFixed(2);

  document.getElementById("result").innerHTML = `Daily Profit: $${dailyProfit}<br>Total in 30 Days: $${monthlyProfit}`;
}


Let's write a little about the calculator and what it does.

  • Investment Calculation: This function calculates daily and monthly profits based on the entered investment amount and the current daily return rate.

You will learn in the fourth part. Voice Commands for Interactive Features .This is also a very important thing to learn.

Voice Handling Code

if (transcript.includes("time")) {
  showTime(); // Display the time
  statusDiv.textContent = "Voice command: 'Time' received. Showing time.";
}



I'll write a little about it in English so you can understand it quickly.

  • Voice Command for Time: If the user says "time," the current time is displayed in the top-right corner.

In the fifth part, we will learn how to impress a user when they visit our website.

It is neccessary to improve t.Real-Time Time Display

function showTime() {
  const time = new Date();
  const options = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true };
  const timeString = time.toLocaleTimeString(undefined, options); // Get local time based on user's location
  timeDisplay.textContent = `Time: ${timeString}`;
  timeDisplay.style.display = 'block'; // Show the time
}


Let me explain this code a little bit.

  • Real-Time Time: This function shows the current time in a user-friendly format and updates the time in real-time.


All these codes show how to create a beautiful and better page that can be controlled by voice using all these HTML JavaScript CSS

Some picture Like Output

Screenshot (135).png

Open Website

1.png
If you say the word "invest", the background color will change every time.

Screenshot (134).png

If you say the word "calculator", the calculator will start showing on the left side.
2.png
If you say the word "Aftab 9", the percentage will increase to five percent.

4.png

Similarly, if you say the word S1, the percentage will be reduced to two percent, and the percentage will be calculated accordingly.

5.png

End

You don't have to read below because I have uploaded the complete source code of this website below so that you can copy it, change it, or compile it and see what it looks like.

Complete one page code

<!DOCTYPE html>
html lang="en">
<head>
  html charset="UTF-8">
  html name="viewport" content="width=device-width, initial-scale=1.0">
  title>Earn Daily Returns</title>
  <style
    body {
      margin: 0;
      font-family: Arial, sans-serif;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      transition: background-color 0.5s ease;
      background-color: #1c1c1c;
      color: white;
      overflow: hidden;
      position: relative;
    }

    .container {
      text-align: center;
      max-width: 600px;
      padding: 20px;
      background-color: rgba(0, 0, 0, 0.8);
      border-radius: 15px;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
    }

    h1 {
      font-size: 2.5em;
      color: #ff8c00;
      margin-bottom: 20px;
    }

    p {
      font-size: 1.2em;
      color: #dcdcdc;
      margin-bottom: 20px;
    }

    .cta-button {
      background-color: #ff8c00;
      color: white;
      padding: 15px 30px;
      font-size: 1.5em;
      border: none;
      border-radius: 10px;
      cursor: pointer;
      transition: background-color 0.3s ease;
      margin-top: 20px;
    }

    .cta-button:hover {
      background-color: #ff6000;
    }

    .cta-button:active {
      transform: scale(0.98);
    }

    .calculator {
      margin-top: 30px;
      text-align: center;
      display: none; /* Initially hide the calculator */
      position: absolute;
      left: 10px; /* Position the calculator on the left side */
      top: 50%;
      transform: translateY(-50%);
      background-color: rgba(0, 0, 0, 0.8);
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
    }

    .calculator input {
      padding: 10px;
      font-size: 1em;
      border: 1px solid #ff8c00;
      border-radius: 5px;
      width: 100px;
      margin-bottom: 10px;
    }

    .calculator button {
      background-color: #ff8c00;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 1em;
    }

    .calculator button:hover {
      background-color: #ff6000;
    }

    .result {
      margin-top: 15px;
      font-size: 1.2em;
      color: #ff8c00;
    }

    .footer {
      font-size: 0.9em;
      color: #dcdcdc;
      margin-top: 20px;
    }

    .footer a {
      color: #ff8c00;
      text-decoration: none;
    }

    .footer a:hover {
      text-decoration: underline;
    }

    .alert {
      font-size: 1em;
      margin-top: 20px;
      padding: 10px 20px;
      background-color: rgba(255, 140, 0, 0.1);
      border: 1px solid #ff8c00;
      border-radius: 10px;
      color: #ff8c00;
    }

    .time-display {
      position: absolute;
      top: 10px;
      right: 20px;
      font-size: 1.5em;
      color: #ff8c00;
      display: none;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1 id="header">Earn Daily Returns 1.1%</h1>
    <p id="introText">Invest and grow your wealth. Say "Invest" to experience dynamic features!</p>

    <div class="calculator" id="calculator">
      <h2>Investment Calculator</h2>
      <input type="number" id="investment" placeholder="Enter Amount" />
      <button onclick="calculate()">Calculate</button>
      <div id="result" class="result"></div>
    </div>

    <div id="status" class="alert" aria-live="polite">Listening for voice commands...</div>

    <div class="footer">
      <p>By proceeding, you agree to our <a href="#">Terms & Conditions</a>.</p>
    </div>
  </div>

  (html comment removed:  Time display )
  <div class="time-display" id="timeDisplay"></div>

  <script>
    // Function to toggle visibility of the introductory text
    function toggleVisibility() {
      const introText = document.getElementById("introText");
      if (introText.style.display === "none") {
        introText.style.display = "block";
      } else {
        introText.style.display = "none";
      }
    }

    // Function to show the calculator
    function showCalculator() {
      const calculator = document.getElementById("calculator");
      calculator.style.display = "block"; // Show the calculator
    }

    // Function to hide the calculator



    function hideCalculator() {
      const calculator = document.getElementById("calculator");
      calculator.style.display = "none"; // Hide the calculator
    }

    // Function to generate random background color
    function getRandomColor() {
      const letters = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }

    // Initialize Speech Recognition API
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    const statusDiv = document.getElementById("status");
    const timeDisplay = document.getElementById("timeDisplay");
    let dailyRate = 1.1; // Default daily rate

    if (SpeechRecognition) {
      const recognition = new SpeechRecognition();
      recognition.continuous = true;
      recognition.lang = "en-US";

      // Start listening for voice input
      recognition.onresult = function (event) {
        const transcript = event.results[event.results.length - 1][0].transcript.toLowerCase();
        console.log("Heard:", transcript);

        // If the word "invest" or "investment" is spoken, change the background color
        if (transcript.includes("invest") || transcript.includes("investment")) {
          const newColor = getRandomColor();
          document.body.style.backgroundColor = newColor;
          statusDiv.textContent = "Background color changed.";
        }

        // If the word "show public" is spoken
        if (transcript.includes("show public")) {
          toggleVisibility(); // Hide intro text if "show public" is heard
          statusDiv.textContent = "Voice command: 'Show Public' received.";
        }

        // If the word "hide public" is spoken
        if (transcript.includes("hide public")) {
          toggleVisibility(); // Hide intro text if "hide public" is heard
          statusDiv.textContent = "Voice command: 'Hide Public' received.";
        }

        // If the word "calculator" is spoken, show the calculator
        if (transcript.includes("calculator")) {
          showCalculator(); // Show the calculator
          statusDiv.textContent = "Voice command: 'Calculator' received. Showing calculator.";
        }

        // If the word "hide calculator" is spoken, hide the calculator
        if (transcript.includes("hide calculator")) {
          hideCalculator(); // Hide the calculator
          statusDiv.textContent = "Voice command: 'Hide Calculator' received. Hiding calculator.";
        }

        // If the word "S1" is spoken, update the daily return and top header
        if (transcript.includes("s1")) {
          dailyRate = 2.0; // Set the daily rate to 2%
          document.getElementById("header").textContent = "Earn Daily Returns 2%"; // Update the header
          statusDiv.textContent = "Voice command: 'S1' received. Daily return set to 2%.";
        }

        // If the word "Aftab 9" is spoken, set the daily rate to 5%
        if (transcript.includes("aftab 9")) {
          dailyRate = 5.0; // Set the daily rate to 5%
          document.getElementById("header").textContent = "Earn Daily Returns 5%"; // Update the header
          statusDiv.textContent = "Voice command: 'Aftab 9' received. Daily return set to 5%.";
        }

        // If the word "Simple" is spoken, set the daily rate to 1%
        if (transcript.includes("simple")) {
          dailyRate = 1.0; // Set the daily rate to 1%
          document.getElementById("header").textContent = "Earn Daily Returns 1%"; // Update the header
          statusDiv.textContent = "Voice command: 'Simple' received. Daily return set to 1%.";
        }

        // If the word "Naeem 7" is spoken, set the daily rate to 3%
        if (transcript.includes("naeem 7")) {
          dailyRate = 3.0; // Set the daily rate to 3%
          document.getElementById("header").textContent = "Earn Daily Returns 3%"; // Update the header
          statusDiv.textContent = "Voice command: 'Naeem 7' received. Daily return set to 3%.";
        }

        // If the word "time" is spoken, show the time on the right top
        if (transcript.includes("time")) {
          showTime(); // Display the time
          statusDiv.textContent = "Voice command: 'Time' received. Showing time.";
        }
      };

      recognition.onerror = function (event) {
        console.error("Speech recognition error:", event.error);
        statusDiv.textContent = "An error occurred while listening.";
      };

      recognition.start();
    } else {
      statusDiv.textContent = "Speech Recognition API is not supported in this browser.";
    }

    // Function to show current time in the user's local time zone
    function showTime() {
      const time = new Date();
      const options = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true };
      const timeString = time.toLocaleTimeString(undefined, options); // Get local time based on user's location
      timeDisplay.textContent = `Time: ${timeString}`;
      timeDisplay.style.display = 'block'; // Show the time
    }

    // Calculator logic
    function calculate() {
      const investment = parseFloat(document.getElementById("investment").value);
      if (isNaN(investment) || investment <= 0) {
        document.getElementById("result").textContent = "Please enter a valid investment amount.";
        return;
      }
      const dailyProfit = (investment * (dailyRate / 100)).toFixed(2);
      const monthlyProfit = (investment + investment * (dailyRate / 100) * 30).toFixed(2);

      document.getElementById("result").innerHTML = `Daily Profit: $${dailyProfit}<br>Total in 30 Days: $${monthlyProfit}`;
    }
  </script>
</body>
</html>

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!