Where is the Javascript "trigger"?

Joined
Aug 16, 2022
Messages
57
Reaction score
2
Hi Everybody,

I have attached a short code block below.
What I want to know is: Where in this code is a "trigger" that causes the Javascript snippet
to execute?


HTML:
<!DOCTYPE HTML>
<html lang="en">
<head>
</head>
<body>
    <input type="password" placeholder="Enter Your Password" id="PW1" name="PW1" required="required">
    <br>
    <input type="password" placeholder="Enter Your Password Again to Confirm" id="PW2" name="PW2" required="required"><br>
<!--Insert a script to evaluate "what to do" if PW1 is equal/unequal to PW2-->
<script>
    // Find input elements with the ID (PW1, PW2)
    const pw1 = document.querySelector('#PW1'),
                pw2 = document.querySelector('#PW2');
    let isPasswordsMatch = false; // variable called flag
    // Use for both event: input
    pw1.addEventListener('input', checkPasswordEquality);
    pw2.addEventListener('input', checkPasswordEquality);

    function checkPasswordEquality() {
    // Remove leading and trailing whitespace from the password values
    const password1 = pw1.value.trim();
    const password2 = pw2.value.trim();

    if (password1.length && password2.length) {
        if (password1 === password2) {
        // Passwords are the same
            pw2.style.backgroundColor = '#00FF00';
            isPasswordsMatch = true;
            } else {
                // Passwords are different
                pw2.style.backgroundColor = '#FF0000';
                isPasswordsMatch = false;
            }
        } else {
            pw2.style.backgroundColor = '';
            pw2.value = '';
            isPasswordsMatch = false;
        }
    }
</script>
</body>
</html>




::::
 
Joined
Jul 4, 2023
Messages
545
Reaction score
71
This code is a "trigger",
JavaScript:
pw1.addEventListener('input', checkPasswordEquality);
pw2.addEventListener('input', checkPasswordEquality);
when you enter data into <input>

Check this out:
HTML:
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
      input[type="password"] {
        display: block;
        width: 20rem;
        height: 1.5rem;
        font: 700 2rem system-ui, monospace, sans-serif;
        padding-left: .5rem;
        padding-bottom: .65rem;
        box-sizing: border-box;
      }
      input::placeholder {
        font-size: 45%;
        transition: font-size 200ms ease-in;
      }
      input:focus::placeholder {
        font-size: 0;     
      }
      input + input {
        margin-top: .5rem;
      }
      #console {
        width: 50dvw;
        height: 8.5ch;
        font: 300 .9rem/1 system-ui, monospace, sans-serif;
        background-color: black;
        color: limegreen;
        padding: .5rem;
        overflow-y: auto;
      }
    </style>
  </head>
  <body>
    <input type="password"
           placeholder="Enter Your Password"
           id="PW1"
           name="PW1"
           required>
    <input type="password"
           placeholder="Enter Your Password Again to Confirm"
           id="PW2"
           name="PW2"
           required>

    <pre id="console"></pre>

    <!--Insert a script to evaluate "what to do" if PW1 is equal/unequal to PW2-->
    <script>
      // Find input elements with the ID (PW1, PW2)
      const pw1 = document.querySelector('#PW1'),
            pw2 = document.querySelector('#PW2');

      // Use for both event: input
      pw1.addEventListener('input', checkPasswordEquality);
      pw2.addEventListener('input', checkPasswordEquality);

      function checkPasswordEquality(e) {
        document.querySelector('#console')
        .innerHTML = `
         Now you are writing in:\n
         id: ${e.target.id}
         value: "${e.target.value}"
        `.trim();
      }
    </script>
  </body>
</html>

[ addEventListener() method ]
 
Last edited:
Joined
Jul 4, 2023
Messages
545
Reaction score
71
BTW,
IMO, it is better to use classList instead of inline styles.
HTML:
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
      input[type="password"] {
        display: block;
        width: 20rem;
        height: 1.5rem;
        font: 700 2rem system-ui, monospace, sans-serif;
        padding-left: .5rem;
        padding-bottom: .65rem;
        box-sizing: border-box;
      }
      input::placeholder {
        font-size: 45%;
        transition: font-size 200ms ease-in;
      }
      input:focus::placeholder {
        font-size: 0;     
      }
      input + input {
        margin-top: .5rem;
      }
      .passwords-matching {
        background-color: green;
      }
      .passwords-different {
        background-color: red;
      }


      #console {
        width: 50dvw;
        height: 10ch;
        font: 300 .9rem/1 system-ui, monospace, sans-serif;
        background-color: black;
        color: limegreen;
        padding: .5rem;
        overflow-y: auto;
      }
    </style>
  </head>
  <body>
    <input type="password"
           placeholder="Enter Your Password"
           id="PW1"
           name="PW1"
           required>
    <input type="password"
           placeholder="Enter Your Password Again to Confirm"
           id="PW2"
           name="PW2"
           required>

    <pre id="console"></pre>

    <!--Insert a script to evaluate "what to do" if PW1 is equal/unequal to PW2-->
    <script>
      // Find input elements with the ID (PW1, PW2)
      const password_input1 = document.querySelector('#PW1'),
            password_input2 = document.querySelector('#PW2');
      let isPasswordsMatch = false;

      // Use for both event: input
      password_input1.addEventListener('input', checkPasswordEquality);
      password_input2.addEventListener('input', checkPasswordEquality);

      // for demonstration purposes
      password_input1.addEventListener('focus', consoleLog);
      password_input2.addEventListener('focus', consoleLog);

      function checkPasswordEquality(e) {
        consoleLog(e); // for demonstration purposes

        const password1 = password_input1.value.trim(),
              password2 = password_input2.value.trim();

        if (password1 === password2 && password1.length) {
          // Passwords are the same
          password_input2.classList.add('passwords-matching');
          password_input2.classList.remove('passwords-different');
          isPasswordsMatch = true;
          consoleLog(e); // for demonstration purposes
          return;
        }

        if (password2.length) {
          // Passwords are different
          password_input2.classList.add('passwords-different');
          password_input2.classList.remove('passwords-matching');
          isPasswordsMatch = false;
          consoleLog(e); // for demonstration purposes
          return;
        }

        password_input2.classList.remove('passwords-matching', 'passwords-different');
        isPasswordsMatch = false;
      }

      function consoleLog(e) { // for demonstration purposes
        document.querySelector('#console')
          .innerHTML = `
         Now you are writing in:\n
         id: ${e.target.id}
         value: ${e.target.value}
         isPasswordsMatch: ${isPasswordsMatch}
        `.trim();     
      }
    </script>
  </body>
</html>
 
Joined
Aug 16, 2022
Messages
57
Reaction score
2
Thank you so much for your reply, VBService.

I have a quick question. You are using a console/ What purpose does that serve?
 
Joined
Jul 4, 2023
Messages
545
Reaction score
71
In the above examples I have used a fake console to demonstrate what is happening in the background to make it easier to understand what the JavaScript code is doing. ;)
 
Joined
Jul 4, 2023
Messages
545
Reaction score
71
Check out this version of fake console with auto-scroll. :cool:
HTML:
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
      #console {
        width: 60ch;
        height: 10ch;
        font: 300 .9rem/1 system-ui, monospace, sans-serif;
        background-color: black;
        color: limegreen;
        padding: .5rem;
        overflow-y: auto;
        scroll-behavior: smooth;
      }
    </style>
  </head>
  <body>

    <pre id="console"></pre>

    <script>
      window.onload = load;
     
      const pause = (m) => { return new Promise(resolve => setTimeout(() => { resolve(); }, m)) };
      const getRandomNumber = (min, max) => { return Math.floor(Math.random() * (max - min + 1)) + min };

      function getCurrentTime() {
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');

        return `${hours}:${minutes}:${seconds}`;
      }

      async function load() {
        for (let i=0; i<30; i++) { // simulation of 30 console entries
          const log = `[${getCurrentTime()}] ${'Lorem ipsum dolor sit amet consectetur adipiscing elit'.split(' ', getRandomNumber(2, 8)).join(' ')}.`;
          consoleLog(log);
          await pause(getRandomNumber(1000, 3000));
        }
      }

      function consoleLog(log) {
        const console_ = document.querySelector('#console');
        console_.innerHTML += log.trim() + '\n';
        console_.scrollTop = console_.scrollHeight; // auto-scroll
      }
    </script>
  </body>
</html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,109
Messages
2,570,670
Members
47,260
Latest member
MadelaineK

Latest Threads

Top