Why is the click event triggered automatically? JS
Faced with such a problem:
When you assign an event click
to an element when you open a web page, this same click is triggered automatically.
Another case, it happens that click
, assigned to a specific element, is triggered when you click anywhere in the document at all.
For example:
<div id="block"></div>
let block = document.querySelector('#block');
block.addEventListener('click', Test());
function Test() {
alert('Какое-то сообщение');
}
So, when the page loads, alert
will immediately work, without clicking on the block
element.
According to my observations, if the HTML elements on if there are several pages, then in this case click
will be triggered anywhere on the screen and call the corresponding function.
What is the problem, and how can it be solved?
3 answers
If you just want to call the Test function on the "click" event":
block.addEventListener("click", Test)
If you want to pass parameters to the Test function:
block.addEventListener("click", () => Test(arg1, arg2))
// или
block.addEventListener("click", function () { Test(arg1, arg2) })
Separately, it is worth noting that your function Test
does not look like a constructor, so it does not make much sense to call it with a capital letter.
You can certainly do this, but it will confuse other developers.
AddEventListener takes the function as the second argument, not the result of executing the function
const block = document.querySelector('#block');
block.addEventListener('click', test);
function test() {
console.log('Какое-то сообщение');
}
#block {
cursor: pointer;
display: inline-block;
}
<div id="block">Какой-то блок</div>
block.addEventListener('click', Test);
A Click assigned to a specific element is triggered when you click anywhere in the document at all
This is not included in the above code.