Using an argument in an event called function (onclick) using JavaScript

I am trying to create an onclick event using JavaScript. I would like the onclick event to trigger a function. I find that if I call a function with no argument or parenthesis, the function is called when the element is clicked.

But if I try to add a function argument, the function is called immediately before the element is clicked.

I found that if I use an anonymous function and put the function I want to call on the onclick event in the anonymous function, it works!

I do not understand why. There must be some logic I am missing.

I am new to programming and I would really appreciate any help in understanding why I can't just call the function with an argument from the onclick event. Thanks to

Here is the code I have that works

window.onload = init;

function init() {
    var divSelect = document.querySelector(".basic");
    divSelect.onclick = function () {addRed(divSelect)};

}

function addRed(el) {
    var divClass = el.getAttribute("class");

    if (divClass == "basic red") {
        el.setAttribute("class", "basic");
    }
    else {

        el.setAttribute("class", "basic red");
    }
}

      

+3


source to share


1 answer


If you do divSelect.onclick = addRed(divSelect);

what happens, it calls addRed(divSelect)

and sets the return value of this parameter to onclick

. This is all fine if you actually return the function you want, but most of the time it isn't. This is why you need to wrap it with an anonymous function.

Another option is to use Function.bind()

:



divSelect.onclick = addRed.bind( // bind a context and pre-fill arguments
    divSelect, // the context, can be anything in this case
    divSelect); // the pre-filled argument

      

+2


source







All Articles