Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to call javascript function in a tag

Which of the following ways is a better way to call a js function from an a tag?

<a href="javascript:someFunction()">LINK</a> 

OR

<a href="#" onclick="someFunction();" return false;">LINK</a> 

I have seen this question here, but it says <span onclick="someFunction()"> is a better option. But due to some reasons I have to use <a> links.

EDIT: I am looking for a cross browser & cross platform solution which should work on androids & iPads too.

like image 827
gopi1410 Avatar asked Jun 04 '12 07:06

gopi1410


People also ask

How do you call a function inside a script tag?

Calling a function using external JavaScript file Js) extension. Once the JavaScript file is created, we need to create a simple HTML document. To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.

Can you call a JS function in HTML?

The first method is to call the JavaScript function in HTML. For this, you have to create a function then define this function either in the head section or body section of the HTML document. You can either create a link or a button and then an onclick() event is associated with them in order to call this function.

What are 2 ways to call a JavaScript function?

Calling a Function through call() and apply() While working with JavaScript functions you've to keep in mind that the functions can have their own properties and methods and call() and apply() being the two of such methods.


1 Answers

Neither is good.

Behaviour should be configured independent of the actual markup. For instance, in jQuery you might do something like

$('#the-element').click(function () { /* perform action here */ }); 

in a separate <script> block.

The advantage of this is that it

  1. Separates markup and behaviour in the same way that CSS separates markup and style
  2. Centralises configuration (this is somewhat a corollary of 1).
  3. Is trivially extensible to include more than one argument using jQuery’s powerful selector syntax

Furthermore, it degrades gracefully (but so would using the onclick event) since you can provide the link tags with a href in case the user doesn’t have JavaScript enabled.

Of course, these arguments still count if you’re not using jQuery or another JavaScript library (but why do that?).

like image 146
Konrad Rudolph Avatar answered Sep 19 '22 18:09

Konrad Rudolph