Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a variable inside onclick?

Tags:

javascript

How can I declare a var in JavaScript when someone clicks something and then a variable is declared, depending on what a function will return, which would be either a true or false value.

something like

onclick="var varable = somefunction(); "

I will then be compare the variable inside the onclick to then execute a function. So if that variable was true a function is executed, if it was false it will return.

How can both of these things be done in js?

like image 408
codrgi Avatar asked Oct 18 '25 14:10

codrgi


1 Answers

The problem is that by using var, that variable is locally scoped to that click handler and not to the global object, which is window. The easiest fix would be to directly set the value of the variable as a property on window:

onclick="window.varable = somefunction();"

Then you can access varable (sic) from other parts of the code.

That said, it's generally a bad idea to put application logic directly in onclick attributes.

like image 113
frontendbeauty Avatar answered Oct 21 '25 02:10

frontendbeauty