Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to execute a function when user clicks on a link?

From my experience I know three different ways to execute a JavaScript function when a user clicks on a link

  1. Use the onclick attribute on the link

     <a href="#" onclick="myfunction();return false;">click me</a>
    
  2. Use the href on the link

     <a href="javascript:myfunction();">click me</a>
    
  3. Don't touch the link, do everything in js

     <a href="#">click me</a>
    

    (in the JavaScript we will stop the default event, and call the function)

Which one is better? What are the advantages and disadvantages?

EDIT deleted the "javascript:" on onclick

like image 262
pleasedontbelong Avatar asked Sep 17 '10 07:09

pleasedontbelong


People also ask

How do you call a function when a link is clicked?

Use the onclick HTML attribute. The onclick event handler captures a click event from the users' mouse button on the element to which the onclick attribute is applied. This action usually results in a call to a script method such as a JavaScript function [...]

Can I call a function in href?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).

Does Onclick work on link?

This is a type of JavaScript link - the onclick attribute defines a JavaScript action when the 'onclick' event for the link is triggered (i.e. when a user clicks the link) - and there is a URL present itself in the onclick attribute.

How do you automatically call a function in HTML?

To invoke this function in the html document, we have to create a simple button and using the onclick event attribute (which is an event handler) along with it, we can call the function by clicking on the button.


2 Answers

Unobtrusive Javascript (your third example) with graceful degredation is the best choice.

like image 168
Kevin Avatar answered Oct 07 '22 11:10

Kevin


It is always good to have a link in the href attribute so as to support users who have disabled JavaScript on their browsers.

<a href="http://www.mywebsite.com/javascriptdisabled.html" onclick="myfunction(); return false;">click me</a>
like image 3
Q_Mlilo Avatar answered Oct 07 '22 12:10

Q_Mlilo