0

I want something like this:

div.onclick = function(x, y);

How can I do this without executing the function?

I don't want to use jQuery.

4
  • just google addEventListener for it Commented Feb 15, 2017 at 16:19
  • Wrap the function call up in an anonymous function, or use bind Commented Feb 15, 2017 at 16:20
  • Is there nothing without using EventListeners? Commented Feb 15, 2017 at 16:21
  • stackoverflow.com/questions/6909988/… Commented Feb 15, 2017 at 16:35

3 Answers 3

1

Putting () after the function will call it. So don't do that.

div.onclick = function; // Note: function is a keyword and can't really be used as a variable name

That won't call the function with the arguments you want though. Event handler functions are always called with one argument: the event object.

You need to create a new function to call yours with those arguments.

function myhandler(event) {
    function(x, y); // Still not a valid name
}
div.onclick = myhandler;
Sign up to request clarification or add additional context in comments.

Comments

0
var NewFunction = function(x){
// your function code
};
div.onclick = NewFunction;

4 Comments

I need those parameters in these brackets
When NewFunction is called, it will be passed one argument (the event object) but you've written it to expect two arguments. Function names starting with capital letters are traditionally reserved for constructor functions in JavaScript, and this isn't one.
@Progaros since "click" is a system generated event, the event details is automatically passed as the first parameter whenever it is triggered.
@Quentin correct. Edited accordingly. Maybe you can explain better to OPs comment. He probably wants to call something like, add(a,b).on click.
0
var myFunction = function(x,y){
  //Some code here
};
div.onclick = function(){ return myFunction(x, y); }

In the second function assignment you ofcourse should replace x and y with something known to that context.

Comments

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.