Event Handling
Event Handling
Event handling refers to the process of responding to and managing events that
occur during the execution of a program, often within a graphical user interface
(GUI) or other interactive system. Events can be user actions (like clicks, key
presses, or mouse movements) or system-generated notifications (like a timer tick
or an incoming network message). Event handling involves detecting these events
and executing predefined actions (event handlers) in response.
import tkinter as tk
def on_button_click():
print("Button clicked!")
root = tk.Tk()
button = tk.Button(root, text="Click Me", command=on_button_click)
button.pack()
root.mainloop()
1|Page
EVENT HANDLING
3. Java (Swing for GUI)
import javax.swing.*;
import java.awt.event.*;
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
frame.add(button);
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Real-World Applications
When discussing event handling, Host Objects play a critical role because they
provide the necessary objects and mechanisms for managing events. In a browser
environment, for example, the Window, Document, and Element objects are
central to event handling.
2|Page
EVENT HANDLING
Key Host Objects in Event Handling
1. Window
Example:
window.addEventListener('resize', () => {
console.log('The window was resized.');
});
2. Document
Example:
document.addEventListener('DOMContentLoaded', () => {
console.log('Document is fully loaded.');
});
3. Element
Example:
1. Event Listeners Host objects like Window, Document, and Element provide
methods such as addEventListener and removeEventListener to attach and
detach event handlers.
Example:
3|Page
EVENT HANDLING
const div = document.querySelector('div');
div.addEventListener('mouseover', () => {
console.log('Mouse over the div!');
});
Capture Phase: The event starts from the Window and descends to the target
element.
Target Phase: The event is processed at the target element.
Bubble Phase: The event ascends back to the Window.
Example:
document.body.addEventListener('click', () => {
console.log('Body clicked!');
}, true); // Capturing phase
Event Object Host objects pass an event object to the handler, containing details
about the event.
Example:
Window
o resize, scroll, load, beforeunload, error
Document
o DOMContentLoaded, visibilitychange
Element
o click, dblclick, mouseover, keyup, change
Special Considerations
4|Page