When to use onclick in HTML?

Hi

For a tag, you can execute javascript via href or onclick.

When should I use onclick instead of href?

for me, the only benefit I get from onclick is that you can hide the name and parameters of the javascript function from your visitors.

+1
source share
3 answers

Ideally, you will not use either. Ideally, your link is a normal hyperlink with a href value referring to a fragment ( #foo ) or URL. Ideally, the link would just work - without Javascript too.

Then you used unobtrusive Javascript , which, if necessary, is bound to links or other DOM elements, and only if Javascript is available:

 <a href="/some/action" id="foobar">Do some action!</a> <script type="text/javascript"> document.getElementById('foobar').addEventListener('click', function () { // do something }, false); </script> 
+5
source

Do not use either.

Write unobtrusive JavaScript .

+5
source

You need to click when you need to do more things than go to another page.

0
source

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


All Articles