Sole hash in anchor href? - javascript

In the project I work on I've recently moved from developing backend (i.e. non-web) servers to web-related things. In the HTML code I've found the following thing all over the place:
<a href='#'>some link</a>
Then some JS is attached to the click event of <a> element.
Does this sole hash has any special meaning? I understand how the href='#some_id' tells the browser to scroll to element with ID = some_id. But href='#' doesn't work that way, right?
If it's all about creating a clickable piece of text, why not simply use a <span>?

Exactly. What you see here is somehow bad design (although it is quite common to use href="#").
What it actually will do is jumping to the top of the page if the default action is not prevented.
Much better would be to
use a <button> and style it accordingly (maybe even only inserted via JavaScript)
or let the link point to some real resource (that triggers some action on the server side) and attach the JavaScript event handler to do this (or similar) action on the client and prevent following the link (keyword: unobtrusive JavaScript).
It also depends on whether the site is meant to run with disabled JavaScript. If yes, then such a link (but also a button) will not work.
But in any case, from a semantic point of view, using a link solely to have something "clickable" is wrong.

A hash on its own links to the top of the page.
This is sometimes used for exactly this purpose -- ie a "Back to top" link, but more typically this kind of link is used in conjunction with a Javascript click even which returns false, and thus negates the action of the href.
In this context, it is used in this way for the following reasons:
An <a> tag may be semantically correct -- ie the item to be clicked on is acting as a link; ie to load more content, or open a popup, etc, even though it is using Javascript for it's functionality.
Using an <a> tag also means that the element will be styled in the same way as other <a> tags on the site. This includes :hover effect styles, etc. Note that IE6 only supports :hover on <a> elements, and nothing else, meaning that if the site was designed to work in IE6 or still needs to support it, then you can't replicate this functionality with other tags. This was a very good reason to use <a> tags for this feature in the past, even if it wasn't appropriate semantically. These days it's less of an issue. Even in modern browsers, using <a> for these items is still useful for cutting down on replicated stylesheets if you want them to look the same as other links. Links also have a few other special features which may be difficult to replicate with other elements, such as being in the tab index sequence, etc.
HTML requires that an <a> tag has a href attribute in order for the element to be rendered as a link, so the hash is used as a minimal value for this. In addition, having a hash in the href attribute means that the link won't cause any nasty unexpected consequenses if the user turns off Javascript or if the developer forgets to return false;. By contrast, having an empty string would cause it to reload the page, which is unlikely to be what you want if you have just run some javascript. It is however also common to have the link point to a valid URL, which would be run if Javascript was switched off; this is a good way to have a fall-back mechanism for your site. But it isn't always appropriate, and clearly isn't the intention here.
Given that the item is just triggering a click event in Javascript, there's no reason why you couldn't use any other element for this. You could very easily use a <span> (or even better, a <button>) instead, but the above points should show that there's nothing wrong with using an <a> tag.
Hope that helps.

Does this sole hash has any special meaning?
It links to the top of the page
Why not simply use a <span>?
It won't be in the focus order
It won't take on the default styles of something that should be clicked
A <button> would be better than a span. Something built on top of a server side alternative would be best.

Because you want the browser to style this link the same as all other links, and without having to specify (e.g. with a class) that "you know, I want this to look like a link even though it's technically not". That's really not good for maintainability.

Because:
the styling is done for you;
the link is semantically still a link, even if it starts off with a no-op href.
Rhetorical question:Can you explain why you think a span is more appropriate than a for a link?
Addendum:Something like a button or another dynamic element may be better suited here, but taking a non-link span of text and pretending that it's a link is worse.

Related

TinyMCE - how do you use onClick instead of <a href=""> for links?

Is there a way to change the defalt behaviour of TimyMCE, so that when you insert a link, it renders something like this:
<span onclick="window.open('http://google.com', '_blank', 'location=yes');"></span>
instead of
Ideally, I would like this to be done by the Link button, but it could be done onSubmit.
ADDED:
The reason for doing this (as I know it seems like bad practice) is to be able to port to PhoneGap (using the InAppBrowser plugin), as is not intended for browser use.
Overlooking that this really isn't a good practice, I will assume you have a valid use case for wanting to do such black magic.
But before, a few things to consider:
I would advise you to keep links as links while working in TinyMCE. That way, your users will be able to insert and edit them as usual. Changing them to span elements inside the editor will practically eliminate the ability to edit them without editing the full source. You should probably convert them to span elements outside the editor.
If you're the stubborn type and don't care about #1 or your users, you should note that the default TinyMCE 4 configuration doesn't allow onclick attributes, so you'll need to update extended_valid_elements, otherwise they will be removed during the cleanup process.
There is probably a better way to do what you're trying to do. As #Vic suggested, an event listener would probably be a better option.
Nevertheless, I will humor you. Below is an overview of the process with a working example.
Overview
If you are developing with TinyMCE 3.x, you'll want to tap into the onSaveContent event. If you are using 4.x, use the saveContent event. In both cases, the concept is the same.
This event gets fired whenever the content of the editor is "saved". This happens automatically if TinyMCE is submitted as part of a form, but you can also use tinymce.triggerSave() to force it on all editors at once.
So, simply setup your callback function to replace all links with the evil span alternative. You can use pure JS or TinyMCE's built-in DOM utilities (probably only a good idea if you're already familiar with them), but for clarity (and sanity) it's much easier with jQuery.
Working Example
TinyMCE Fiddle: http://fiddle.tinymce.com/mAdaab/1
This example uses TinyMCE 4
Open your browser's console to see the output
After TinyMCE loads, press the Save button
The resulting HTML will appear in your console
Do with it what you wish, but remember that there probably is a better way.
What you are proposing is a really bad practice (as in not using anchor tags for links) wouldnt it be easier to actually give your link an id or class and attach event listener with javascript and on click prevent default behavour grab the href attribute and use your window.open?

What should the HREF attribute be for javascript links on a 508 compliant page?

I know this question:
Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"? contains a discussion of what the correct href content should be for javascript links. How does this relate to 508 compliance? Does anyone know if the javascript:void(0) is acceptable when click handlers are defined elsewhere in the javascript code?
This is where terminology becomes important - in terms of accessibility there is no such thing as "a javascript link". There are links, which are unadulterated anchor elements, and there are javascript behaviours, which should be assumed not-runnable for accessibility.
An empty anchor element that triggers javascript (so something like href='#' onclick='...') is not a link, it's a UI element for triggering page behaviour. For accessibility, don't abuse the anchor element for this, use a real UI element with the correct ARIA role.
For a click-through link (which do something like "click anchor" -> "magical JS is called" -> "window.location is changed to some new page") then be aware that you're semanticlaly misrepresenting your content. Even though you're using an anchor element, your use of it is not as a link, since it's not an anchor to another resource. Like in the above case, it's actually a button. The fact that the page location changes at the end does not change this.
For true accessibility, you'll have to give up any JavaScript-in-the-middle. But don't worry, that's much less severe than it sounds: the simplest solution is to use rerouting links instead. If you've ever used google.com or duckduckgo.com, etc. you'll already be familiar with this: rather than link out to the actual URL, link out to the URL proxied over a page-less script. You can guarantee that an anchor with the URL "http://our.domain.com/ref=http://the.actual.link.to.visit", will end up redirecting to the actual site just fine, and you can tack on any desired operation that should take place "when people click" as a server side action when you resolve the redirect.
508 compliance will be hard if you think you rely on JavaScript. So for accessibility: actively try not to. Enrich if you can use it, ensure things still work without it.
I essentially agree with Mike.
How does this relate to 508 compliance?
A common misconception about Section 508 is "oh I ran my site with JAWS (or maybe NVDA), and was fine. So I am compliant." Section 508 is therotically supposed to cover all disabilities not just blindness. When you wonder off into heavy JavaScripting, agencies tend to use the "Software applications and operating systems" (1194.21) Standards in addition to "Web-based intranet and internet information and systems" (1194.22) because they talk more about UI elements. Places like WebAIM, unfortunately deny this.
So when 1194.21 is included, the Standards can be more easily read as "you put all the #alts and <label>s on, but can this site/app/system with the keyboard? AKA is it keyboard navigatiable?" Can you get to that <span> that looks like a link?
As Mke said, one way to assist with this is using ARIA. So, that <span> now has to be:
<span onclick="Clicky()" role="link">Link</span>
(Ref: MDN)
Now back to your question:
I know this question: Href attribute for JavaScript links: "#" or "javascript:void(0)"? Does anyone know if the javascript:void(0) is acceptable when click handlers are defined elsewhere in the javascript code?
I would advocate for the void because when a reference (think it is called an in-page ref)is not defined, the focus goes back to the browser frame, versus staying on the link. You would need to write some handlers to return the focus to the link.

What is the proper use of the anchor tag?

I've read how the anchor tag is holy, it should not be used with javascript:
Popup
that it should ONLY be used for a link to another page:
Take me over there
So what is the proper use of the anchor tag with javascript? Should I be using:
Energize!
or some other variant? I'm somewhat confused by different views on the subject. Also is it only SEO that I should be worried about if making the href a javascript piece? Or is it more of a proper web standards compliance deal?
Thoughts? Hopefully I'm not the only one confused.
You are not alone Jakub; even the biggest WWW companies use different approaches.
However based on experiences since Netscape days I wouldn't use :
Popup
which can make some troubles on some browsers, like opening an empty page or breaking the event order on the current page.
However;
Energize!
or;
Link
don't make a serious trouble and are ok to use. Note that the prior one may reset the scroll to the top.
You should use meaningful link targets and unobtrusive javascript wherever possible, but this is not always possible in real life examples. It's not a defined standard, but a method highly agreed by most of the web developers.
When it comes to standards, there is one related with this situation:
You should consider using a 'button' for inputs which doesn't really send the visitor to a page, but does an operation. This is also important for SEO.
As #Sime says (and it should be an answer really), it is considered "bad practise" to now directly reference javascript in any HTML object. So in these cases you attach the event using something like jQuery using the concepts laid out in "unobtrusive javascript".
As you mention another consideration is SEO and accessibility. If SEO is important to your site, make sure that the site is fully navigable using just standard links. Again you can manage this using "unobtrusive javascript", etc.
I've always gone with using an anchor as normal (i.e. specify either an alternate url that is another location where the user could perform what's being done through javascript, or use javascript:void() / #) then use the onclick event for anything you want executed.
You could also use a <span> if you're that worried about conformance, just would need to perhaps style it (change cursor, perhaps color as well) to make it visually obvious you're making it an action.
I think Facebook is the best-case example. Almost all of their links are javascript tied in, but they also have a "backup" page for those that either have disallowed javascript or don't have it (the later, in this day and age, being far less common). Take a look at a module that reacts like you'd like yours to and see how they've done it. They also invested a bunch of work in best-practices that you can benefit from.
If anything, you should bind your anchor links to javascript methods only by using unobtrusive javascript like Paul mentioned.
This means, using separation of concerns and leaving your markup being just that, html markup:
<a id="Jolter">Energize!</a>
and later
<script type="text/javascript">
$(document).ready(function(){
$("#Jolter").click(function(){
// doStuffHere ...
});
});
</script>

Empty-linked anchor

I have an anchor that doesn't go anywhere but has an onclick (e.g. <a onclick="..."></a>). My question pertains to the href attribute. What should I put for the value?
If I simply omit href, the anchor doesn't have the appropriate decoration--the mouse pointer icon doesn't change when the mouse is put over it.
If I use href="#", then the window scrolls to the top of the page when the link is clicked.
If I use href="javascript:..." and put the value of onclick proceeding javascript:, the page is left and the address bar contains the Javascript when the link is clicked.
When I refer to browser behavior, I'm referring to Chrome, which I'm testing it in to start with.
What should I be putting for href when the anchor isn't an actual link but exists only to have the onclick perform behavior?
Ideally you would have an option for those with Javascript disabled:
do the option!
If you're not into that sort of thing, although you really should be, the most common way is to use the pound but then cancel the event to prevent the default action from happening, like so:
do something
But then you have to make sure do_something returns false. (or you can just add return false; at the end of the click handler, but this gets even more unsightly fast)
Although, to be honest, you really shouldn't have inline Javascript attributes to begin with. They are bad practice, a nightmare to maintain, and there are much better alternatives out there.
EDIT: In response to your comment, the alternative is unobtrusive javascript:
"Unobtrusive JavaScript" is an emerging technique in the JavaScript programming language, as used on the World Wide Web. Though the term is not formally defined, its basic principles are generally understood to include:
Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
Progressive enhancement to support user agents that may not support advanced JavaScript functionality
Read the page for some examples.
In your onclick handler, add this to the end:
return false;
This will cancel the default processing (i.e. following the link) and you can put whatever you want in the href (the # is as good as any).
txt
I prefer to drop the href (it's not required according to W3C spec) if it's not used. To get the expected mouse cursor, use CSS!
<style type="text/css">
a { cursor: pointer; }
</style>
<a onclick="go();">link</a>
Foo
Short, descriptive and does not jump like #.
There are two ways of doing this, if the id tag of the link is link, you can use href="#"in your HTML, and then in your JavaScript have:
$('#link').click(function(evt) {
// code goes here
evt.preventDefault();
});
This prevents the browser's normal behavior. Or
$('#link').click(function(evt) {
// code goes here
return false;
});

Using an anchor as a javascript action, what should the link be?

I've seen (and used) code to have a link spawn a javascript action many times in my life, but I've never come to a firm conclusion on if the href attribute should be blank or #. Do you have any preference one way or the other, and if so, why?
linky
or
linky
You must have something for the href attribute, otherwise the browser will not treat it as a link (for example, making it focusable or giving it an underline) - that's why the use of "#" has become prevalent.
Also, the contents of the event attributes (onclick, onmouseover, on...) are already treated as javascript: you don't need to preface it with javascript:
So given your example, the best way to do that inline (which itself is not the best way, probably), is like this:
linky
Checkout the discussion over at Href for Javascript links: “#” or “javascript:void(0)”?.
Also, leaving href blank causes the browser to not use the pointer cursor when the user mouses over, though you can fix that with CSS.
I always use # as having javascript: inside of html attributes seems to generally be considered as bad practise they days.
So saying that, you should try and refrain from using onclick= attributes and use javascript listeners in external .js files instead.
For example you using jQuery..
$(".link").click(function(e) {
e.preventDefault();
DoSomething();
});
Why not have the href point to a page explaining they have JavaScript turned off and they need to turn it on to get the missing functionality ?
Since the link will only be followed when they have javascript turned off, let it be something informative!
Also remember people sometimes middle click on such links and the OnClick event does not fire, so if you can get them a page that works without the need for javascript it would be ideal.
In cases like this, where you intend not to provide a non-javascript option, I prefer:
linky
This way you can at least provide a plan text description as the JavaScript comment.

Categories