How to Call Event Listener in JavaScript?

Learn how to call event listener in JavaScript using the addEventListener() method.

JavaScript Event Listener Example

In the following example, it will create three objects, one square box, and two buttons. One button will start listening to the event and another is to stop listening to the event.

Code for the HTML HEAD Part:

        width: 100px;
        height: 100px;
        background-color: #0f0;
    function listenEvent(eventObj, event, eventHandler) {
        if (eventObj.addEventListener) {
            eventObj.addEventListener(event, eventHandler,false);
        else if (eventObj.attachEvent) {
            event = "on" + event;
            eventObj.attachEvent(event, eventHandler);
        else {
            eventObj["on" + event] = eventHandler;
    function stopListening (eventObj,event,eventHandler) {
        if (eventObj.removeEventListener) {
        else if (eventObj.detachEvent) {
            event = "on" + event;
        else {
            eventObj["on" + event] = null;
    function startListening() {
        var box = document.getElementById("box");
    function stopClick() {
        var box = document.getElementById("box");
        stopListening(box,"click", clickBox);
    function clickBox() {
    listenEvent(window,"load",function() {
        var bttn1 = document.getElementById("start");
        var bttn2 = document.getElementById("stop");
        listenEvent(bttn2, "click", stopClick);

Code for HTML BODY Part:

<div id="box"><p>The Box</p></div>
<button id="start">Start Listening</button>
<button id="stop">Stop Listening</button>


As shown in the featured image of this article.

Leave a Comment