The addEventListener() method allows you to add an event to an HTML element in JavaScript.
Although the example used often shows this function being used to add a response of a ‘click’ event to a button, there is an easier way by using the ‘onclick’ property.
This is the typical way to use a button:
<button onclick="submit()">Submit</button>
However, if you are wanting to add or change the function that the button responds to, you can change it in JavaScript. These two codes are equivalent:
<html>
<body>
<button id="btn1" onclick='submit()'>Submit</button><br>
<p id="text"></p>
<script>
function submit(){
document.getElementById('text').innerHTML = "done".
}
</script>
</body>
</html>
<html>
<body>
<button id="btn1">Submit</button><br>
<p id="text"></p>
<script>
document.getElementById('btn1').addEventListener('click',submit);
function submit(){
document.getElementById('text').innerHTML = "done".
}
</script>
</body>
</html>
Leave a comment