How JavaScript Interacts With HTML Documents

402 VIEWS

Want to know how JavaScript interacts with HTML documents? The simple answer is events.

Each time a user clicks on a button, submits a form, or enters a password on a webpage, what happens? An event occurs. Events are actions that occur in the web browser after a feedback. In JavaScript, we use event listeners to pick up these feedbacks. The feedbacks act as signals for the next activity to take place on the web page and JavaScript simply listens for these signals using an event listener or handlers. So what exactly are events? How do we fix them in our codes, and how do they work?

This article will cover events and types of events, which includes keyboard events, mouse events, and document events. We will also dive into event handlers and learn how to work with them.

Each time a user performs an activity on a webpage, actions occur. The activity of the user on the web page leads to alteration or modification of the webpage. The user’s activities could be scrolling, clicking, or typing. These activities cause actions that lead to alteration, and modification of the HTML document, hence, the webpage. The actions may help to:

  • Reload the webpage.
  • Present the user with the required information
  • Close the entire website
  • Redirect the user to another website
  • Change the website look

How does JavaScript know the right time to perform an action after a user’s activity? We shall get to know how these actions occur right on time. The alteration of the HTML document doesn’t just happen out of the blue, all by itself. The HTML document relies on some signals. These signals lead us to a very important concept in JavaScript known as events.

What Are Events?

Let’s use a simple example to describe events. When your body is tired, you probably sweat or become weak. In other words, you get signals to rest. That is just how events work. They act as signals. They send information from the HTML document to JavaScript. JavaScript waits and listens for those events to enable it to implement the next action. Events act as the middleman between the HTML document and JavaScript. They are how JavaScript interacts with HTML documents.

Types of Events

There are different types of events. We use different events for different purposes. We have keyboard events, mouse events, and document events.

Keyboard Events

These events fire once the user touches a key on the keyboard. We have the keydown and the keyup type of keyboard events. 

  • The keydown event sends signals from the key on a keyboard to JavaScript when a user presses it down.
  • The keyup event sends signals to JavaScript once the user releases the key on the keyboard.
Mouse Events

These events fire once the mouse is in use. 

  • Mousemove event: Once the user moves the mouse cursor around an element, this event fires up. Any movement of the cursor on the screen of the user sends a signal and calls for action.
  • Mouseout: This event fires when the cursor is outside of an element. For example, a button could display a grey color when the cursor is right inside the borders of the button. But changes to black once the cursor is out of the button.
  • Mouseover: This fires when the mouse cursor moves inside the boundaries of the element.
  • Click event: this fires up when the mouse clicks on an element.
  • Double click events: fires up when the mouse cursor clicks on an element twice.
Document Events
  • DOMContentLoaded: This event fires up and processes once a webpage refreshes or reloads.

Event Handlers

Event handlers are used to handle the user actions, and browser actions and also verify user input. They also help JavaScript to listen for events and call the next line of action. How do we assign event handlers? 

  1. We use an attribute to assign an event handler to an HTML element. This event handler fires up some activities each time an event occurs in that particular element. For example, we could call an alert action each time a user clicks on the button by using the event handler known as an onclick. Here is an example showing how we attached an event handler to an HTML element to listen for an event.
    <button onclick="alert('Welcome!')">Click here</button>

    Here is another example where an event handler defined in the HTML calls a function defined in a script:

    <!DOCTYPE html>
    <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">
        <link rel="stylesheet" href="index.css">
        <title>Document</title>
    </head>
    <body>
        
     
            <button onclick="action()">Click here</button>
     
        <script>
     
            function action(){
                alert('Hello');
            }
     
        </script>
    </body>
    </html>
  2. We use special methods to attach and detach an event handler. These special methods are:
    • addEventListener: Just as the name implies, we use this method to listen for an event and add an event handler. Here is the syntax below:
       document.addEventListener('click', action);
      Function action(){
      alert(“Hello world”)
      }

      In the above example, we listened for a click on the HTML document, and we called the function action.

    • removeEventListener: This method is similar to the addEventListener. But we use it to listen for events to remove the event handlers. Here is the syntax below:
      document.removeEventListener('click', action);

Based on what we have talked about so far, let us play with the event concept using an event handler. So we can see how it works, where we can fix events in our codes, and how they cause JavaScript to interact with HTML.

Let’s create a button that changes its entire webpage to blue, and we will listen for a click.

<!DOCTYPE html>
<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">
    <link rel="stylesheet" href="index.css">
    <title>Document</title>
</head>
<body>
    
 
        <button class="btn">Click here</button>
 
    <script>
        // Access the button and add an event listener
    let btn = document.querySelector('.btn').addEventListener('click', action);
 
        // Declare the function
     function action(){
        document.body.style.backgroundColor = 'blue';
     }
 
    
    </script>
</body>
</html>

Now that you know the basics of how JavaScript interacts with HTML documents, do you want to learn more about how to manipulate HTML documents? Take a look at this article: Understanding the JavaScript DOM Manipulations.


Faith Njah is a front-end developer, with experience in building dynamic websites using web technologies like HTML, CSS, JavaScript, and A-frame VR. She is also passionate about learning.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published.

Menu
Skip to toolbar