Html link to javascript function

How to use a link to call JavaScript code?

asked Mar 27, 2009 at 1:33

0

<a onclick="jsfunction()" href="#">

or

<a onclick="jsfunction()" href="javascript:void(0);">

Edit:

The above response is really not a good solution, having learned a lot about JS since I initially posted. See EndangeredMassa's answer below for the better approach to solving this problem.

answered Mar 27, 2009 at 1:38

ChelseaChelsea

6,6715 gold badges28 silver badges31 bronze badges

6

Unobtrusive JavaScript, no library dependency:

<html>
<head>
    <script type="text/javascript">

        // Wait for the page to load first
        window.onload = function() {

          //Get a reference to the link on the page
          // with an id of "mylink"
          var a = document.getElementById("mylink");

          //Set code to run when the link is clicked
          // by assigning a function to "onclick"
          a.onclick = function() {

            // Your code here...

            //If you don't want the link to actually 
            // redirect the browser to another page,
            // "google.com" in our example here, then
            // return false at the end of this block.
            // Note that this also prevents event bubbling,
            // which is probably what we want here, but won't 
            // always be the case.
            return false;
          }
        }
    </script>
</head>
<body>
    <a id="mylink" href="http://www.google.com">linky</a>        
</body>
</html>

answered Mar 27, 2009 at 1:50

EndangeredMassaEndangeredMassa

17k8 gold badges53 silver badges79 bronze badges

12

<a href="javascript:alert('Hello!');">Clicky</a>

EDIT, years later: NO! Don't ever do this! I was young and stupid!

Edit, again: A couple people have asked why you shouldn't do this. There's a couple reasons:

  1. Presentation: HTML should focus on presentation. Putting JS in an HREF means that your HTML is now, kinda, dealing with business logic.

  2. Security: Javascript in your HTML like that violates Content Security Policy (CSP). Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware. Read more here.

  3. Accessibility: Anchor tags are for linking to other documents/pages/resources. If your link doesn't go anywhere, it should be a button. This makes it a lot easier for screen readers, braille terminals, etc, to determine what's going on, and give visually impaired users useful information.

answered Mar 27, 2009 at 1:35

Matt GrandeMatt Grande

11.7k6 gold badges60 silver badges88 bronze badges

5

And, why not unobtrusive with jQuery:

  $(function() {
    $("#unobtrusive").click(function(e) {
      e.preventDefault(); // if desired...
      // other methods to call...
    });
  });

HTML

<a id="unobtrusive" href="http://jquery.com">jquery</a>

answered Mar 27, 2009 at 1:54

Mister LuckyMister Lucky

4,0332 gold badges19 silver badges18 bronze badges

3

Unobtrusive Javascript has many many advantages, here are the steps it takes and why it's good to use.

  1. the link loads as normal:

    <a id="DaLink" href="http://host/toAnewPage.html">click here</a>

this is important becuase it will work for browsers with javascript not enabled, or if there is an error in the javascript code that doesn't work.

  1. javascript runs on page load:

     window.onload = function(){
            document.getElementById("DaLink").onclick = function(){
                   if(funcitonToCall()){
                       // most important step in this whole process
                       return false;
                   }
            }
     }
    
  2. if the javascript runs successfully, maybe loading the content in the current page with javascript, the return false cancels the link firing. in other words putting return false has the effect of disabling the link if the javascript ran successfully. While allowing it to run if the javascript does not, making a nice backup so your content gets displayed either way, for search engines and if your code breaks, or is viewed on an non-javascript system.

best book on the subject is "Dom Scription" by Jeremy Keith

Html link to javascript function

answered Mar 28, 2009 at 15:27

Fire CrowFire Crow

7,2594 gold badges35 silver badges35 bronze badges

I think you can use the onclick event, something like this:

<a onclick="jsFunction();">

answered Mar 27, 2009 at 1:36

Html link to javascript function

David ZDavid Z

124k26 gold badges249 silver badges275 bronze badges

Or, if you're using PrototypeJS

<script type="text/javascript>
  Event.observe( $('thelink'), 'click', function(event) {
      //do stuff

      Event.stop(event);
  }
</script>

<a href="#" id="thelink">This is the link</a>

answered Mar 27, 2009 at 1:43

Mark BiekMark Biek

143k54 gold badges155 silver badges200 bronze badges

3

You can use a button and style it like a link: HTML code:

button {
width:0.0000000001px;
height:0.00000000001px;
  background-color: #ffffff;
  color: Blue;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
}
<button  onclick="function()"><u>Example button</u></button>

answered Mar 9, 2021 at 21:31

based on @mister_lucky answer use with jquery:

$('#unobtrusive').on('click',function (e) {
    e.preventDefault(); //optional
    //some code
});

Html Code:

<a id="unobtrusive" href="http://jquery.com">jquery</a>

answered May 25, 2020 at 5:38

just use javascript:---- exemplale

javascript:var JFL_81371678974472 = new JotformFeedback({ formId: '81371678974472', base: 'https://form.jotform.me/', windowTitle: 'Photobook Series', background: '#e44c2a', fontColor: '#FFFFFF', type: 'false', height: 700, width: 500, openOnLoad: true })

Html link to javascript function

sticky bit

35.8k12 gold badges29 silver badges39 bronze badges

answered May 30, 2018 at 21:29

1

How do you call a JavaScript function from 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.
We can link JavaScript to HTML by adding all the JavaScript code inside the HTML file. We achieve this using the script tag which was explained earlier. We can put the <script></script> tag either inside the head of the HTML or at the end of the body.

Can an A HREF call a JavaScript function?

In an A tag, you can call JavaScript through the HREF portion of the tag. You could also call JavaScript through an onClick function, onHover function, or other A link attributes.
You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.