Jin Yong
Jin Yong

Reputation: 43778

How to use a link to call JavaScript?

How to use a link to call JavaScript code?

Upvotes: 212

Views: 459069

Answers (11)

Shawn GameForreal
Shawn GameForreal

Reputation: 76

Why not just make it a button and style it like a link?

<button onclick = 'myFunction()' style='background-color: white; border: none; color: blue'>I look like a link</button>

function myFunction() {
alert("the cursor also reacts as if a normal link, while hovering the text; outside of this snippet")
}
<button onclick = 'myFunction()'; style='background-color: white; border: none; color: blue; cursor: pointer;'>I look like a link</button>

Upvotes: 0

Domi S Herdian
Domi S Herdian

Reputation: 1

Just use Javascript - example:

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 })

Upvotes: -6

Rohan Kilambi
Rohan Kilambi

Reputation: 21

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>

Upvotes: 1

Mostafa Asadi
Mostafa Asadi

Reputation: 397

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>

Upvotes: 0

Matt Grande
Matt Grande

Reputation: 12157

<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.

Upvotes: 58

Fire Crow
Fire Crow

Reputation: 7729

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

Upvotes: 13

Chelsea
Chelsea

Reputation: 6801

<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.

Upvotes: 234

EndangeredMassa
EndangeredMassa

Reputation: 17528

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>

Upvotes: 230

Mister Lucky
Mister Lucky

Reputation: 4073

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>

Upvotes: 43

Mark Biek
Mark Biek

Reputation: 150759

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>

Upvotes: 9

David Z
David Z

Reputation: 131580

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

<a onclick="jsFunction();">

Upvotes: 11

Related Questions