Passing Data and Event Object

Passing Data and Event Object

Sep 12, 2025
240

image

Passing Data to Event Handlers

Sometimes you need to pass specific data to an event handler. When setting up event handlers using element attributes, this is pretty straightforward. For example, let’s pass some text to a button click handler:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Event Handler Example</title>
</head>
<body>
    <button id="btn" onclick="btn_click('Button Clicked')">Click Me</button>
    <script>
        // Text is passed to the handler
        function btn_click(text) {
            console.log(text); // Output the text
        }
    </script>
</body>
</html>

Here we’re passing text to the button handler:

<button id="btn" onclick="btn_click('Button Clicked')">

The handler function receives this text and uses it somehow, like logging it to the console:

function btn_click(text) {
    console.log(text); // Output the text
}

In this case we passed a string to the handler function, but in reality, it can be any object. For example, using the this keyword you can pass the current object where the event occurs:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Event Handler Example</title>
</head>
<body>
    <button id="btn" onclick="btn_click(this)">Click Me</button>
    <script>
        let clicks = 0; // Click counter
        
        // Button element reference is passed to handler
        function btn_click(btn) {
            // Change button text
            btn.textContent = `Clicked ${++clicks}`;
        }
    </script>
</body>
</html>

The this keyword refers to the current object being clicked. In the handler code we can get this object and access its properties, like the textContent property to change the button's text.

Returning false from Event Handlers

Sometimes we need to return false from an event handler. Consider this example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Event Handler Example</title>
</head>
<body>
    <a id="link" href="https://www.linkedin.com/in/alenibric" onclick="return a_click(this)">Alen IBRIC</a>
    <script>
        // Link reference is passed to handler
        function a_click(anchor) {
            // Get the link URL
            console.log(anchor.href);
            return false; // Prevent redirection
        }
    </script>
</body>
</html>

Here in the onclick attribute of the link element, we don't just call the event handler, but return its result:

<a id="link" href="https://www.linkedin.com/in/alenibric" onclick="return a_click(this)">

The handler function returns false:

function a_click(anchor) {
    console.log(anchor.href);
    return false; // Prevent redirection
}

For some handlers, you can confirm or stop event processing. For example, clicking a link should lead to redirection. But by returning false from the handler, we can stop the standard event processing path, and redirection won't happen.

If you return true, the event is processed in the standard way. If you don't return any result at all, the event will be processed as if you returned true:

<a id="link" href="https://www.linkedin.com/in/alenibric" onclick="a_click(this)">Alen IBRIC</a>
<script>
    function a_click(anchor) {
        console.log(anchor.href);
    }
</script>

The Event Object

When processing events, the browser automatically passes an Event object as a parameter to the handler function. This object encapsulates all information about the event. Using its properties, we can get this information:

  • bubbles: returns true if the event is bubbling. For example, if an event occurs on a nested element, it can be handled on the parent element.

  • cancelable: returns true if the default event processing can be canceled

  • currentTarget: defines the element to which the event handler is attached

  • defaultPrevented: returns true if the Event object's preventDefault() method was called

  • eventPhase: stores a number representing the event processing phase. Possible values:

  • 0 (Event.NONE)

  • 1 (Event.CAPTURING_PHASE)

  • 2 (Event.AT_TARGET)

  • 3 (Event.BUBBLING_PHASE)

  • target: points to the element on which the event was triggered

  • timeStamp: stores the time when the event occurred

  • type: indicates the event name

  • isTrusted: indicates whether the event was generated by web page elements or JavaScript code

Example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Event Object Example</title>
</head>
<body>
    <button onclick="btn_click(event)">Click Me</button>
    <script>
        function btn_click(e) {
            console.log(e);
        }
    </script>
</body>
</html>

When calling the handler function, event information is available through the event object. This object isn't defined by the developer - it's just a function argument that stores all event information:

<button onclick="btn_click(event)">

In JavaScript code, this object can be accessed through the function parameter:

function btn_click(e) {
    console.log(e);
}

Here we just log the object to console. But naturally, we could also get specific event information:

function btn_click(e) {
    console.log("Type:", e.type); // Type: click
    console.log("Target:", e.target); // Target: <button onclick="btn_click(event)">Click Me</button>
    console.log("Timestamp:", e.timeStamp);
}

Getting Event Object with Different Handler Attachment Methods

You can get the event object similarly when the event handler is attached through element properties or using the addEventListener() method.

Example with element property attachment:

<button id="btn">Click Me</button>
<script>
    function btn_click(e) {
        console.log("Type:", e.type);
        console.log("Target:", e.target);
        console.log("Timestamp:", e.timeStamp);
    }
    
    // Set click handler for element with id="btn"
    document.getElementById("btn").onclick = btn_click;
</script>

Or attaching handler using addEventListener method:

<button id="btn">Click Me</button>
<script>
    function btn_click(e) {
        console.log("Type:", e.type);
        console.log("Target:", e.target);
        console.log("Timestamp:", e.timeStamp);
    }
    
    const btn = document.getElementById("btn");
    // Attach "click" event handler
    btn.addEventListener("click", btn_click);
</script>

preventDefault() Method

Using the Event object’s preventDefault() method, we can stop further event execution. In many cases this method doesn't play a big role. However, in some situations it can be useful. For example, when clicking a link, we can use additional processing to determine whether to follow the link or prevent the navigation. Another example: a user submits form data, but during processing in the event handler we determine that form fields are filled incorrectly, and in this case we can also prevent submission.

Example of stopping link navigation:

<a id="link" href="https://www.linkedin.com/in/alenibric">Alen IBRIC</a>
<script>
    function linkHandler(e) {
        console.log("Link has been clicked");
        e.preventDefault(); // Stop link navigation
    }
    
    const link = document.getElementById("link");
    link.addEventListener("click", linkHandler);
</script>

Here, clicking the link will trigger the linkHandler method. Since we call e.preventDefault() in this method to prevent link navigation, no navigation will occur. This approach is often used with AJAX requests when you need to handle link clicks but not navigate to another resource - instead making a request from JavaScript code without page reload.

Using ‘this’ in Event Handlers

To get the current object for which the event is being processed, inside the event handler we can use the this keyword:

<button id="btn">Click Me</button>
<script>
    const btn = document.getElementById("btn");
    
    function btn_click() {
        console.log(this); // <button id="btn">Click Me</button>
    }
    
    btn.addEventListener("click", btn_click);
</script>

Here when processing the click event on the button, the this object in the btn_click function will represent this button. Actually, in this case the values of this and event.target would be equivalent:

function btn_click(e) {
    console.log(this === e.target); // true
}


Gefällt dir dieser Beitrag?

Kaufe DelphiFan Forum einen Kaffee

Mehr von DelphiFan Forum