0

I want to create a div with an onclick event handler like

element.innerHTML = '<div onclick="somefunction(e, 10)"></div>';

where e would be the event object and 10 is some other random argument. I can't seem to find a way to do this. Is it possible?

Note that I do not want to create and then append the child to the parent element separately.

2
  • No. Quit those dirty in-line javascript hacks. Commented Nov 1, 2011 at 22:45
  • Yes (see answers). Do what is best for your situation. Commented Nov 1, 2011 at 23:32

1 Answer 1

2

For inline handlers like that you should be able to pass the event object directly if you spell it out in full rather than e (in your actual function definition you can call the corresponding parameter anything you like):

element.innerHTML = '<div onclick="somefunction(event, 10)"></div>';

For other event registration techniques there are other ways to get access to the event object, but inline is kind of a special case that should be the same in all browsers.

For more detail see this page: http://www.quirksmode.org/js/events_access.html

Sign up to request clarification or add additional context in comments.

1 Comment

It works because in browsers conforming to Netscape's event model (such as Mozilla and Firefox), event resolves to the handler's event object. In other browsers (like IE) event resolves to the global window.event object, which is essentially the same thing.

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.