Is the javascript: prefix really needed? I know you should aim for unobtrusive JavaScript but under what circumstances would something break if it is not there?
javascript: is a URI scheme.
It is needed to create a URI that runs Javascript, either in an href="" attribute or in the browser address bar.
There is never a situation in which javascript: is optional.
Best practices indicate that javascript: URIs should be avoided where possible in favor of click handlers, so its use is frowned upon.
However, there are cases where there is no alternative. For example, bookmarklets can only be created by using javascript:.
They're "needed" if you are encoding Javascript code into an URI, for example in the href property of an <a> tag.
They're bad practice, though.
If you put JavaScript code into the href attribute of an a, or other attribute which takes a URL, then it's required for the browser to detect that it is JS. It's not necessary (and may not even work) if you use it with onclick or other attributes that already expect JS code.
That "prefix" is used only in the href attribute of an html anchor (). It is never actually needed, since you could as well define a click event handler.
It is needed even in onclick situations if you also have a VBS routine on the same page.
Related
I don't know why this link does not work, but I have a Javascript redirect (window.opener.location) that I am passing a number of variables through the URL and am having issues when those variables contain apostrophes. I am using URLENCODE() in PHP to build the link, which looks like it is doing what I need when I dump the source, but Safari and Chrome both throw "Unexpected identifier at 'www'" errors when I click the link.
This seems to tell me that the JS link is still being treated as if it has an apostrophe instead of the %27 equivalent of an apostrophe? I am using a dummy name "qqq'www qqq'www" with apostrophes in first and last name for my testing to break as much stuff as possible.
Here is the link I am having trouble with:
<em>Yes</em>
But if I change the link to use onclick instead of the HREF, it works? I realize this is the better coding method than href='javascript:...' too.
<em>Yes</em>
Everything is identical except where I make the JS call. Is this possibly due to the way the HREF and onclick are handled on encoding/decoding? Maybe the HREF is un-encoding the apostrophes prior to making the link call because the JS is embedded in the HREF call?
Any insight into this behavior would be appreciated so I can better understand what is really going on here. Yes it works, but not knowing why makes me feel like a worse developer...
Thanks!
Your links do not have a > to end the starting <a - and yes, do not use href="javascript:
Also if you need to encode, use encodeURIComponent and lastly do not try to close the window before changing the opener.
But why not name the opener and user a target and a setTimeout?
<a target="nameOfOpener"
href="../cust/maint_cust.php?action=del_are_you_sure&cust_id=249735&lname=Qqq%27www&fname=Qqq%27www"
onclick="setTimeout(function() {top.close()},100)"><em>Yes</em></a>
Browsers give a special treatment to href attributes starting with 'javascript:'. Any %xy encoding, as in your case the %27, will be decoded first before executing the Javascript code. I checked this for current versions of Firefox and Chrome. I would be curious to find a documentation of this feature.
The short answer is: Do not use 'javascript:' in a href, if your Javascript code contains %xy encodings.
In case you really have to use 'javacript:' in a href, put your URL into a javascript variable and then reference that variable in your href's Javascript code.
<script>
myURLwithEncodings = "../cust/maint_cust.php?action=del_are_you_sure&cust_id=249735&lname=Qqq%27www&fname=Qqq%27www";
</script>
<em>Yes</em>
I have seen at many locations that people use javascript: before functions(classes) or using attributes? E.g., javascript:Blob, javascript:void(0).
I'm wondering what are the situation when using this notation can be necessary?
Or what're the best practices regarding using or not using this?
Expanding scope of my question:
Can it be useful to use it without href. I.e., in JS file directly?
Does ECMAScript have to do anything with it?
"javascript:" is a URL protocol. When the browser loads a javascript: URL, it takes the rest of the URL as JavaScript code and executes it. Thus, you can put this in an href attribute on an <a> tag.
It's generally better to not do this, though - instead, you can set href='#' and put your JS code in the onclick attribute. (Some recommend setting href='javascript:void(0)', which is similar but subtly different. See here.)
This is usually used for HTML a tag HREF's ie LINK TEXT
This question already has answers here:
href="javascript:" vs. href="javascript:void(0)"
(8 answers)
Closed 7 years ago.
I have seen href="javascript:void(0)" and I have seen href="javascript:;" Is there any reason I would not just use href="javascript:" instead?
Edit: Let me make it clear: I am combining this with an onclick and have no objection to using return false if it becomes necessary to use the alternative. Of course this is only if the alternative makes better sense over javascript:.
Also, I have yet to see a answer to my question shown (clearly I think) in the first paragraph. Thanks, david. :)
I have seen href="javascript:void(0)" and I have seen href="javascript:;" Is there any reason I would not just use href="javascript:" instead?
Personally I'd avoid using either. I'd have onclick='return false;' instead, and just set href='#'.
Why? Because if you put Javascript code in the href, then it appears in the browser's status bar when you hover over the link, just like any other URL. It just looks messy.
In fact, since it's going to be ignored anyway, you could put any URL you fancy into the href, not just a hash. The hash is safest, just in case your user has Javascript disabled, but aside from that point, it could be anything.
But I have to point out: having an <a> tag with the href going to a void Javascript code seems to rather defeat the point of having an <a> tag in the first place. I can see how you'd want to enable and disable a link at runtime, but simply setting the href to void does seem somewhat pointless. If it isn't going to be a real link, why not just have a <span> or some other tag. If you must make it look like a link, it's trivial to do that in CSS.
Doesn't answer you question but may shed a bit more light on it, some early versions of browsers like netscape had problems when a script was used within the href.
The void operator was pretty much to only way force the click to do nothing.
Now, with browsers properly implementing "pseudo URLs", you can safely just use javascript:;.
The ideal situation is to not put any code on the element itself, but rather use javascript in either a script tag, or in an external file and bind the event handler there.
It's better not to use either. The href attribute indicates a url. It's better to use event handlers to get the desired behaviour, which is probably the onclick event.
In this case the desired behaviour apparently is to do nothing. Firstly, why use an anchor tag at all when it doesn't link anywhere? Secondly, this can be handles by preventing event bubbling, by letting the onclick event handler return false. Then the href can either point to #, or better even to have it point to a url that more or less has the same effect as the event handler, so it will degrade gracefully when javascript is turned off.
in a code which i am goin through there is a link has href=javascript:; in code.when it is clicked it opens a lightbox to show some msg with close button.how is it done.I think this uses dojo
The code:
..
will actually do nothing. Generally this Nothing link allows some javascript code to use the onclick event instead. The onclick event triggers the window which may be from django or jquery or wherever.
EDITED:
i have just added this link that explane you how dojo work with onlclik event:
Dojo, how to do onclick event on a DIV
ok, just for the sake, all the answer here are good answer, in your particular case if you are using Dojo
the <a href="javascript:;" > simply prevent your <a> tag to jump around when clicked and of course have no action!
probably you have something like this in your code:
<a href="javascript:;" id="some" class="some_too" rel="some_too_too">
Dojo simply keep the <a> id OR class OR rel tags and execute the function!
href="javascript:somefunction();" is just a way to point to a function of some javascript code.
You can also do: href="#" onclick="somefunction();return false;"
Nothing really dojo about it. All it does is call the function or javascript code. It just tells the element to use javascript.
or href="javascript:void(0);" onclick="somefunction();" as stated already.
It's known as the javascript pseudo-protocol. It was designed to replace the contents of the document with a value calculated by JavaScript. It's best not to use it, for several reasons, including:
If JavaScript is disabled, you have a link that goes nowhere
If your JavaScript returns a value, the contents of the page will be replaced by that value
More reasons why you shouldn't use it
<a href="javascript:void(0)" onClick="callFunction();">
Call callFunction() method onClick
this can also be used as foollows
<a href="javascript:callFunction();">
<a href="#" onClick="callFunction();">
this also call javascript callFunction() method but it adds # in your URL to Avoid this Use
<a href="javascript:void(0)" onClick="callFunction();">
I believe this just indicates that your link is going to perform some javascript function. Usually you couple this by hooking up events on the link e.g. OnClick/OnMouseMove
All this does is make a call to a Javascript function which executes some Javascript. Maybe posting the code as an example helps.
Supposedly, it's a URL to a resource that's reachable via the "javascript" protocol, just like you can have "http:" or "ftp:". I don't know if it's an actual standard but most browsers understand that the URL must be fed to the JavaScript interpreter. So, in practice, you can use it to have JavaScript code that's triggered by a link, e.g.:
Say hello
Of course, writing your JavaScript code inside HTML tags is neither clean nor mantainable. But the possibility exists.
What about href="javascript:;"? If you pay close attention, you'll realise that ";" is a JavaScript code snippet that, well, does nothing. That's the point. This is often used to have a link that points nowhere. The main purpose is that clicking on it triggers JavaScript code defined somewhere else (via onclick event handlers).
Last but not least, you often see stuff like onclick="javascript:doStuff()". The onclick HTML attribute expects Javascript code, not a URL. In this situation, the javascript: prefix is totally superfluous. However, the code still runs. It happens to be a label in JavaScript syntax just by chance ;-)
In the 1990s, there was a fashion to put Javascript code directly into <a> href attributes, like this:
Press me!
And then suddenly I stopped to see it. They were all replaced by things like:
Press me!
For a link whose sole purpose is to trigger Javascript code, and has no real href target, why is it encouraged to use the onclick property instead of the href property?
The execution context is different, to see this, try these links instead:
Press me! <!-- result: undefined -->
Press me! <!-- result: A -->
javascript: is executed in the global context, not as a method of the element, which is usually want you want. In most cases you're doing something with or in relation to the element you acted on, better to execute it in that context.
Also, it's just much cleaner, though I wouldn't use in-line script at all. Check out any framework for handling these things in a much cleaner way. Example in jQuery:
$('a').click(function() { alert(this.tagName); });
Actually, both methods are considered obsolete. Developers are instead encouraged to separate all JavaScript in an external JS file in order to separate logic and code from genuine markup
http://www.alistapart.com/articles/behavioralseparation
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
The reason for this is that it creates code that is easier to maintain and debug, and it also promotes web standards and accessibility. Think of it like this: Looking at your example, what if you had hundreds of links like that on a page and needed to change out the alert behavior for some other function using external JS references, you'd only need to change a single event binding in one JS file as opposed to copying and pasting a bunch of code over and over again or doing a find-and-replace.
Couple of reasons:
Bad code practice:
The HREF tag is to indicate that there is a hyperlink reference to another location. By using the same tag for a javascript function which is not actually taking the user anywhere is bad programming practice.
SEO problems:
I think web crawlers use the HREF tag to crawl throughout the web site & link all the connected parts. By putting in javascript, we break this functionality.
Breaks accessibility:
I think some screen readers will not be able to execute the javascript & might not know how to deal with the javascript while they expect a hyperlink. User will expect to see a link in the browser status bar on hover of the link while they will see a string like: "javascript:" which might confuse them etc.
You are still in 1990's:
The mainstream advice is to have your javascript in a seperate file & not mingle with the HTML of the page as was done in 1990's.
HTH.
I open lots of links in new tabs - only to see javascript:void(0). So you annoy me, as well as yourself (because Google will see the same thing).
Another reason (also mentioned by others) is that different languages should be separated into different documents. Why? Well,
Mixed languages aren't well supported
by most IDEs and validators.
Embedding CSS and JS into HTML pages
(or anything else for that matter)
pretty much destroys opportunities to
have the embedded language checked for correctness
statically. Sometimes, the embedding language as well.
(A PHP or ASP document isn't valid HTML.)
You don't want syntax
errors or inconsistencies to show up
only at runtime.
Another reason is to have a cleaner separation between
the kinds of things you need to
specify: HTML for content, CSS for
layout, JS usually for more layout
and look-and-feel. These don't map
one to one: you usually want to apply
layout to whole categories of
content elements (hence CSS) and look and feel as well
(hence jQuery). They may be changed at different
times that the content elements are changed (in fact
the content is often generated on the fly) and by
different people. So it makes sense to keep them in
separate documents as well.
Using the javascript: protocol affects accessibility, and also hurts how SEO friendly your page is.
Take note that HTML stands for Hypter Text something something... Hyper Text denotes text with links and references in it, which is what an anchor element <a> is used for.
When you use the javascript: 'protocol' you're misusing the anchor element. Since you're misusing the <a> element, things like the Google Bot and the Jaws Screen reader will have trouble 'understanding' your page, since they don't care much about your JS but care plenty about the Hyper Text ML, taking special note of the anchor hrefs.
It also affects the usability of your page when a user who does not have JavaScript enabled visits your page; you're breaking the expected functionality and behavior of links for those users. It will look like a link, but it won't act like a link because it uses the javascript protocol.
You might think "but how many people have JavaScript disabled nowadays?" but I like to phrase that idea more along the lines of "How many potential customers am I willing to turn away just because of a checkbox in their browser settings?"
It boils down to how href is an HTML attribute, and as such it belongs to your site's information, not its behavior. The JavaScript defines the behavior, but your never want it to interfere with the data/information. The epitome of this idea would be the external JavaScript file; not using onclick as an attribute, but instead as an event handler in your JavaScript file.
Short Answer: Inline Javascript is bad for the reasons that inline CSS is bad.
The worst problem is probably that it breaks expected functionality.
For example, as others has pointed out, open in new window/tab = dead link = annoyed/confused users.
I always try to use onclick instead, and add something to the URL-hash of the page to indicate the desired function to trigger and add a check at pageload to check the hash and trigger the function.
This way you get the same behavior for clicks, new tab/window and even bookmarked/sent links, and things don't get to wacky if JS is off.
In other words, something like this (very simplified):
For the link:
onclick = "doStuff()"
href = "#dostuff"
For the page:
onLoad = if(hash="dostuff") doStuff();
Also, as long as we're talking about deprecation and semantics, it's probably worth pointing out that '</a>' doesn't mean 'clickable' - it means 'anchor,' and implies a link to another page. So it would make sense to use that tag to switch to a different 'view' in your application, but not to perform a computation. The fact that you don't have a URL in your href attribute should be a sign that you shouldn't be using an anchor tag.
You can, alternately, assign a click event action to nearly any html element - maybe an <h1>, an <img>, or a <p> would be more appropriate? At any rate, as other people have mentioned, add another attribute (an 'id' perhaps) that javascript can use as a 'hook' (document.getElementById) to get to the element and assign an onclick. That way you can keep your content (HTML) presentation (CSS) and interactivity (JavaScript) separated. And the world won't end.
I typically have a landing page called "EnableJavascript.htm" that has a big message on it saying "Javascript must be enabled for this feature to work". And then I setup my anchor tags like this...
<a href="EnableJavascript.htm" onclick="funcName(); return false;">
This way, the anchor has a legitimate destination that will get overwritten by your Javascript functionality whenever possible. This will degrade gracefully. Although, now a days, I generally build web sites with complete functionality before I decide to sprinkle some Javascript into the mix (which all together eliminates the need for anchors like this).
Using onclick attribute directly in the markup is a whole other topic, but I would recommend an unobtrusive approach with a library like jQuery.
I think it has to do with what the user sees in the status bar. Typically applications should be built for failover in case javascript isn't enabled however this isn't always the case.
With all the spamming that is going on people are getting smarter and when an email looks 'phishy' more and more people are looking at the status bar to see where the link will actually take them.
Remember to add 'return false;' to the end of your link so the page doesn't jump to the top on the user (unless that's the behaviour you are looking for).