Learn How To Listen: Event Listeners And Dynamic Websites

svper563

svper563

Posted on May 6, 2023

Learn How To Listen: Event Listeners And Dynamic Websites

It is an unspoken rule of the modern internet that your website is to be responsive, fluid, dynamic, and whatever other buzz words industry professionals happen to be tossing around today. Long gone are the days where static, un-styled text and images are sufficient to capture the attention of your audience. I know that when I come across such a static site myself, I click away fast as lighting out of fear of catching some kind of virus - after all, only hackers living in their parents' basement since 1987 would still host a site like that, right?

All jokes aside, a prominent tool in our belt as web developers is event listeners. They allow us to watch for specific user interactions and respond to them in ways that make our pages respond dynamically. In this article, I will explore some simple events that you can listen for that can take your next web application from zero to hero. Let's get started.

People Will Copy Your Code Eventually

As developers, we often scrape Stack Overflow to "borrow" code that fixes our problems, at least until the next bug starts bugging us. The next time that you post code to your oh-so-popular blog, try letting your visitors know that you know when they're borrowing your code:

index.html

<body>
  <div id='my-code-snippet'>
    <code>
      console.log("Hello, world!")
    </code>
  <div>
</body>

Enter fullscreen mode Exit fullscreen mode

script.js

let myCodeElement = document.getElementById('my-code-snippet');

myCodeElement.addEventListener("copy", () => {
    let warnElement = document.createElement('p');
    warnElement.innerHTML = "<em>I know what you did.</em>"
    myCodeElement.appendChild(warnElement)
})
Enter fullscreen mode Exit fullscreen mode

The HTML simply displays our brilliant code snippet for the world, and our Javascript does the job of watching for would-be-thieves.

Before copying:
Image description

After copying:
Image description

Of course, there are many ways to prevent your visitors from copying your code, but it is not best practice as it would most likely break the internet, which I'm sure is a less-than-desirable outcome. Let's avoid that.

Clap Back By Spying On Your Users

As honest programmers, we surely don't have any reason at all to watch our users' every move while they're on our sites. But, hypothetically speaking, there are ways to track every key press. Let's explore that.

document.addEventListener('keydown', (event) => {
    // Legitimate code goes here
})
Enter fullscreen mode Exit fullscreen mode

The keydown listener fires when your user presses down any key on their keyboard. The key property of the event object holds the value of the key pressed. The object also has many other properties that you can check. Let's say you want to make your own hot keys for your web application; you can do this easily by using the altKey and ctrlKey properties.

document.addEventListener('keydown', (event) => {
    if (event.altKey && event.ctrlKey && event.key === 'r') {
        // Your Hotkey action 
    }
})
Enter fullscreen mode Exit fullscreen mode

The altKey and ctrlKey properties each hold a boolean value indicated whether they were pressed at the time of the keypress.

If you need to listen for when a user releases a key, you can use the keyup listener instead.

There is also the keypress event as well, but it is only fired when a key that produces a character value is pressed down. As a result, this event cannot track when the Alt, Ctrl, or Shift keys are pressed. In addition to its limited functionality, there is a good shot that your user's browser of choice has dropped support for it, or will very soon.

Keep in mind that none of these events account for non-standard keyboard layouts by default. If your user is not using the standard QWERTY layout, it could cause some problems. For example, if your user is using the QWERTZ layout, pressing the 'Z' key on their keyboard will register as the 'Y' key instead. You can use the getLayoutMap() method to check for this and handle it accordingly.

When You're Found Out: Conducting Damage Control

When you're eventually caught for your supposedly "shady" coding practices, it's going to be important to know how to protect your image from the "honest" and "hardworking" people who want to destroy it. Remember: You cannot be exposed for misconduct if you expose yourself first. Let's add a modal popup to our site for new users that forces them to agree to our privacy policy before they can continue on our site. Let's use the click event listener to help us accomplish this.

index.html

<head>
  <style>
      body {
          background-color: #112;
          color: white;
      }

      #privacy-modal {
          visibility: hidden;
          position: absolute;
          padding: 20px;
          background-color: #334;
          border: 5px solid black;
      } 
  </style>
</head>

<body>
  <div id="privacy-modal">
      <h2>Before You Continue: Accept Our Privacy Policy</h2>
      <p>You must accept our privacy policy to continue on our website.</p>
      <h3>Privacy policy</h3>
      <p>Nothing is sacred. You will get hacked. You have been warned.</p>
      <button id="accept-terms-button">Accept</button>
      <button id="decline-terms-button">Decline</button>
    </div>
    <div id="content">
      // Legitimate content goes here
    </div>
</body>
Enter fullscreen mode Exit fullscreen mode

script.js

let privacyModal = document.getElementById('privacy-modal');
let acceptTermsButton = document.getElementById('accept-terms-button');
let declineTermsButton = document.getElementById('decline-terms-button');

if (!localStorage.getItem("hasAccepted")) {
    privacyModal.style.visibility = "visible";
    privacyModal.style.position = "fixed";
}

acceptTermsButton.addEventListener('click', () => {
    localStorage.setItem('hasAccepted', "true");
    privacyModal.style.visibility = "hidden";
    privacyModal.style.position = "absolute";
})

declineTermsButton.addEventListener('click', () => {
    window.location.replace('https://www.myspace.com')
})
Enter fullscreen mode Exit fullscreen mode

The first time that your users visit your wonderful and legitimate website, the privacy modal will overlay on top of the content, obscuring the page until they accept or decline. By clicking on the accept button, the code remembers the user choice by storing a truthy value in the localStorage attribute hasAccepted, and then hides the modal. Users who decline will be redirected immediately to the internet backrooms.

Now you know how to harvest your user's data openly and freely, just like every other legitimate tech company in the world.

Conclusion: I Am Not A Lawyer

I'm hoping that the technical aspects of this post can help you, but for legal purposes I am not endorsing that you steal data or hack other people. If you do hack and get caught, please don't email me at 3am complaining about it. Any other time of the day or night is acceptable.

Read more about event listeners on MDN's website.

💖 💪 🙅 🚩
svper563
svper563

Posted on May 6, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related