Handling with object method

Every element in the DOM contains some methods like onclick, ondrag, onkeypress, etc. which can be used to handle the event. You can pass a function to this method which takes the event object a parameter.

Syntax:

element.onclick = (event)=>{
    ...
}

Example: let us add an object method to press me onclick button which prints ‘w3wiki’ in <h1>.

Javascript




<!DOCTYPE html>
<html>
 
<head>
    <title>EventHandlers</title>
</head>
 
<body>
    <div class="buttons">
        <button>Press me onclick</button>
    </div>
    <script>
        const buttonContainer = document.querySelector('.buttons');
        buttonContainer.onclick = () => {
            document.write("<h1>w3wiki</h1>");
        }
    </script>
</body>
 
</html>


Output:

Explain about EventHandler with Example

Event handlers are the properties in the browser or DOM API that handles the response to an event. Let us understand this with an example when we click on any virtual button of the browser a particular task gets executed for us, and eventually, the browser responds to your trigger with some result, or when you hover on a browser component it gets disguised by changing its display properties. This happens with event handlers. Event handlers help you to reflect on an event occurrence.

Similar Reads

Different ways of handling an event in Javacript

There are three ways of handling an event or you can say that there are three types of event handlers...

Handling with addEventListener

This is the best way to handle an event because you can also remove the associated handlers using the method removeEventListener....

Handling with object method

...

Handling with HTML inline attribute

Every element in the DOM contains some methods like onclick, ondrag, onkeypress, etc. which can be used to handle the event. You can pass a function to this method which takes the event object a parameter....