2
I took this example below the book "Eloquent Javascript" 2nd edition in Portuguese pg.184.
The goal is to draw dots on the screen using clicks: every time the mouse is clicked, a blue dot is created where the mouse is pointing.
However, beyond the beige style that is applied to the background, nothing else happens. I’ve already checked for syntax errors and I can’t find anything... I tried to declare the style in the head, and it didn’t change anything either.
Follows the code:
<!DOCTYPE html>
<html>
<body>
<!-- Estilo do body, e da classe .dot-->
<style>
body {
height:200px;
background:beige;
}
.dot{
height:8px; width:8px;
border-radius: 4px;
background: blue;
position:absolute;
}
</style>
<!-- Para obter informações precisas sobre o local onde aconteceu um evento do mouse você pode olhar para as
suas propriedades pageX e pageY , que contêm as coordenadas do evento(em pixels) em relação ao canto
superior esquerdo do documento. -->
<script>
addEventListener("click", function(event){
var dot = document.createElement("div");
dot.className("dot");
dot.style.left = (event.pageX -4) + "px";
dot.style.top = (event.pageY -4) + "px";
document.body.appendChild(dot);
});
</script>
</body>
</html>
Truth! classname is an element property...
– Lucas Pletsch
But I’m hearing "click"... in this snippet I mean this: "Document.getElementById('body'). addeventlistener("click", Function(Event)". It’s not?
– Lucas Pletsch
I just fixed the classname to ="dot" and it’s solved. Thanks!
– Lucas Pletsch
I didn’t know you could add an event listener to anything, answering and learning
– Costamilam
realized now that by default adding an eventListener to "anyone", it will be added to the body...
– Lucas Pletsch
Or maybe it is added to the html element within which the script is inserted.... You will know.
– Lucas Pletsch
you can test by taking the tag
<body>
, if it still works means that the event is not added to that specific tag, but I believe that when it is not specified, all tags receive the event listener, I’m not sure of that, but if it is true it is something bad, since it spends a lot of resources adding where it doesn’t need to and unwanted effects can occur (creating points where it shouldn’t)– Costamilam
Even without the <body> tag it works.
– Lucas Pletsch
According to the same book "Eloquent Javascritp", when we add an eventListener to no object, it is the DOM window object that receives it. That is, the parent object of everything we include on the screen... of all tags is not?
– Lucas Pletsch
I wouldn’t know how to answer that, if you already have a question related to that, you can create one to talk about "adding event listeners to nothing"
– Costamilam