I have a list of elements in my HTML that looks like this:
<div class='container'>
<div class="zone green"></div>
<div class="zone red"></div>
<div class="zone blue"></div>
<div class="zone yellow"></div>
<div class="zone purple"></div>
<div class="zone brown"></div>
<div class="zone green"></div>
<div class="zone red"></div>
<div class="zone blue"></div>
<div class="zone yellow"></div>
<div class="zone purple"></div>
<div class="zone brown"></div>
<script type="text/javascript" src="script.js"></script>
</div>
And I was trying to make it so that every element I clicked on would log to the console the animal in the element. This was my attempt:
const selection = document.querySelectorAll(".zone");
selection.forEach(element => {
element.addEventListener('click', pickSelection(element))
})
function pickSelection(animal) {
console.log(animal.textContent)
}
But it was not returning anything when I clicked on any of the elements. However, once I changed the eventListener to this, it started working:
selection.forEach(element => {
element.addEventListener('click', () => pickSelection(element))
})
Why does it work in the second version of the code and not the first? In the first version, I thought I am passing the element argument to the pickSelection function by writing "pickSelection(element)", but apparently it only works if there is "() =>" in front of it, but what is the difference in this notation? Thanks.