'Attaching listeners to body doesn't work?
I can't figure out why this piece of code isn't working:
<!DOCTYPE html>
<html><head></head><body onload="
document.body.addEventListener('mousedown',function(e){
alert(123);
},false);
"></body></html>
There isn't even any error whatsoever.. it just does nothing.
amazingly if I change 'mousedown' to 'keydown' it works
<!DOCTYPE html>
<html><head></head><body onload="
document.body.addEventListener('keydown',function(e){
alert(123);
},false);
"></body></html>
(I'm using Chrome btw)
Solution 1:[1]
Notice that I added some content and added a border to body so that you can see its dimensions. If you remove the content, everything you see is a black line. body does not take up any space if there is no content (like any other block element) which implies you cannot click inside of it.
It seems you thought that body would spread across the whole browser window, but that is not the case.
If you attach the handler to window instead, it gets all events that happen inside the visible area.
Solution 2:[2]
An alternative is to use jQuery bind. It does not only make you code less but is also supported by most browsers. Try this one:
$('body').bind('click mousedown', function() {
alert(123);
});
Solution 3:[3]
Try using the global window object instead:
<!DOCTYPE html>
<html><head></head><body onload="
window.addEventListener('click',function(e){
alert(123);
},false);
"></body></html>
For the given HTML, the body has no height and width, so it will not receive any mouse events when you click on the window. It still can receive key events though. If you give it a height and width, it will work.
<!DOCTYPE html>
<html><head></head><body style="height:1000px; width:1000px" onload="
document.body.addEventListener('mousedown',function(e){
alert(123);
},false);
"></body></html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jhourlad Estrella |
| Solution 3 |
