Inline JavaScript onclick function

JavascriptOnclick

Javascript Problem Overview


Is there a way to write following code inline like so?

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

Instead of doing this:

 <a href="#" onClick="doSomething(); return false;"></a>

 function doSomething(){
    //do something;
 }

Javascript Solutions


Solution 1 - Javascript

you can use Self-Executing Anonymous Functions. this code will work:

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

see JSfiddle

Solution 2 - Javascript

This should work

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

You may inline any javascript inside the onclick as if you were assigning the method through javascript. I think is just a matter of making code cleaner keeping your js inside a script block

Solution 3 - Javascript

This isn't really recommended, but you can do it all inline like so:

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

But I can't think of any situations off hand where this would be better than writing the function somewhere else and invoking it onClick.

Solution 4 - Javascript

Based on the answer that @Mukund Kumar gave here's a version that passes the event argument to the anonymous function:

<a href="#" onClick="(function(e){
    console.log(e);
    alert('Hey i am calling');
    return false;
})(arguments[0]);return false;">click here</a>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionToniqView Question on Stackoverflow
Solution 1 - JavascriptMukund KumarView Answer on Stackoverflow
Solution 2 - JavascriptITomasView Answer on Stackoverflow
Solution 3 - JavascriptjvdubView Answer on Stackoverflow
Solution 4 - JavascriptKarloXView Answer on Stackoverflow