Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using an argument in a function called by an event (onclick) using JavaScript

I'm trying to create an onclick event using JavaScript. I would like the onclick event to trigger a function. What I'm finding is that if I call the function without an argument or the parenthesis, the function is called when the element is clicked.

But if I try adding an argument to the function, the function is called immediately, before the element is even clicked.

What I've discovered is that if I use an anonymous function, and place the function that I want to be called by the onclick event within the anonymous function, it works!

I don't understand why. There has to be something about the logic that I'm missing.

I'm new to programming, and I would greatly appreciate any help in understanding why I can't simply call a function with an argument from an onclick event. Thanks

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");
    }
}
like image 625
Leisanne Avatar asked Feb 11 '26 07:02

Leisanne


1 Answers

If you're doing divSelect.onclick = addRed(divSelect); what's happening is that it calls addRed(divSelect), and sets the return value of that as the onclick. That's all fine if you actually return the function you want, but in most cases, it's not. That's why you need to wrap it in an anonymous function.

The other 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
like image 145
Scimonster Avatar answered Feb 13 '26 16:02

Scimonster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!