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;
});
Related
I was used to do href="#" but is there any other way?
Because clicking on such kind of a link sometimes can turn user to front of a page viewed and I want to load some scripts by clicking on a link.
Keep using Click, but use some Javascript/jQuery to prevent the page from jumping:
$('a').click(function() {
// do whatever
return false;
}
The return false line will prevent the browser from following the link, which in this case will stop it from jumping to the top of the page.
You should keep the link as an <a> tag, rather than use a span or div, since this is far more semantic (i.e. users/crawlers will know it's supposed to do something since it's a link).
You should also avoid using inline Javascript (i.e. onclick="doSomething()") since this is a huge pain if you ever want to change the behaviour, and you also want to make your Javascript as unobtrusive as possible.
yes, href="#" makes ou scroll...
You can try:
Woho
Why not use onclick
<a href="#" onclick="doMyThing() return false;" />
Similar discussion on SO, href-tag-for-javascript-links-or-javascriptvoid0
href="javascript:void(0)"
Thanks Yaniro
As #Yaniro commented you can use href="javascript:void(0)", the reason for this is:
JavaScript Void 0 Explanation
Web browsers will try and take whatever is used as a URL and load it. The only reason we can use a JavaScript Alert statement without loading a new page is because alert is a function that returns a null value. This means that when the browser attempts to load a new page it sees null and has nothing to load.
The important thing to notice here is that if you ever do use a JavaScript statement as the URL that returns a value, the browser will attempt to load a page. To prevent this unwanted action, you need to use the void function on such statement, which will always return null and never load a new page.
Extracted from: JavaScript Void 0 Explanation
For a good markup if you want an event on same page. So, it's better if you use div or span for this & define your click event on it.
div{
color:red;
}
JS
$('div').click{function(
)};
You can simply use the onclick attribute in any element, e.g.
<span onclick="foo()">Do something</span>
The habit of using href="#" is a holdover from the early days when browsers did not support onclick generally, only for links (in the technical sense: a elements with href attribute). That’s water under the bridge, but old habits often don’t die, especially if people just adopted them without knowing the reasons.
Instead of span, you could use a too. Without any href attribute, an a element has no special meaning.
By nondisruptiveness principles, the element should be generated dynamically with JavaScript instead of being a static part of the page (since when JavaScript is disabled, it would just sit there, making an impression of being relevant, but without doing anything).
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.
This question may have been asked before, but I had trouble finding an answer, since I didn't quite know what search terms to use.
In HTML, how do you make a link go a place, but execute JavaScript instead when it is clicked? Right now, I have a link that's somewhat like this:
Stuff
But, the thing is, when someone right clicks the link, I want them to be able to copy a direct URL to the link. Also, if someone's browser does not support JavaScript, or they have it disabled, I would still like them to be able to reach the page. Is it just
Stuff?
Or is there something more complicated?
Thanks!
Stuff
Make sure that the dosuff function returns false if you want the link to not be followed when the script runs.
(The 'javascript:' is pointless. It labels a loop, but you don't have a loop. See the HTML spec for how to specify which language is being used in the intrinsic event handler attributes — better yet, use unobtrusive JavaScript and progressive enhancement).
You need to let the event return false to block the default action.
<a href="http://example.com" onclick="doSomething(); 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.
I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the javascript: prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between:
onchange="javascript: myFunction(this)"
and
onchange="myFunction(this)"
?
Probably nothing in your example. My understanding is that javascript: is for anchor tags (in place of an actual href). You'd use it so that your script can execute when the user clicks the link, but without initiating a navigation back to the page (which a blank href coupled with an onclick will do).
For example:
Blah
Rather than:
Blah
It should not be used in event handlers (though most browsers work defensively, and will not punish you). I would also argue that it should not be used in the href attribute of an anchor. If a browser supports javascript, it will use the properly defined event handler. If a browser does not, a javascript: link will appear broken. IMO, it is better to point them to a page explaining that they need to enable javascript to use that functionality, or better yet a non-javascript required version of the functionality. So, something like:
Ajax me
Edit: Thought of a good reason to use javascript:. Bookmarklets. For instance, this one sends you to google reader to view the rss feeds for a page:
var b=document.body;
if(b&&!document.xmlVersion){
void(z=document.createElement('script'));
void(z.src='http://www.google.com/reader/ui/subscribe-bookmarklet.js');
void(b.appendChild(z));
}else{
location='http://www.google.com/reader/view/feed/'+encodeURIComponent(location.href)
}
To have a user easily add this Bookmarklet, you would format it like so:
Drag this to your bookmarks, or right click and bookmark it!
It should only be used in the href tag.
That's ridiculous.
The accepted way is this:
Blah
But to answer the OP, there is generally no reason to use javascript: anymore. In fact, you should attach the javascript event from your script, and not inline in the markup. But, that's a purist thing I think :-D
The origins of javascript: in an event handler is actually just an IE specific thing so that you can specify the language in addition to the handler. This is because vbscript is also a supported client side scripting language in IE. Here's an example of "vbscript:".
In other browsers (as has been said by Shadow2531) javascript: is just a label and is basically ignored.
href="javascript:..." can be used in links to execute javascript code as DannySmurf points out.
javascript: in JS code (like in an onclick attribute) is just a label for use with continue/goto label statements that may or may not be supported by the browser (probably not anywhere). It could be zipzambam: instead. Even if the label can't be used, browsers still accept it so it doesn't cause an error.
This means that if someone's throwing a useless label in an onclick attribute, they probably don't know what they're doing and are just copying and pasting or doing it out of habit from doing the below.
javascript: in the href attribute signifies a Javascript URI.
Example:
javascript:(function()%7Balert(%22test%22)%3B%7D)()%3B
I am no authority in JavaScript, and perhaps more of a dunce than the asker, but AFAIK, the difference is that the javascript: prefix is preferred/required in URI-contexts, where the argument may be as well a traditional HTTP URL as a JavaScript trigger.
So, my intuitive answer would be that, since onChange expects JavaScript, the javascript: prefix is redundant (if not downright erroneous). You can, however, write javascript:myFunction(this) in your address bar, and that function is run. Without the javascript:, your browser would try to interpret myFunction(this) as a URL and tries to fetch the DNS info, browse to that server, etc...
#mercutio
That's ridiculous.
No, it's not ridiculous, javascript: is a pseudo protocol that can indeed only be used as the subject of a link, so he's quite right. Your suggestion is indeed better, but the best way of all is to use unobtrusive javascript techniques to iterate over HTML elements and add behaviour programmatically, as used in libraries like jQuery.
Basically, is there any appreciable difference between: onchange="javascript: myFunction(this)" and onchange="myFunction(this)" ?
Assuming you meant href="javascript: myFunction(this)", yes there is, especially when loading content using the javascript. Using the javascript: pseudo protocol makes the content inaccessible to some humans and all search engines, whereas using a real href and then changing the behaviour of the link using javascript makes the content accessible if javascript is turned off or not available in the particular client.
Flubba:
Use of javascript: in HREF breaks "Open in New Window" and "Open in New Tab" in a Firefox and other browsers.
It isn't "wrong", but if you want to make your site hard to navigate...
I don't know if the javascript: prefix means anything within the onevent attributes but I know they are annoying in anchor tags when trying to open the link in a new tab. The href should be used as a fall back and never to attach javascript to links.