What is the difference between onclick and href = "javascript: function name?

Is there a difference between

1 : <a href="javascript:MyFunction()">Link1</a> 

and

 2 : <a href="#" onclick="MyFunction()">Link2</a> 

? Will it affect page performance in any way?

+4
source share
6 answers

If your element does not actually need to bind the user somewhere, do not make it a bind element. If you use the <a> tags just to get the underscore / cursor change, don't do this. Instead, use CSS in the <span> (or other element).

 span.link { text-decoration: underline; color: blue; cursor: pointer; } 

Keep your HTML semantics and use anchor elements only when you want to link the user somewhere.

+9
source

There is no difference in performance.

The first is shit, because it will not succeed for users without JS.

The second one is still crap, but it would be better if href provided a url for users without JS enabled.

+7
source

In the onclick version, you can pass 'this' as an argument so that you can return to the tag / object from which the click came. Impossible using protocol method:

 <a href="#" onclick="alert(this.innerHTML)">yo yo yo</a> 

pops up a popup warning "yo yo yo", whereas

 <a href="javascript:alert(this.innerHTML)">yo yo yo</a> 

spit out 'undefined'.

+4
source

A href = "javascript: doSomething" means that you do not have a URL to return if the user has not enabled js.

Therefore setting href = "something.html" and onclick = "return doSomething ()" is usually considered better, because if js is disabled, you can go to a new page, but if js is turned on, you can return false to prevent link navigation and displaying something on one page without refreshing the page.

Even better, don't add inline onclick, just add js handlers when the page loads. This is an unobtrusive way.

+1
source

There is a difference in functionality, the first one does not try to process the link. The second one does.

However, I agree with Coronatus - both methods are not ideal. I would suggest exploring unobtrusive JavaScript (possibly jQuery ), as you could dynamically add a click event to an element.

-1
source

If your site requires Javascript to work correctly, javascript in href is best because it shows the link in the status bar and keeps the code compact. Href also supports a keyboard without a mouse. If your site should function without Javascript, then you should use onclick so that href can have a link in it. Adding an action to a separate Javascript file does not allow you to tightly bind code and data.

-1
source

Source: https://habr.com/ru/post/1306037/


All Articles