Understanding "javascript : ... ;" inside <a href=" "> - javascript

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).

Related

How to avoid href="#" in javascript anchor links

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.

What to use as "href" attribute when i want a link to link nowhere and use it for running a script?

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).

Sole hash in anchor href?

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.

What does "javascript:void(0)" mean?

login
I've seen such hrefs many times, but I don't know what exactly that means.
The void operator evaluates the given
expression and then returns undefined.
The void operator is often used merely
to obtain the undefined primitive
value, usually using “void(0)” (which
is equivalent to “void 0”). In these
cases, the global variable undefined
can be used instead (assuming it has
not been assigned to a non-default
value).
An explanation is provided here: void operator.
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.
In addition to the technical answer, javascript:void means the author is Doing It Wrong.
There is no good reason to use a javascript: pseudo-URL(*). In practice it will cause confusion or errors should anyone try things like ‘bookmark link’, ‘open link in a new tab’, and so on. This happens quite a lot now people have got used to middle-click-for-new-tab: it looks like a link, you want to read it in a new tab, but it turns out to be not a real link at all, and gives unwanted results like a blank page or a JS error when middle-clicked.
<a href="#"> is a common alternative which might arguably be less bad. However you must remember to return false from your onclick event handler to prevent the link being followed and scrolling up to the top of the page.
In some cases there may be an actual useful place to point the link to. For example if you have a control you can click on that opens up a previously-hidden <div id="foo">, it makes some sense to use <a href="#foo"> to link to it. Or if there is a non-JavaScript way of doing the same thing (for example, ‘thispage.php?show=foo’ that sets foo visible to begin with), you can link to that.
Otherwise, if a link points only to some script, it is not really a link and should not be marked up as such. The usual approach would be to add the onclick to a <span>, <div>, or an <a> without an href and style it in some way to make it clear you can click on it. This is what StackOverflow [did at the time of writing; now it uses href="#"].
The disadvantage of this is that you lose keyboard control, since you can't tab onto a span/div/bare-a or activate it with space. Whether this is actually a disadvantage depends on what sort of action the element is intended to take. You can, with some effort, attempt to mimic the keyboard interactability by adding a tabIndex to the element, and listening for a Space keypress. But it's never going to 100% reproduce the real browser behaviour, not least because different browsers can respond to the keyboard differently (not to mention non-visual browsers).
If you really want an element that isn't a link but which can be activated as normal by mouse or keyboard, what you want is a <button type="button"> (or <input type="button"> is just as good, for simple textual contents). You can always use CSS to restyle it so it looks more like a link than a button, if you want. But since it behaves like a button, that's how really you should mark it up.
(*: in site authoring, anyway. Obviously they are useful for bookmarklets. javascript: pseudo-URLs are a conceptual bizarreness: a locator that doesn't point to a location, but instead calls active code inside the current location. They have caused massive security problems for both browsers and webapps, and should never have been invented by Netscape.)
It means it’ll do nothing. It’s an attempt to have the link not ‘navigate’ anywhere. But it’s not the right way.
You should actually just return false in the onclick event, like so:
hello
Typically it’s used if the link is doing some ‘JavaScript-y’ thing. Like posting an AJAX form, or swapping an image, or whatever. In that case you just make whatever function is being called return false.
To make your website completely awesome, however, generally you’ll include a link that does the same action, if the person browsing it chooses not to run JavaScript.
<a href="backup_page_displaying_image.aspx"
onclick="return coolImageDisplayFunction();">hello</a>
It is a very popular method of adding JavaScript functions to HTML links.For example: the [Print] links that you see on many webpages are written like this:
Print
Why do we need href while onclick alone can get the job done? Because when users hover over the text 'Print' when there's no href, the cursor will change to a caret (ꕯ) instead of a pointer (👆). Only having href on an a tag validates it as a hyperlink.
An alternative to href="javascript:void(0);", is the use of href="#". This alternative doesn't require JavaScript to be turned on in the user's browser, so it is more compatible.
There is a huge difference in the behaviour of # vs javascript:void(0);.
# scrolls you to the top of the page but javascript:void(0); does not.
This is very important if you are coding dynamic pages because the user does not want to go back to the top when they click a link on the page.
You should always have an href on your a tags. Calling a JavaScript function that returns 'undefined' will do just fine. So will linking to '#'.
Anchor tags in Internet Explorer 6 without an href do not get the a:hover style applied.
Yes, it is terrible and a minor crime against humanity, but then again so is Internet Explorer 6 in general.
I hope this helps.
Internet Explorer 6 is actually a major crime against humanity.
It's worth mentioning that you'll sometimes see void 0 when checking for undefined, simply because it requires fewer characters.
For example:
if (something === undefined) {
doSomething();
}
Compared to:
if (something === void 0) {
doSomething();
}
Some minification methods replace undefined with void 0 for this reason.
Usage of javascript:void(0) means that the author of the HTML is misusing the anchor element in place of the button element.
Anchor tags are often abused with the onclick event to create
pseudo-buttons by setting href to "#" or "javascript:void(0)" to
prevent the page from refreshing. These values cause unexpected
behavior when copying/dragging links, opening links in a new
tabs/windows, bookmarking, and when JavaScript is still downloading,
errors out, or is disabled. This also conveys incorrect semantics to
assistive technologies (e.g., screen readers). In these cases, it is
recommended to use a <button> instead. In general you should only use
an anchor for navigation using a proper URL.
Source: MDN's <a> Page.
Web Developers use javascript:void(0) because it is the easiest way to prevent the default behavior of a tag. void(*anything*) returns undefined and it is a falsy value. and returning a falsy value is like return false in onclick event of a tag that prevents its default behavior.
So I think javascript:void(0) is the simplest way to prevent the default behavior of a tag.
void is an operator that is used to return a undefined value so the browser will not be able to load a new page.
Web browsers will try and take whatever is used as a URL and load it unless it is a JavaScript function that returns null. For example, if we click a link like this:
Click Me
then an alert message will show up without loading a new page, and that 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.
An important thing to note about the void operator is that it requires a value and cannot be used by itself. We should use it like this:
I am a useless link
To understand this concept one should first understand the void operator in JavaScript.
The syntax for the void operator is: void «expr» which evaluates expr and returns undefined.
If you implement void as a function, it looks as follows:
function myVoid(expr) {
return undefined;
}
This void operator has one important usage that is - discarding the result of an expression.
In some situations, it is important to return undefined as opposed to the result of an expression. Then void can be used to discard that result. One such situation involves javascript: URLs, which should be avoided for links, but are useful for bookmarklets. When you visit one of those URLs, many browsers replace the current document with the result of evaluating the URLs “content”, but only if the result isn’t undefined. Hence, if you want to open a new window without changing the currently displayed content, you can do the following:
javascript:void window.open("http://example.com/")
A link must have an href target to be specified to enable it to be a usable display object.
Most browsers will not parse advanced JavaScript in the href of an <a> element, for example:
Get element
Because the href tag in most browsers does not allow whitespace or will convert whitespace to %20 (the HEX code for space), the JavaScript interpreter will run into multiple errors.
So if you want to use an <a> element's href to execute inline JavaScript, you must specify a valid value for href first that isn't too complex (doesn't contain whitespace), and then provide the JavaScript in an event attribute tag like onClick, onMouseOver, onMouseOut, etc.
The typical answer is to do something like this:
Get element
This works fine but it makes the page scroll to the top because the # in the href tells the browser to do this.
Placing a # in the <a> element's href specifies the root anchor, which is by default the top of the page, but you can specify a different location by specifying the name attribute inside an <a> element.
<a name="middleOfPage"></a>
You can then change your <a> element's href to jump to middleOfPage and execute the JavaScript in the onClick event:
Get element
There will be many times where you do not want that link jumping around, so you can do two things:
Get element
Now it will go nowhere when clicked, but it could cause the page to re-centre itself from its current viewport.
The best way to use in-line javascript using an <a> element's href, but without having to do any of the above is JavaScript:void(0);:
Get element
This tells the browser no to go anywhere, but instead execute the JavaScript:void(0); function in the href because it contains no whitespace, and will not be parsed as a URL. It will instead be run by the compiler.
void is a keyword which, when supplied with a parameter of 0 returns undefined, which does not use any more resources to handle a return value that would occur without specifying the 0 (it is more memory-management/performance friendly).
The next thing that happens is the onClick gets executed. The page does not move, nothing happens display-wise.
The void operator evaluates the given expression and then returns undefined.
It avoids refreshing the page.
From what I've seen, the void operator has 3 common uses in JavaScript. The one that you're referring to, <a href="javascript:void(0)"> is a common trick to make an <a> tag a no-op. Some browsers treat <a> tags differently based on whether they have a href , so this is a way to create a link with a href that does nothing.
The void operator is a unary operator that takes an argument and returns undefined. So var x = void 42; means x === undefined. This is useful because, outside of strict mode, undefined is actually a valid variable name. So some JavaScript developers use void 0 instead of undefined. In theory, you could also do <a href="javascript:undefined"> and it would so the same thing as void(0).

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