Event-based code in JavaScript executes functions when a specific event occurs, such as a click, hover, or key press. This is achieved using event listeners like onclick, onmouseover, and onkeydown. For example:
<button onclick=”alert(‘Button clicked!’)”>Click Me</button>
Here, when the button is clicked, an alert box appears. JavaScript’s addEventListener() method provides more control by allowing multiple event handlers:
document.getElementById(“myButton”).addEventListener(“click”, function() {
alert(“Event triggered!”);
})
Event-driven programming enhances interactivity and user experience on a webpage.