Event listener not responding

Hi , on clicking the button the event listener is not showing any log.
Here is the code -

canvas = document.getElementById(“mycanvas”);
function f(){
console.log(“You clicked on the canvas”);
}

canvas.addEventListener(‘click’,f);

function f2() {
console.log(“A key was pressed”,e);
}

canvas.addEventListener(“keydown”,f2);

You need to place this code in window.onload callback function. Most probably, at the time of execution of your current code, the element mycanvas is not rendered, thus nothing happens. Placing it in window.onload callback ensures that code runs after all the elements are loaded in the DOM.

@rijulsingh1 see the above answer

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.