3

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");
    }
}
1
  • sidenote: how many elements with class="basic" do you have? Cause if that's more than one, this is not gonna work very well.. Instead of addRed(divSelect), try using addRed(this) (as a general rule). Commented Oct 23, 2014 at 17:47

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I'm returning the value. So I'm actually really running the function before the event occurs, right? I want to to execute upon the onclick. I'm going to investigate further into when to add the parenthesis and when to leave them off. Thanks so much!
Yeah, you're running the function immediately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.