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; }
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With