daveb
daveb

Reputation: 76171

Is it possible to detect that your javascript code is executing because of an event?

If you don't control the invocation of your code, but would like to know if it's being executed by an event handler, is this possible?

Upvotes: 2

Views: 269

Answers (4)

Sarel Botha
Sarel Botha

Reputation: 12700

You could maybe do this if you had a way to look up the stack, but that's not a very good way to do it. This article shows how to access the stack.

A Javascript stacktrace in any browser

Upvotes: 0

BoltBait
BoltBait

Reputation: 11489

Um...

There's really only 3 places to put javascript (that I know of): 1) inside of script tags directly, 2) inside of a function inside of a script tag, and 3) in a link or event directly (like... onClick="", etc.).

In the case of (1) it executes as soon as loaded by the browser and in this case it wouldn't really be invocated by an event. But, in all other cases, the only way to get the code to execute is because of an event.

So, it seems to me that it is pretty easy to know if your code was executed because of an event...

Now, if you want to know the specific event handler that is executing your code, that is another matter. :D

Upvotes: 0

shahkalpesh
shahkalpesh

Reputation: 33476

Javascript has event object that can help you identify the source of the event.

Upvotes: 3

sblundy
sblundy

Reputation: 61414

You could have it signal by modifying a global variable. For debugging purposes, there's an alert.

Upvotes: 0

Related Questions