Search code examples
javascripthtmlruby-on-railsunobtrusive-javascript

Use <a> tags or any tags for javascript links?


Is there a preferred way or advantages to using one over the other ?

i.e.

  1. You can have a hyperlink a where the href points to # with a class or id and then javascript that looks for that elements on-click event.

  2. You can have a simple div or span that has a class or id and bind the javascript on-click to that element.

I have seen both done.

Context is ruby on rails applications that are using javascript for some functionality.


Solution

  • This is more of an HTML question than javascript.

    1. A elements are simple, work in every browser and are utterly reliable whether scripting is available or not.
    2. Browsers support A elements through context menu features to open them in new windows or tabs
    3. A elements have a default presentation in browsers that lets users know they are links without any other scripting or styling support required
    4. Different browsers may present links slightly differently, so users get used to seeing them behave in the particular way their browser presents them. Scripted and styled other elements likely will present in an unfamiliar way to at least some users.
    5. Browsers offer features to support A element links such as tab navigation between links and separate lists of links in the page.
    6. Screen readers and other support mechanisms for accessibility understand A element links and can present them to their users
    7. Browsers typically present the destination of an A element link to a user so they can decide whether to follow the link or not
    8. A element URLs are easily copied and shared without following the link
    9. A elements can be used to create bookmarks without following the link

    Scripted and styled links do not have any of the above features, or at least require significant additional effort to support any of them.