login
I\'ve seen such href
s many times, but I don\'t know what exactly
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 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 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 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 element.
You can then change your 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 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.