Toniq
Toniq

Reputation: 5006

Inline JavaScript onclick function

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;
 }

Upvotes: 85

Views: 243323

Answers (5)

user21996978
user21996978

Reputation:

I know this thread is old, but I was looking for a solution to this today. When you're "inlining" JavaScript like below, don't include "function xx()" and such. See the below example. I tested it today, and it works perfectly without console errors or warnings.

Wanted to share a solution:

<a href="#" type="button" onClick="var myDiv = document.getElementById('myDIV'); if (myDiv.style.display === 'block') { myDiv.style.display = 'none'; } else { myDiv.style.display = 'block'; }">click</a>

In a standard HTML markup, the following would be a typical implementation of the "inlined JS" example above.

<body>
<a href="#" type="button" onclick="myFunction()">Try it</a>
...(this is where the rest of the html page content goes)....
<script>
function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
     x.style.display = "block";
  } else {
     x.style.display = "none";
  }
}
</script>
</body>

Upvotes: 1

ITomas
ITomas

Reputation: 839

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

Upvotes: 36

Mukund Kumar
Mukund Kumar

Reputation: 23211

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>

Upvotes: 137

KarloX
KarloX

Reputation: 987

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>

Upvotes: 17

jvdub
jvdub

Reputation: 927

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.

Upvotes: 13

Related Questions