Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to execute Javascript on an anchor

Generally, there are 3 ways (that I am aware of) to execute javascript from an <a/> tag:

1) Use onclick():

<a href="#" onclick="alert('hello'); return false">hello</a>

2) Directly link:

<a href="javascript:alert('hello')">hello</a>

3) Or attach externally:

// In an onload event or similar
document.getElementById('hello').onclick = window.alert('Hello'); 
return false;
<a id="hello" href="#">hello</a>

I am actually loading the link via AJAX, so #3 is basically out. So, is it better to do #1 or #2 or something completely different? Also, why? What are the pitfalls that I should be aware of?

Also of note, the anchor really doesn't link anywhere, hence the href="#", I am using a so the styles conform as this is still an object to be clicked and a button is inappropriate in the context.

Thanks

like image 317
steveo225 Avatar asked Sep 22 '11 14:09

steveo225


People also ask

Can we use anchor tag in JavaScript?

Using JavaScript In vanilla JavaScript, you can use the document. createElement() method, which programmatically creates the specified HTML element. The following example creates a new anchor tag with desired attributes and appends it to a div element using the Node. appendChild() method.

How do you call JS link in HTML?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Can I use onclick in anchor tag?

Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.


3 Answers

If you are loading the content via ajax and need to hook up event handlers, then you have these choices:

  1. Put a javascript handler in your HTML with your option 1) or 2). In my mind option 1) is a cleaner way of specifying it, but I don't think there's a mountain of difference between 1) or 2) - they both do essentially the same thing. I'm not a fan of this option in general because I think there's value in keeping the markup and the code separate.
  2. After loading the content with ajax, call some local code that will find and hook up all the links. This would be the same kind of code you would have in your page and execute on DOMReady if the HTML had been static HTML in your page. I would use addEventListener (falling back to attachEvent) to hook up this way as it more cleanly allows multiple listeners for a single object.
  3. Call some code after you load the content with ajax that finds all the links and hooks up the clicks to some generic click handler that can then examine meta data in the link and figure out what should be done on that click based on the meta data. For example, this meta data could be attributes on the clicked link.
  4. When you load the content, also load code that can find each link individually and hook up an appropriate event handler for each link much the way one would do it if the content was just being loaded in a regular page. This would meet the desire of separating HTML from JS as the JS would find each appropriate link and hook up an event handler for it with addEventListener or attachEvent.
  5. Much like jQuery .live() works, hook up a generic event handler for unhandled clicks on links at the document level and dispatch each click based on some meta data in the link.
  6. Run some code that uses an actual framework like jQuery's .live() capability rather than building your own capability.

Which I would use would depend a little on the circumstances.

First of all, of your three options for attaching an event handler, I'd use a new option #4. I'd use addEventListener (falling back to attachEvent for old versions of IE) rather than assigning to onclick because this more cleanly allows for multiple listeners on an item. If it were me, I'd be using a framework (jQuery or YUI) that makes the cross browser compatibility invisible. This allows complete separation of HTML and JS (no JS inline with the HTML) which I think is desirable in any project involving more than one person and just seems cleaner to me..

Then, it's just a question for me for which of the options above I'd use to run the code that hooks up these event listeners.

If there were a lot of different snippets of HTML that I was dynamically loading and it would be cleaner if they were all "standalone" and separately maintainable, then I would want to load both HTML and relevant code at the same time so have the newly loaded code handle hooking up to it's appropriate links.

If a generic standalone system wasn't really required because there were only a few snippets to be loaded and the code to handle them could be pre-included in the page, then I'd probably just make a function call after the HTML snippet was loaded via ajax to have the javascript hook up to the links in the snippet that had just been loaded. This would maintain the complete separation between HTML and JS, but be pretty easy to implement. You could put some sort of key object in each snippet that would identify which piece of JS to call or could be used as a parameter to pass to the JS or the JS could just examine the snippet to see which objects were available and hook up to whichever ones were present.

like image 99
jfriend00 Avatar answered Oct 05 '22 09:10

jfriend00


Number 3 is not "out" if you want to load via AJAX.

var link = document.createElement("a");
//Add attributes (href, text, etc...)
link.onclick = function () { //This has to be a function, not a string
    //Handle the click
    return false; //to prevent following the link
};
parent.appendChild(link); //Add it to the DOM
like image 27
Dennis Avatar answered Oct 05 '22 09:10

Dennis


Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.

The way that CSP does this is disabling all the vectors where a user could inject Javascript into a page - in your question that is both options 1 and 2 (especially 1).

For this reason best practice is always option 3, as any other option will break if CSP is enabled.

like image 25
Keith Avatar answered Oct 05 '22 09:10

Keith