Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;  } 
like image 667
Toniq Avatar asked Feb 24 '14 23:02

Toniq


People also ask

How do you write an inline function in JavaScript?

var func = function() { //Your Code Here }; Explanation: Making an inline function is really simple. First, make an anonymous function(a function with no name), and then assign it to a variable.

What is onclick JavaScript?

The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more. Using JavaScript, this event can be dynamically added to any element.

How do you call an inline function in HTML?

Inline JavaScript can be achieved by using Script tag inside the body of the HTML, and instead of specifying the source(src=”…”) of the JavaScript file in the Script tag, we have to write all the JavaScript code inside the Script tag.

Can we use Onclick in anchor tag?

It is safe to click on that link with # href; the page does leave/reload url. Follow the above advice with caution, as HTML5 rules explicitly state that href="#" is supposed to navigate to the top of the page. You can simply add the href attibute without content, and get the click behaviour.


2 Answers

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

like image 133
Mukund Kumar Avatar answered Sep 21 '22 10:09

Mukund Kumar


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

like image 39
ITomas Avatar answered Sep 17 '22 10:09

ITomas