I am in the process of changing some of my code from onClick to addEventListener because of the various benefits I have read about and for the purpose of separation of concerns. One of the problems I have run into however is that whereas with onClick, I was able to call a function and pass a parameter, I am now finding that if I attempt to pass a parameter when using addEventListener, the function is immediately carried out using the given parameter.
<!-- Choose Branch and Open Menu -->
<script type="text/javascript">
document.getElementById('BranchOne').addEventListener("click", setBranch("BranchOne"));
document.getElementById('BranchOne').addEventListener("click", CategoryMenu);
document.getElementById('BranchTwo').addEventListener("click", setBranch("BranchTwo"));
document.getElementById('BranchTwo').addEventListener("click", CategoryMenu);
document.getElementById('BranchThree').addEventListener("click", setBranch("BranchThree"));
document.getElementById('BranchThree').addEventListener("click", CategoryMenu);
document.getElementById('BranchFour').addEventListener("click", setBranch("BranchFour"));
document.getElementById('BranchFour').addEventListener("click", CategoryMenu);
function CategoryMenu() {
document.getElementById('CategoryMenu').style.display = "block";
}
</script>
I have taken instead to setting the branches by having two separate addEventListeners, one of which carries out the CategoryMenu function and one of which sets the branch in an external JS file, however, I now find that it seems to carry out all of these functions one after another and the branch always ends up being the final one in the series (BranchFour). Originally the Branch was taken as a parameter of CategoryMenu and then set in the external JS file using the CategoryMenu method.
So to recap on on my main questions:
-Why can I not seem to send a parameter inside of the addEventListener e.g.
document.getElementById('BranchFour').addEventListener("click", CategoryMenu(Branch));
function CategoryMenu(Branch) {
document.getElementById('CategoryMenu').style.display = "block";
}
</script>
and:
-Why when I click a div with specific ID (e.g. div with ID="BranchOne") does it carry out all of the different events one after the other rather than just the one which my ID pertains to?