Is there a better way to define anchor links that perform javascript other than using href="#"? The main reason I dislike using this href is because it invalidates browser history. The back button just removes the "#" from the URL. If you use any type of Go Back link, it won't work unless they click it twice.
In cases where my Javascript is inlined, I can use href="javascript:func()", but this won't work when the listeners are attached from an external script file.
So I'm just looking for a cleaner direction to point my empty anchors.
If you "MUST" use <a> tag for your actions, in such cases, I prefer to add preventDefault in the event listener. This prevents "#" from being added to the URL.
window.onload = function() {
document.getElementById("noHash").addEventListener("click", function(e) {
e.preventDefault();
console.log("Hi There!");
});
}
Say Hi
I'm posting an alternate answer just so others who stumble onto this see that this is an option. When I asked about it, I didn't realize you could use the code href="javascript:void(0)". As far as I can tell, this doesn't have any negative side effects, and you can still attach click listeners to it later on.
In addition, the new HTML spec apparently states that anchor tags don't even need href attributes, and removing href attributes didn't seem to have any side effects in any browsers that I tried it in (Chrome, Firefox, Opera, Edge). Still, I stuck to the void option.
And finally, I read somewhere that another option is to use href="#!". I'm assuming this does nothing as long as you don't have an id of ! on your page, but I have not tested this one. EDIT: Tested this - it has the same issues as using href="#" by itself.
Related
What is the meanign of javascript:; that is kept inside the href attribute in an link?
Like
Link
IF you need to pass a javascript snippet which needs to run instead of the default behavior of an element then you use this javascript: ; syntax.
For example
Test <!-- Runs on the click of the link -->
Similarly, you can combine these on other events also, like onclick, onchange etc but this is really not necessary, since you can execute the snippet, directly.
The uses of this, i have seen in years are:
Test
<form action="javascript:void(0);">..</form>
The javascript:; in the href does the same as putting something in the "onclick" property.
Thus,
Link
is identical to
Link
I'm not sure which is better to use when, but worth mentioning is that you can type these "links" in to the address bar of most modern browsers and it will run.
copy and paste (or type, chrome seems to prohibit this.) in to your address bar
javascript:alert("test");
as well as you can save links with these addresses to bookmarks so that it will run that script on any page you click the bookmark on.
That alone does nothing, but normally javascript: precedes some JavaScript code to indicate that the browser should execute the code instead of treat the href attribute as a URL. Thats it.
This might be intended as a reference that does nothing when clicked and might be accompanied by setting onclick etc. to actually do anything.
upd: While some say that putting a script in href is the same as putting it in onclick, there are some differences, like what happens on right click (and some scripts definitely should not be opened in a new tab or such). Still, my opinion of the practice is that it is somewhat ugly, and not only because of uninformative text in status bar when mouse over the link.
You can imagine that as someone copying that "javascript:;" into the url box and hitting Enter. Since it starts with "javascript:" the browser will know to execute what follows as javascript in the current page. Since all that follows is a ";", nothing will happen, actually. That's the same as clicking a button that has a onClick attribute set to ";".
For example:
Click me!
has the same effect that
<button onClick="alert('howdy!')">Click me!</button>
or even
Click me!
Keep in mind that, since it's a link, most browsers will render its address (in that case "javascript:alert('howdy!')") in the status bar, and that may be undesired (I find it to be particularly ugly).
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.
I want to add some Ajax sorting options to a list. Since my site runs without JavaScript thus far I'd like to keep it running for people with it turned off, old/mobile browsers or noscript.
How can I run a block of JavaScript when clicking a link if JavaScript is enabled and have that link direct the browser to a new page if it's not. I'd like to keep away from hacky noscript tags.
Your links need valid href values pointing to the alternative non-JavaScript pages, and in your click event, you need to return false, to avoid JavaScript enabled browsers to follow the links:
<a id="aboutLink" href="about-us.html">About Us</a>
$('#aboutLink').click(function () {
// ajax content retrieval here...
return false; // stop the link action...
});
I would use preventDefault:
$('a').click(function(e) {
e.preventDefault(); //stop the browser from following
$('#someDiv').load('content.php');
});
Load content
If there's no Javascript, the HREF will be followed.
I would imagine you could put the URL of the new page in the HREF, and return false from the onClick event handler to stop the link from being taken. If JS is not enabled then the onClick will not be run, meaning the HREF will be followed.
For a good separation of concerns, your best bet is to use attachEvent (IE) or addEventListener (standard) (or a toolkit that hides that from you, like Prototype, jQuery, MooTools, YUI, Glow, etc.) and then cancel the event from within JavaScript. Assuming this link:
<a href='foo' id='mylink'>Link text</a>
...here's an example using Prototype:
// Hook up your handler on page load
document.observe("dom:loaded", function() {
// Look up the link, apply your handler
$('mylink').observe('click', yourHandler);
});
// Your handler:
function yourHandler(event) {
// Prevent the default action
event.stop();
// ...your code here...
}
You don't have to assign the link an ID, there are lots of ways to find DOM elements other than IDs, but it makes a handy example.
jQuery, et. al., will have their own versions of event.stop(), but it comes down to cancelling the event.
I would simply write down the HTML as it would look like without JavaScript, and then modify the content as it should look with JavaScript enabled.
In case JS is enabled, the site might load a little bit slower and may look a bit weird while it is being built, but the functionality remains.
In case JS is disabled, the site stays as it is and remains accessible for non-JS Users
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;
});
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.