Simple parameter function doesn’t work as intended

Advertisements

So I got a simple script which allows me to show/hide my hamburger navigation.


document.getElementById("hamburger_menu").addEventListener("click", show);

    function show() {
        document.getElementById("navigation").classList.toggle("show");
    }

This script works perfectly fine. As I want to reuse the script to show my searchbar I decided to use parameters in my script. To make this happen I made my script like this:


    function show(target) {
        document.getElementById(target).classList.toggle("show");
    }

document.getElementById("hamburger_menu").addEventListener("click", show("navigation"));

But for some weird reason this script is completely broken. Any advice here?

>Solution :

The event handler for your click event can’t be a function call, it needs to be an actual function.
You could do an anonymous function like

document.getElementById("hamburger_menu").addEventListener('click', () => show("navigation"));

instead.

Leave a ReplyCancel reply