Please help in explaining why the click event handler is executed before the script is finished executing.
console.log('Script started running')
document.body.addEventListener('click', () => {
console.log('Click callback executed')
})
console.log('Before click')
document.body.click()
console.log('After click')
My expectation was
Script started running
Before click
After click
Click callback executed
But the output observed on running is
Script started running
Before click
Click callback executed
After click
Should the script not be executed fully(call stack made empty) before any event callback from the task queue is executed ?
The HTMLElement.click() method simulates a mouse click on an element.
The handler has to be executed immediately before continuing the script.
If you were to remove this line and click manually, you would get your desired result.
console.log('Script started running')
document.getElementById('button').addEventListener('click', () => {
console.log('Click callback executed')
})
console.log('Before click')
//document.body.click()
console.log('After click')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id='button'>Click me</button>
</body>
</html>