JavaScript onclick function

Is there a way to write the following code in a line like this?

<a href="#" onClick="function(){ //do something; return false; };return false;"></a> 

Instead of this:

  <a href="#" onClick="doSomething(); return false;"></a> function doSomething(){ //do something; } 
+6
source share
3 answers

You can use self-signed anonymous functions. this code will work:

 <a href="#" onClick="(function(){ alert('Hey i am calling'); return false; })();return false;">click here</a> 

see jsfiddle

+12
source

This should work

  <a href="#" onclick="function hi(){alert('Hi!')};hi()">click</a> 

You can embed any javascript inside onclick, as if you were assigning a method via javascript. I think this is just a question of how to make the code cleaner by keeping your js inside a script block

+5
source

This is not recommended, but you can do it all like this:

 <a href="#" onClick="function test(){ /* Do something */ } test(); return false;"></a> 

But I can’t think of any situations where it would be better than writing a function elsewhere and calling it onClick .

+1
source

All Articles