url link as on and off button without following url [duplicate] - javascript

The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?
function myJsFunc() {
alert("myJsFunc");
}
Run JavaScript Code
or
function myJsFunc() {
alert("myJsFunc");
}
Run JavaScript Code

I use javascript:void(0).
Three reasons. Encouraging the use of # amongst a team of developers inevitably leads to some using the return value of the function called like this:
function doSomething() {
//Some code
return false;
}
But then they forget to use return doSomething() in the onclick and just use doSomething().
A second reason for avoiding # is that the final return false; will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.
A third reason is that there are cases where the onclick event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my onclick (or on anything) in HTML markup look like this:
onclick="someFunc.call(this)"
OR
onclick="someFunc.apply(this, arguments)"
Using javascript:void(0) avoids all of the above headaches, and I haven't found any examples of a downside.
So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:
Use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.
OR
Use href="javascript:void(0)"
The second is clearly much easier to communicate.

Neither.
If you can have an actual URL that makes sense use that as the HREF. The onclick won't fire if someone middle-clicks on your link to open a new tab or if they have JavaScript disabled.
If that is not possible, then you should at least inject the anchor tag into the document with JavaScript and the appropriate click event handlers.
I realize this isn't always possible, but in my opinion it should be striven for in developing any public website.
Check out Unobtrusive JavaScript and Progressive enhancement (both Wikipedia).

Doing Link or Link or whatever else that contains an onclick attribute - was okay back five years ago, though now it can be a bad practice. Here's why:
It promotes the practice of obtrusive JavaScript - which has turned out to be difficult to maintain and difficult to scale. More on this in Unobtrusive JavaScript.
You're spending your time writing incredibly overly verbose code - which has very little (if any) benefit to your codebase.
There are now better, easier, and more maintainable and scalable ways of accomplishing the desired result.
The unobtrusive JavaScript way
Just don't have a href attribute at all! Any good CSS reset would take care of the missing default cursor style, so that is a non-issue. Then attach your JavaScript functionality using graceful and unobtrusive best practices - which are more maintainable as your JavaScript logic stays in JavaScript, instead of in your markup - which is essential when you start developing large scale JavaScript applications which require your logic to be split up into blackboxed components and templates. More on this in Large-scale JavaScript Application Architecture
Simple code example
// Cancel click event
$('.cancel-action').click(function(){
alert('Cancel action occurs!');
});
// Hover shim for Internet Explorer 6 and Internet Explorer 7.
$(document.body).on('hover','a',function(){
$(this).toggleClass('hover');
});
a { cursor: pointer; color: blue; }
a:hover,a.hover { text-decoration: underline; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="cancel-action">Cancel this action</a>
A blackboxed Backbone.js example
For a scalable, blackboxed, Backbone.js component example - see this working jsfiddle example here. Notice how we utilize unobtrusive JavaScript practices, and in a tiny amount of code have a component that can be repeated across the page multiple times without side-effects or conflicts between the different component instances. Amazing!
Notes
Omitting the href attribute on the a element will cause the element to not be accessible using tab key navigation. If you wish for those elements to be accessible via the tab key, you can set the tabindex attribute, or use button elements instead. You can easily style button elements to look like normal links as mentioned in Tracker1's answer.
Omitting the href attribute on the a element will cause Internet Explorer 6 and Internet Explorer 7 to not take on the a:hover styling, which is why we have added a simple JavaScript shim to accomplish this via a.hover instead. Which is perfectly okay, as if you don't have a href attribute and no graceful degradation then your link won't work anyway - and you'll have bigger issues to worry about.
If you want your action to still work with JavaScript disabled, then using an a element with a href attribute that goes to some URL that will perform the action manually instead of via an Ajax request or whatever should be the way to go. If you are doing this, then you want to ensure you do an event.preventDefault() on your click call to make sure when the button is clicked it does not follow the link. This option is called graceful degradation.

'#' will take the user back to the top of the page, so I usually go with void(0).
javascript:; also behaves like javascript:void(0);

I would honestly suggest neither. I would use a stylized <button></button> for that behavior.
button.link {
display: inline-block;
position: relative;
background-color: transparent;
cursor: pointer;
border: 0;
padding: 0;
color: #00f;
text-decoration: underline;
font: inherit;
}
<p>A button that looks like a <button type="button" class="link">link</button>.</p>
This way you can assign your onclick. I also suggest binding via script, not using the onclick attribute on the element tag. The only gotcha is the psuedo 3d text effect in older IEs that cannot be disabled.
If you MUST use an A element, use javascript:void(0); for reasons already mentioned.
Will always intercept in case your onclick event fails.
Will not have errant load calls happen, or trigger other events based on a hash change
The hash tag can cause unexpected behavior if the click falls through (onclick throws), avoid it unless it's an appropriate fall-through behavior, and you want to change the navigation history.
NOTE: You can replace the 0 with a string such as javascript:void('Delete record 123') which can serve as an extra indicator that will show what the click will actually do.

The first one, ideally with a real link to follow in case the user has JavaScript disabled. Just make sure to return false to prevent the click event from firing if the JavaScript executes.
Link
If you use Angular2, this way works:
<a [routerLink]="" (click)="passTheSalt()">Click me</a>.
See here https://stackoverflow.com/a/45465728/2803344

Neither if you ask me;
If your "link" has the sole purpose of running some JavaScript code it doesn't qualify as a link; rather a piece of text with a JavaScript function coupled to it. I would recommend to use a <span> tag with an onclick handler attached to it and some basic CSS to immitate a link. Links are made for navigation, and if your JavaScript code isn't for navigation it should not be an <a> tag.
Example:
function callFunction() { console.log("function called"); }
.jsAction {
cursor: pointer;
color: #00f;
text-decoration: underline;
}
<p>I want to call a JavaScript function <span class="jsAction" onclick="callFunction();">here</span>.</p>

Ideally you'd do this:
Link text
Or, even better, you'd have the default action link in the HTML, and you'd add the onclick event to the element unobtrusively via JavaScript after the DOM renders, thus ensuring that if JavaScript is not present/utilized you don't have useless event handlers riddling your code and potentially obfuscating (or at least distracting from) your actual content.

Using just # makes some funny movements, so I would recommend to use #self if you would like to save on typing efforts of JavaScript bla, bla,.

I use the following
Link
instead
Link

I recommend using a <button> element instead, especially if the control is supposed to produce a change in the data. (Something like a POST.)
It's even better if you inject the elements unobtrusively, a type of progressive enhancement. (See this comment.)

I agree with suggestions elsewhere stating that you should use regular URL in href attribute, then call some JavaScript function in onclick. The flaw is, that they automaticaly add return false after the call.
The problem with this approach is, that if the function will not work or if there will be any problem, the link will become unclickable. Onclick event will always return false, so the normal URL will not be called.
There's very simple solution. Let function return true if it works correctly. Then use the returned value to determine if the click should be cancelled or not:
JavaScript
function doSomething() {
alert( 'you clicked on the link' );
return true;
}
HTML
link text
Note, that I negate the result of the doSomething() function. If it works, it will return true, so it will be negated (false) and the path/to/some/URL will not be called. If the function will return false (for example, the browser doesn't support something used within the function or anything else goes wrong), it is negated to true and the path/to/some/URL is called.

# is better than javascript:anything, but the following is even better:
HTML:
For great justice
JavaScript:
$(function() {
$(".some-selector").click(myJsFunc);
});
You should always strive for graceful degradation (in the event that the user doesn't have JavaScript enabled...and when it is with specs. and budget). Also, it is considered bad form to use JavaScript attributes and protocol directly in HTML.

Unless you're writing out the link using JavaScript (so that you know it's enabled in the browser), you should ideally be providing a proper link for people who are browsing with JavaScript disabled and then prevent the default action of the link in your onclick event handler. This way those with JavaScript enabled will run the function and those with JavaScript disabled will jump to an appropriate page (or location within the same page) rather than just clicking on the link and having nothing happen.

Definitely hash (#) is better because in JavaScript it is a pseudoscheme:
pollutes history
instantiates new copy of engine
runs in global scope and doesn't respect event system.
Of course "#" with an onclick handler which prevents default action is [much] better. Moreover, a link that has the sole purpose to run JavaScript is not really "a link" unless you are sending user to some sensible anchor on the page (just # will send to top) when something goes wrong. You can simply simulate look and feel of link with stylesheet and forget about href at all.
In addition, regarding cowgod's suggestion, particularly this: ...href="javascript_required.html" onclick="... This is good approach, but it doesn't distinguish between "JavaScript disabled" and "onclick fails" scenarios.

I usually go for
Link description
It's shorter than javascript:void(0) and does the same.

I choose use javascript:void(0), because use this could prevent right click to open the content menu. But javascript:; is shorter and does the same thing.

I would use:
Link
Reasons:
This makes the href simple, search engines need it. If you use anything else ( such as a string), it may cause a 404 not found error.
When mouse hovers over the link, it doesn't show that it is a script.
By using return false;, the page doesn't jump to the top or break the back button.

Don't use links for the sole purpose of running JavaScript.
The use of href="#" scrolls the page to the top; the use of void(0) creates navigational problems within the browser.
Instead, use an element other than a link:
<span onclick="myJsFunc()" class="funcActuator">myJsFunc</span>
And style it with CSS:
.funcActuator {
cursor: default;
}
.funcActuator:hover {
color: #900;
}

So, when you are doing some JavaScript things with an <a /> tag and if you put href="#" as well, you can add return false at the end of the event (in case of inline event binding) like:
Run JavaScript Code
Or you can change the href attribute with JavaScript like:
Run JavaScript Code
or
Run JavaScript Code
But semantically, all the above ways to achieve this are wrong (it works fine though). If any element is not created to navigate the page and that have some JavaScript things associated with it, then it should not be a <a> tag.
You can simply use a <button /> instead to do things or any other element like b, span or whatever fits there as per your need, because you are allowed to add events on all the elements.
So, there is one benefit to use <a href="#">. You get the cursor pointer by default on that element when you do a href="#". For that, I think you can use CSS for this like cursor:pointer; which solves this problem also.
And at the end, if you are binding the event from the JavaScript code itself, there you can do event.preventDefault() to achieve this if you are using <a> tag, but if you are not using a <a> tag for this, there you get an advantage, you don't need to do this.
So, if you see, it's better not to use a tag for this kind of stuff.

It would be better to use jQuery,
$(document).ready(function() {
$("a").css("cursor", "pointer");
});
and omit both href="#" and href="javascript:void(0)".
The anchor tag markup will be like
<a onclick="hello()">Hello</a>
Simple enough!

Usually, you should always have a fall back link to make sure that clients with JavaScript disabled still has some functionality. This concept is called unobtrusive JavaScript.
Example... Let's say you have the following search link:
Search
You can always do the following:
var link = document.getElementById('searchLink');
link.onclick = function() {
try {
// Do Stuff Here
} finally {
return false;
}
};
That way, people with JavaScript disabled are directed to search.php while your viewers with JavaScript view your enhanced functionality.

If you happen to be using AngularJS, you can use the following:
Do some fancy JavaScript
Which will not do anything.
In addition
It will not take you to the top of the page, as with (#)
Therefore, you don't need to explicitly return false with JavaScript
It is short an concise

Depending on what you want to accomplish, you could forget the onclick and just use the href:
Link Text
It gets around the need to return false. I don't like the # option because, as mentioned, it will take the user to the top of the page. If you have somewhere else to send the user if they don't have JavaScript enabled (which is rare where I work, but a very good idea), then Steve's proposed method works great.
Link text
Lastly, you can use javascript:void(0) if you do not want anyone to go anywhere and if you don't want to call a JavaScript function. It works great if you have an image you want a mouseover event to happen with, but there's not anything for the user to click on.

I believe you are presenting a false dichotomy. These are not the only two options.
I agree with Mr. D4V360 who suggested that, even though you are using the anchor tag, you do not truly have an anchor here. All you have is a special section of a document that should behave slightly different. A <span> tag is far more appropriate.

I tried both in google chrome with the developer tools, and the id="#" took 0.32 seconds. While the javascript:void(0) method took only 0.18 seconds. So in google chrome, javascript:void(0) works better and faster.

I personally use them in combination. For example:
HTML
Link
with little bit of jQuery
$('a[href="#"]').attr('href','javascript:void(0);');
or
$('a[href="#"]').click(function(e) {
e.preventDefault();
});
But I'm using that just for preventing the page jumping to the top when the user clicks on an empty anchor. I'm rarely using onClick and other on events directly in HTML.
My suggestion would be to use <span> element with the class attribute instead of
an anchor. For example:
<span class="link">Link</span>
Then assign the function to .link with a script wrapped in the body and just before the </body> tag or in an external JavaScript document.
<script>
(function($) {
$('.link').click(function() {
// do something
});
})(jQuery);
</script>
*Note: For dynamically created elements, use:
$('.link').on('click', function() {
// do something
});
And for dynamically created elements which are created with dynamically created elements, use:
$(document).on('click','.link', function() {
// do something
});
Then you can style the span element to look like an anchor with a little CSS:
.link {
color: #0000ee;
text-decoration: underline;
cursor: pointer;
}
.link:active {
color: red;
}
Here's a jsFiddle example of above aforementioned.

On a modern website the use of href should be avoided if the element is only doing JavaScript functionality (not a real link).
Why?
The presence of this element tells the browser that this is a link with a destination.
With that, the browser will show the Open In New Tab / Window function (also triggered when you use shift+click).
Doing so will result in opening the same page without the desired function triggered (resulting in user frustration).
In regards to IE:
As of IE8, element styling (including hover) works if the doctype is set. Other versions of IE are not really to worry about anymore.
Only Drawback:
Removing HREF removes the tabindex.
To overcome this, you can use a button that's styled as a link or add a tabindex attribute using JS.

When I've got several faux-links, I prefer to give them a class of 'no-link'.
Then in jQuery, I add the following code:
$(function(){
$('.no-link').click(function(e){
e.preventDefault();
});
});
And for the HTML, the link is simply
Faux-Link
I don't like using Hash-Tags unless they're used for anchors, and I only do the above when I've got more than two faux-links, otherwise I go with javascript:void(0).
Faux-Link
Typically, I like to just avoid using a link at all and just wrap something around in a span and use that as a way to active some JavaScript code, like a pop-up or a content-reveal.

It's nice to have your site be accessible by users with JavaScript disabled, in which case the href points to a page that performs the same action as the JavaScript being executed. Otherwise I use "#" with a "return false;" to prevent the default action (scroll to top of the page) as others have mentioned.
Googling for "javascript:void(0)" provides a lot of information on this topic. Some of them, like this one mention reasons to NOT use void(0).

Related

How to avoid anchor links from jumping/scrolling [duplicate]

When I have a link that is wired-up with a jQuery or JavaScript event such as:
My Link
How do I prevent the page from scrolling to the top? When I remove the href attribute from the anchor the page doesn't scroll to the top but the link doesn't appear to be click-able.
You need to prevent the default action for the click event (i.e. navigating to the link target) from occurring.
There are two ways to do this.
Option 1: event.preventDefault()
Call the .preventDefault() method of the event object passed to your handler. If you're using jQuery to bind your handlers, that event will be an instance of jQuery.Event and it will be the jQuery version of .preventDefault(). If you're using addEventListener to bind your handlers, it will be an Event and the raw DOM version of .preventDefault(). Either way will do what you need.
Examples:
$('#ma_link').click(function($e) {
$e.preventDefault();
doSomething();
});
document.getElementById('#ma_link').addEventListener('click', function (e) {
e.preventDefault();
doSomething();
})
Option 2: return false;
In jQuery:
Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault()
So, with jQuery, you can alternatively use this approach to prevent the default link behaviour:
$('#ma_link').click(function(e) {
doSomething();
return false;
});
If you're using raw DOM events, this will also work on modern browsers, since the HTML 5 spec dictates this behaviour. However, older versions of the spec did not, so if you need maximum compatibility with older browsers, you should call .preventDefault() explicitly. See event.preventDefault() vs. return false (no jQuery) for the spec detail.
You can set your href to #! instead of #
For example,
Link
will not do any scrolling when clicked.
Beware! This will still add an entry to the browser's history when clicked, meaning that after clicking your link, the user's back button will not take them to the page they were previously on. For this reason, it's probably better to use the .preventDefault() approach, or to use both in combination.
Here is a Fiddle illustrating this (just scrunch your browser down until your get a scrollbar):
http://jsfiddle.net/9dEG7/
For the spec nerds - why this works:
This behaviour is specified in the HTML5 spec under the Navigating to a fragment identifier section. The reason that a link with a href of "#" causes the document to scroll to the top is that this behaviour is explicitly specified as the way to handle an empty fragment identifier:
2. If fragid is the empty string, then the indicated part of the document is the top of the document
Using a href of "#!" instead works simply because it avoids this rule. There's nothing magic about the exclamation mark - it just makes a convenient fragment identifier because it's noticeably different to a typical fragid and unlikely to ever match the id or name of an element on your page. Indeed, we could put almost anything after the hash; the only fragids that won't suffice are the empty string, the word 'top', or strings that match name or id attributes of elements on the page.
More exactly, we just need a fragment identifier that will cause us to fall through to step 8 in the following algorithm for determining the indicated part of the document from the fragid:
Apply the URL parser algorithm to the URL, and let fragid be the fragment component of the resulting parsed URL.
If fragid is the empty string, then the indicated part of the document is the top of the document; stop the algorithm here.
Let fragid bytes be the result of percent-decoding fragid.
Let decoded fragid be the result of applying the UTF-8 decoder algorithm to fragid bytes. If the UTF-8 decoder emits a decoder error, abort the decoder and instead jump to the step labeled no decoded fragid.
If there is an element in the DOM that has an ID exactly equal to decoded fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
No decoded fragid: If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid (not decoded fragid), then the first such element in tree order is the indicated part of the document; stop the algorithm here.
If fragid is an ASCII case-insensitive match for the string top, then the indicated part of the document is the top of the document; stop the algorithm here.
Otherwise, there is no indicated part of the document.
As long as we hit step 8 and there is no indicated part of the document, the following rule comes into play:
If there is no indicated part ... then the user agent must do nothing.
which is why the browser doesn't scroll.
An easy approach is to leverage this code:
Link Title
This approach doesn't force a page refresh, so the scrollbar stays in place. Also, it allows you to programmatically change the onclick event and handle client side event binding using jQuery.
For these reasons, the above solution is better than:
Link Title
Link Title
where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.
You should change the
My Link
to
My Link
This way when the link is clicked the page won't scroll to top. This is cleaner than using href="#" and then preventing the default event from running.
I have good reasons for this on the first answer to this question, like the return false; will not execute if the called function throws an error, or you may add the return false; to a doSomething() function and then forget to use return doSomething();
Returning false from the code you're calling will work and in a number of circumstances is the preferred method but you can also so this
Link Title
When it comes to SEO it really depends on what your link is going to be used for. If you are going to actually use it to link to some other content then I would agree ideally you would want something meaningful here but if you are using the link for functionality purposes maybe like Stack Overflow does for the post toolbar (bold, italic, hyperlink, etc) then it probably doesn't matter.
Try this:
My Link
If you can simply change the href value, you should use:
Link Title
Another neat solution I just came up with is to use jQuery to stop the click action from occurring and causing the page to scroll, but only for href="#" links.
<script type="text/javascript">
/* Stop page jumping when links are pressed */
$('a[href="#"]').live("click", function(e) {
return false; // prevent default click action from happening!
e.preventDefault(); // same thing as above
});
</script>
Link to something more sensible than the top of the page in the first place. Then cancel the default event.
See rule 2 of pragmatic progressive enhancement.
Also, you can use event.preventDefault inside onclick attribute.
doSmth
No need to write exstra click event.
For Bootstrap 3 for collapse, if you don't specify data-target on the anchor and rely on href to determine the target, the event will be prevented. If you use data-target you'll need to prevent the event yourself.
<button type="button" class="btn btn-default" data-toggle="collapse" data-target="#demo">Collapse This</button>
<div id="demo" class="collapse">
<p>Lorem ipsum dolor sit amet</p>
</div>
event.preventDefault() will stop the scrolling but also not change the link state to visited (color), which I need.
The "3 years late" solution is not too late and eliminates unforseen side-effects.
The hrefs I create are in a loop (indexed by "i") "#i!", where i is the index to an array containing the text for the anchor tag.
Works like a charm. (Just #i would work too, except I have other ids set to i).
While I'd like to use the `href='javascript:function()'` approach, this adds 11 bytes (javascript:) plus the bytes of the function name plus parameters to the page size. Mutiply this by 1000+ hrefs and thats 16kb+ added to the page size. (Yes, pagination would help but not for the user). So maybe in a different situation I'd go with the javascript: solution.
You can simply write like this also:-
Delete User
When calling the function, follow it by return false
example:
<input type="submit" value="Add" onclick="addNewPayment();return false;">
Create a page which contains two links- one at the top and one at the bottom. On clicking the top link, the page has to scroll down to the bottom of the page where bottom link is present. On clicking the bottom link, the page has to scroll up to the top of the page.
<a onclick="yourfunction()">
this will work fine . no need to add href="#"
You might want to check your CSS. In the example here: https://css-tricks.com/the-checkbox-hack/ there's position: absolute; top: -9999px;. This is particularly goofy on Chrome, as onclick="whatever" still jumps to the absolute position of the clicked element.
Removing position: absolute; top: -9999px;, for display: none; might help.

How can I specify an anchor tag behaves like a hyperlink, without an href and without an anchor name?

Okay so this one has some similar threads but I couldn't find anything that nailed it on the head, so here we go.
I'm trying to simulate a link using the anchor tag, like so:
<a onClick="javascript: DownloadPorn();">Click Here!</a>
All of this works fine and dandy; the link shows, I can click it, and my javascript method is successfully executed.
The question here, is how can I correctly force the link to display in the 'same manner' as an actual 'HTML Link'? Or rather, in the 'same manner' as if I were to have an href in the above mentioned tag; like so:
Click Here!
Now... THIS Code snippet forces the link to display in the manner that I expect it to, but in using this method, when a link is clicked, the scroll location is bounced back to the top.
It's probably clear, that this is not an intended behavior for the framework I am trying to develop. If anyone has any suggestions to overcome this particular issue, I would greatly appreciate your input.
--- While typing this all up, I considered that I could place a static anchor at the top of the screen( say 0,0 or -,- ), and force all of my links to reference that anchor. If anyone sees any viability in this solution, I'm likely to explore it.
--- Edited ---
Accepted Answer:
In order to have an anchor behave as a hyperlink, without manipulating the browsers current position; utilize a Javascript method returning nothing(?) in the href attribute, or a valid return of 'false' in one of the alternate event handlers for an anchor, I.E. the onClick method.
Possible solutions:
Link
Link
Link
Thanks again, everyone.
--- End Edit ---
If you use return false at the end of your onclick attribute it will not make it scroll anywhere.
Click Here!
or you can make your function return false, and return its result (false) as well as execute it in the onclick attribute, which is shorter:
<script type="text/javascript">
function someFunc() {
// all your function code here
return false;
}
</script>
Click Here!
Set the javascript function to the href.
Click Here!
Edit: Just to note some consider this bad practice.
Set the href to javascript:void(0);, this will mean the browser displays the link as if it had a real href:
Click Here!
There are other methods such as setting the href to #, but the advantage of the one shown is that you don't have to worry about returning false or specifying return DownloadBooks().
This question has some good info about the use of javascript:void(0).

What does href expression do?

I have seen the following href used in webpages from time to time. However, I don't understand what this is trying to do or the technique. Can someone elaborate please?
An <a> element is invalid HTML unless it has either an href or name attribute.
If you want it to render correctly as a link (ie underlined, hand pointer, etc), then it will only do so if it has a href attribute.
Code like this is therefore sometimes used as a way of making a link, but without having to provide an actual URL in the href attribute. The developer obviously wanted the link itself not to do anything, and this was the easiest way he knew.
He probably has some javascript event code elsewhere which is triggered when the link is clicked, and that will be what he wants to actually happen, but he wants it to look like a normal <a> tag link.
Some developers use href='#' for the same purpose, but this causes the browser to jump to the top of the page, which may not be wanted. And he couldn't simply leave the href blank, because href='' is a link back to the current page (ie it causes a page refresh).
There are ways around these things. Using an empty bit of Javascript code in the href is one of them, and although it isn't the best solution, it does work.
basically instead of using the link to move pages (or anchors), using this method launches a javascript function(s)
<script>
function doSomething() {
alert("hello")
}
</script>
click me
clicking the link will fire the alert.
There are several mechanisms to avoid a link to reach its destination. The one from the question is not much intuitive.
A cleaner option is to use href="#no" where #no is a non-defined anchor in the document.
You can use a more semantic name such as #disable, or #action to increase readability.
Benefits of the approach:
Avoids the "moving to the top" effect of the empty href="#"
Avoids the use of javascript
Drawbacks:
You must be sure the anchor name is not used in the document.
The URL changes to include the (non-existing) anchor as fragment and a new browser history entry is created. This means that clicking the "back" button after clicking the link won't behave as expected.
Since the <a> element is not acting as a link, the best option in these cases is not using an <a> element but a <div> and provide the desired link-like style.
is just shorthand for:
It's used to write js codes inside of href instead of event listeners like onclick and avoiding # links in href to make a tags valid for HTML.
Interesting fact
I had a research on how to use javascript: inside of href attribute and got the result that I can write multiple lines in it!
<a href="
javascript:
a = 4;
console.log(a++);
a += 2;
console.log(a++);
if(a < 6){
console.log('a is lower than 6');
}
else
console.log('a is greater than 6');
function log(s){
console.log(s);
}
log('function implementation working too');
">Click here</a>
Tested in chrome Version 68.0.3440.106 (Official Build) (64-bit)
Tested in Firefox Quantum 61.0.1 (64-bit)
It is a way of making a link do absolutely nothing when clicked (unless Javascript events are bound to it).
It is a way of running Javascript instead of following a link:
link
When there isn't actually javascript to run (like your example) it does nothing.
Refer to this:
Link to the website opened in different tab
Link to the div in the page(look at the chaneged url)
Nothing happens if there is no javaScript to render
javascript: tells the browser going to write javascript code
Old thread but thought I'd just add that the reason developers use this construct is not to create a dead link, but because javascript URLs for some reason do not pass references to the active html element correctly.
e.g. handler_function(this.id) works as onClick but not as a javascript URL.
Thus it's a choice between writing pedantically standards-compliant code that involves you in having to manually adjust the call for each hyperlink, or slightly non-standard code which can be written once and used everywhere.
Since it is a styling issue, instead of polluting the HTML with non valid syntax, you could/should use a W3 valid workaround:
Format the HTML properly, without href, following the W3 accessibility guide lines for buttons.
Use CSS to fix the initial goal of applying a clickable UX effect on a control.
Here's a live example for you to try the UX.
HTML
<a role="button" aria-pressed="false">Underlined + Pointer</a>
<a role="button" aria-pressed="false" class="btn">Pointer</a>
CSS
a[role="button"]:not([href]):not(.btn) { text-decoration: underline; }
a[role="button"]:not([href]) { cursor: pointer; }
I was searching for a solution that does not refresh pages but opens menu items on Ipads and phones.
I tried it on also mobile, It works well
Dr
1. Use that java script to Clear an HTML row Or Delete a row using the id set to a span and use JQuery to set a function to that span's click event.
2. Dynamically set the div html to a string variable and replace {id} with a 1 or 2 etc. cell of a larger div table and rows
<div class="table-cell">
<span id="clearRow{id}">
Clear
</span>
</div>
<div class="table-cell">
<span id="deleteRow{id}">
Delete
</span>
</div>
//JQuery - Clear row
$("#clearRow" + idNum).click(function(){
$("someIDOrWildcardSelector" + idNum).val("");
$("someIDOrWildcardSelector" + idNum).val("");
$("someIDOrWildcardSelector" + idNum).val("");
});
//JQuery to remove / delete an html row
$("#deleteRow" + idNum).click(function(){
//depending upon levels of parent / child use 1 to many .parent().parent().parent()
$(this).parent().remove();
});

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

When I have a link that is wired-up with a jQuery or JavaScript event such as:
My Link
How do I prevent the page from scrolling to the top? When I remove the href attribute from the anchor the page doesn't scroll to the top but the link doesn't appear to be click-able.
You need to prevent the default action for the click event (i.e. navigating to the link target) from occurring.
There are two ways to do this.
Option 1: event.preventDefault()
Call the .preventDefault() method of the event object passed to your handler. If you're using jQuery to bind your handlers, that event will be an instance of jQuery.Event and it will be the jQuery version of .preventDefault(). If you're using addEventListener to bind your handlers, it will be an Event and the raw DOM version of .preventDefault(). Either way will do what you need.
Examples:
$('#ma_link').click(function($e) {
$e.preventDefault();
doSomething();
});
document.getElementById('#ma_link').addEventListener('click', function (e) {
e.preventDefault();
doSomething();
})
Option 2: return false;
In jQuery:
Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault()
So, with jQuery, you can alternatively use this approach to prevent the default link behaviour:
$('#ma_link').click(function(e) {
doSomething();
return false;
});
If you're using raw DOM events, this will also work on modern browsers, since the HTML 5 spec dictates this behaviour. However, older versions of the spec did not, so if you need maximum compatibility with older browsers, you should call .preventDefault() explicitly. See event.preventDefault() vs. return false (no jQuery) for the spec detail.
You can set your href to #! instead of #
For example,
Link
will not do any scrolling when clicked.
Beware! This will still add an entry to the browser's history when clicked, meaning that after clicking your link, the user's back button will not take them to the page they were previously on. For this reason, it's probably better to use the .preventDefault() approach, or to use both in combination.
Here is a Fiddle illustrating this (just scrunch your browser down until your get a scrollbar):
http://jsfiddle.net/9dEG7/
For the spec nerds - why this works:
This behaviour is specified in the HTML5 spec under the Navigating to a fragment identifier section. The reason that a link with a href of "#" causes the document to scroll to the top is that this behaviour is explicitly specified as the way to handle an empty fragment identifier:
2. If fragid is the empty string, then the indicated part of the document is the top of the document
Using a href of "#!" instead works simply because it avoids this rule. There's nothing magic about the exclamation mark - it just makes a convenient fragment identifier because it's noticeably different to a typical fragid and unlikely to ever match the id or name of an element on your page. Indeed, we could put almost anything after the hash; the only fragids that won't suffice are the empty string, the word 'top', or strings that match name or id attributes of elements on the page.
More exactly, we just need a fragment identifier that will cause us to fall through to step 8 in the following algorithm for determining the indicated part of the document from the fragid:
Apply the URL parser algorithm to the URL, and let fragid be the fragment component of the resulting parsed URL.
If fragid is the empty string, then the indicated part of the document is the top of the document; stop the algorithm here.
Let fragid bytes be the result of percent-decoding fragid.
Let decoded fragid be the result of applying the UTF-8 decoder algorithm to fragid bytes. If the UTF-8 decoder emits a decoder error, abort the decoder and instead jump to the step labeled no decoded fragid.
If there is an element in the DOM that has an ID exactly equal to decoded fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
No decoded fragid: If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid (not decoded fragid), then the first such element in tree order is the indicated part of the document; stop the algorithm here.
If fragid is an ASCII case-insensitive match for the string top, then the indicated part of the document is the top of the document; stop the algorithm here.
Otherwise, there is no indicated part of the document.
As long as we hit step 8 and there is no indicated part of the document, the following rule comes into play:
If there is no indicated part ... then the user agent must do nothing.
which is why the browser doesn't scroll.
An easy approach is to leverage this code:
Link Title
This approach doesn't force a page refresh, so the scrollbar stays in place. Also, it allows you to programmatically change the onclick event and handle client side event binding using jQuery.
For these reasons, the above solution is better than:
Link Title
Link Title
where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.
You should change the
My Link
to
My Link
This way when the link is clicked the page won't scroll to top. This is cleaner than using href="#" and then preventing the default event from running.
I have good reasons for this on the first answer to this question, like the return false; will not execute if the called function throws an error, or you may add the return false; to a doSomething() function and then forget to use return doSomething();
Returning false from the code you're calling will work and in a number of circumstances is the preferred method but you can also so this
Link Title
When it comes to SEO it really depends on what your link is going to be used for. If you are going to actually use it to link to some other content then I would agree ideally you would want something meaningful here but if you are using the link for functionality purposes maybe like Stack Overflow does for the post toolbar (bold, italic, hyperlink, etc) then it probably doesn't matter.
Try this:
My Link
If you can simply change the href value, you should use:
Link Title
Another neat solution I just came up with is to use jQuery to stop the click action from occurring and causing the page to scroll, but only for href="#" links.
<script type="text/javascript">
/* Stop page jumping when links are pressed */
$('a[href="#"]').live("click", function(e) {
return false; // prevent default click action from happening!
e.preventDefault(); // same thing as above
});
</script>
Link to something more sensible than the top of the page in the first place. Then cancel the default event.
See rule 2 of pragmatic progressive enhancement.
Also, you can use event.preventDefault inside onclick attribute.
doSmth
No need to write exstra click event.
For Bootstrap 3 for collapse, if you don't specify data-target on the anchor and rely on href to determine the target, the event will be prevented. If you use data-target you'll need to prevent the event yourself.
<button type="button" class="btn btn-default" data-toggle="collapse" data-target="#demo">Collapse This</button>
<div id="demo" class="collapse">
<p>Lorem ipsum dolor sit amet</p>
</div>
event.preventDefault() will stop the scrolling but also not change the link state to visited (color), which I need.
The "3 years late" solution is not too late and eliminates unforseen side-effects.
The hrefs I create are in a loop (indexed by "i") "#i!", where i is the index to an array containing the text for the anchor tag.
Works like a charm. (Just #i would work too, except I have other ids set to i).
While I'd like to use the `href='javascript:function()'` approach, this adds 11 bytes (javascript:) plus the bytes of the function name plus parameters to the page size. Mutiply this by 1000+ hrefs and thats 16kb+ added to the page size. (Yes, pagination would help but not for the user). So maybe in a different situation I'd go with the javascript: solution.
You can simply write like this also:-
Delete User
When calling the function, follow it by return false
example:
<input type="submit" value="Add" onclick="addNewPayment();return false;">
Create a page which contains two links- one at the top and one at the bottom. On clicking the top link, the page has to scroll down to the bottom of the page where bottom link is present. On clicking the bottom link, the page has to scroll up to the top of the page.
<a onclick="yourfunction()">
this will work fine . no need to add href="#"
You might want to check your CSS. In the example here: https://css-tricks.com/the-checkbox-hack/ there's position: absolute; top: -9999px;. This is particularly goofy on Chrome, as onclick="whatever" still jumps to the absolute position of the clicked element.
Removing position: absolute; top: -9999px;, for display: none; might help.

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?
function myJsFunc() {
alert("myJsFunc");
}
Run JavaScript Code
or
function myJsFunc() {
alert("myJsFunc");
}
Run JavaScript Code
I use javascript:void(0).
Three reasons. Encouraging the use of # amongst a team of developers inevitably leads to some using the return value of the function called like this:
function doSomething() {
//Some code
return false;
}
But then they forget to use return doSomething() in the onclick and just use doSomething().
A second reason for avoiding # is that the final return false; will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.
A third reason is that there are cases where the onclick event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my onclick (or on anything) in HTML markup look like this:
onclick="someFunc.call(this)"
OR
onclick="someFunc.apply(this, arguments)"
Using javascript:void(0) avoids all of the above headaches, and I haven't found any examples of a downside.
So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:
Use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.
OR
Use href="javascript:void(0)"
The second is clearly much easier to communicate.
Neither.
If you can have an actual URL that makes sense use that as the HREF. The onclick won't fire if someone middle-clicks on your link to open a new tab or if they have JavaScript disabled.
If that is not possible, then you should at least inject the anchor tag into the document with JavaScript and the appropriate click event handlers.
I realize this isn't always possible, but in my opinion it should be striven for in developing any public website.
Check out Unobtrusive JavaScript and Progressive enhancement (both Wikipedia).
Doing Link or Link or whatever else that contains an onclick attribute - was okay back five years ago, though now it can be a bad practice. Here's why:
It promotes the practice of obtrusive JavaScript - which has turned out to be difficult to maintain and difficult to scale. More on this in Unobtrusive JavaScript.
You're spending your time writing incredibly overly verbose code - which has very little (if any) benefit to your codebase.
There are now better, easier, and more maintainable and scalable ways of accomplishing the desired result.
The unobtrusive JavaScript way
Just don't have a href attribute at all! Any good CSS reset would take care of the missing default cursor style, so that is a non-issue. Then attach your JavaScript functionality using graceful and unobtrusive best practices - which are more maintainable as your JavaScript logic stays in JavaScript, instead of in your markup - which is essential when you start developing large scale JavaScript applications which require your logic to be split up into blackboxed components and templates. More on this in Large-scale JavaScript Application Architecture
Simple code example
// Cancel click event
$('.cancel-action').click(function(){
alert('Cancel action occurs!');
});
// Hover shim for Internet Explorer 6 and Internet Explorer 7.
$(document.body).on('hover','a',function(){
$(this).toggleClass('hover');
});
a { cursor: pointer; color: blue; }
a:hover,a.hover { text-decoration: underline; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="cancel-action">Cancel this action</a>
A blackboxed Backbone.js example
For a scalable, blackboxed, Backbone.js component example - see this working jsfiddle example here. Notice how we utilize unobtrusive JavaScript practices, and in a tiny amount of code have a component that can be repeated across the page multiple times without side-effects or conflicts between the different component instances. Amazing!
Notes
Omitting the href attribute on the a element will cause the element to not be accessible using tab key navigation. If you wish for those elements to be accessible via the tab key, you can set the tabindex attribute, or use button elements instead. You can easily style button elements to look like normal links as mentioned in Tracker1's answer.
Omitting the href attribute on the a element will cause Internet Explorer 6 and Internet Explorer 7 to not take on the a:hover styling, which is why we have added a simple JavaScript shim to accomplish this via a.hover instead. Which is perfectly okay, as if you don't have a href attribute and no graceful degradation then your link won't work anyway - and you'll have bigger issues to worry about.
If you want your action to still work with JavaScript disabled, then using an a element with a href attribute that goes to some URL that will perform the action manually instead of via an Ajax request or whatever should be the way to go. If you are doing this, then you want to ensure you do an event.preventDefault() on your click call to make sure when the button is clicked it does not follow the link. This option is called graceful degradation.
'#' will take the user back to the top of the page, so I usually go with void(0).
javascript:; also behaves like javascript:void(0);
I would honestly suggest neither. I would use a stylized <button></button> for that behavior.
button.link {
display: inline-block;
position: relative;
background-color: transparent;
cursor: pointer;
border: 0;
padding: 0;
color: #00f;
text-decoration: underline;
font: inherit;
}
<p>A button that looks like a <button type="button" class="link">link</button>.</p>
This way you can assign your onclick. I also suggest binding via script, not using the onclick attribute on the element tag. The only gotcha is the psuedo 3d text effect in older IEs that cannot be disabled.
If you MUST use an A element, use javascript:void(0); for reasons already mentioned.
Will always intercept in case your onclick event fails.
Will not have errant load calls happen, or trigger other events based on a hash change
The hash tag can cause unexpected behavior if the click falls through (onclick throws), avoid it unless it's an appropriate fall-through behavior, and you want to change the navigation history.
NOTE: You can replace the 0 with a string such as javascript:void('Delete record 123') which can serve as an extra indicator that will show what the click will actually do.
The first one, ideally with a real link to follow in case the user has JavaScript disabled. Just make sure to return false to prevent the click event from firing if the JavaScript executes.
Link
If you use Angular2, this way works:
<a [routerLink]="" (click)="passTheSalt()">Click me</a>.
See here https://stackoverflow.com/a/45465728/2803344
Neither if you ask me;
If your "link" has the sole purpose of running some JavaScript code it doesn't qualify as a link; rather a piece of text with a JavaScript function coupled to it. I would recommend to use a <span> tag with an onclick handler attached to it and some basic CSS to immitate a link. Links are made for navigation, and if your JavaScript code isn't for navigation it should not be an <a> tag.
Example:
function callFunction() { console.log("function called"); }
.jsAction {
cursor: pointer;
color: #00f;
text-decoration: underline;
}
<p>I want to call a JavaScript function <span class="jsAction" onclick="callFunction();">here</span>.</p>
Ideally you'd do this:
Link text
Or, even better, you'd have the default action link in the HTML, and you'd add the onclick event to the element unobtrusively via JavaScript after the DOM renders, thus ensuring that if JavaScript is not present/utilized you don't have useless event handlers riddling your code and potentially obfuscating (or at least distracting from) your actual content.
Using just # makes some funny movements, so I would recommend to use #self if you would like to save on typing efforts of JavaScript bla, bla,.
I use the following
Link
instead
Link
I recommend using a <button> element instead, especially if the control is supposed to produce a change in the data. (Something like a POST.)
It's even better if you inject the elements unobtrusively, a type of progressive enhancement. (See this comment.)
I agree with suggestions elsewhere stating that you should use regular URL in href attribute, then call some JavaScript function in onclick. The flaw is, that they automaticaly add return false after the call.
The problem with this approach is, that if the function will not work or if there will be any problem, the link will become unclickable. Onclick event will always return false, so the normal URL will not be called.
There's very simple solution. Let function return true if it works correctly. Then use the returned value to determine if the click should be cancelled or not:
JavaScript
function doSomething() {
alert( 'you clicked on the link' );
return true;
}
HTML
link text
Note, that I negate the result of the doSomething() function. If it works, it will return true, so it will be negated (false) and the path/to/some/URL will not be called. If the function will return false (for example, the browser doesn't support something used within the function or anything else goes wrong), it is negated to true and the path/to/some/URL is called.
# is better than javascript:anything, but the following is even better:
HTML:
For great justice
JavaScript:
$(function() {
$(".some-selector").click(myJsFunc);
});
You should always strive for graceful degradation (in the event that the user doesn't have JavaScript enabled...and when it is with specs. and budget). Also, it is considered bad form to use JavaScript attributes and protocol directly in HTML.
Unless you're writing out the link using JavaScript (so that you know it's enabled in the browser), you should ideally be providing a proper link for people who are browsing with JavaScript disabled and then prevent the default action of the link in your onclick event handler. This way those with JavaScript enabled will run the function and those with JavaScript disabled will jump to an appropriate page (or location within the same page) rather than just clicking on the link and having nothing happen.
Definitely hash (#) is better because in JavaScript it is a pseudoscheme:
pollutes history
instantiates new copy of engine
runs in global scope and doesn't respect event system.
Of course "#" with an onclick handler which prevents default action is [much] better. Moreover, a link that has the sole purpose to run JavaScript is not really "a link" unless you are sending user to some sensible anchor on the page (just # will send to top) when something goes wrong. You can simply simulate look and feel of link with stylesheet and forget about href at all.
In addition, regarding cowgod's suggestion, particularly this: ...href="javascript_required.html" onclick="... This is good approach, but it doesn't distinguish between "JavaScript disabled" and "onclick fails" scenarios.
I usually go for
Link description
It's shorter than javascript:void(0) and does the same.
I choose use javascript:void(0), because use this could prevent right click to open the content menu. But javascript:; is shorter and does the same thing.
I would use:
Link
Reasons:
This makes the href simple, search engines need it. If you use anything else ( such as a string), it may cause a 404 not found error.
When mouse hovers over the link, it doesn't show that it is a script.
By using return false;, the page doesn't jump to the top or break the back button.
Don't use links for the sole purpose of running JavaScript.
The use of href="#" scrolls the page to the top; the use of void(0) creates navigational problems within the browser.
Instead, use an element other than a link:
<span onclick="myJsFunc()" class="funcActuator">myJsFunc</span>
And style it with CSS:
.funcActuator {
cursor: default;
}
.funcActuator:hover {
color: #900;
}
So, when you are doing some JavaScript things with an <a /> tag and if you put href="#" as well, you can add return false at the end of the event (in case of inline event binding) like:
Run JavaScript Code
Or you can change the href attribute with JavaScript like:
Run JavaScript Code
or
Run JavaScript Code
But semantically, all the above ways to achieve this are wrong (it works fine though). If any element is not created to navigate the page and that have some JavaScript things associated with it, then it should not be a <a> tag.
You can simply use a <button /> instead to do things or any other element like b, span or whatever fits there as per your need, because you are allowed to add events on all the elements.
So, there is one benefit to use <a href="#">. You get the cursor pointer by default on that element when you do a href="#". For that, I think you can use CSS for this like cursor:pointer; which solves this problem also.
And at the end, if you are binding the event from the JavaScript code itself, there you can do event.preventDefault() to achieve this if you are using <a> tag, but if you are not using a <a> tag for this, there you get an advantage, you don't need to do this.
So, if you see, it's better not to use a tag for this kind of stuff.
It would be better to use jQuery,
$(document).ready(function() {
$("a").css("cursor", "pointer");
});
and omit both href="#" and href="javascript:void(0)".
The anchor tag markup will be like
<a onclick="hello()">Hello</a>
Simple enough!
Usually, you should always have a fall back link to make sure that clients with JavaScript disabled still has some functionality. This concept is called unobtrusive JavaScript.
Example... Let's say you have the following search link:
Search
You can always do the following:
var link = document.getElementById('searchLink');
link.onclick = function() {
try {
// Do Stuff Here
} finally {
return false;
}
};
That way, people with JavaScript disabled are directed to search.php while your viewers with JavaScript view your enhanced functionality.
If you happen to be using AngularJS, you can use the following:
Do some fancy JavaScript
Which will not do anything.
In addition
It will not take you to the top of the page, as with (#)
Therefore, you don't need to explicitly return false with JavaScript
It is short an concise
Depending on what you want to accomplish, you could forget the onclick and just use the href:
Link Text
It gets around the need to return false. I don't like the # option because, as mentioned, it will take the user to the top of the page. If you have somewhere else to send the user if they don't have JavaScript enabled (which is rare where I work, but a very good idea), then Steve's proposed method works great.
Link text
Lastly, you can use javascript:void(0) if you do not want anyone to go anywhere and if you don't want to call a JavaScript function. It works great if you have an image you want a mouseover event to happen with, but there's not anything for the user to click on.
I believe you are presenting a false dichotomy. These are not the only two options.
I agree with Mr. D4V360 who suggested that, even though you are using the anchor tag, you do not truly have an anchor here. All you have is a special section of a document that should behave slightly different. A <span> tag is far more appropriate.
I tried both in google chrome with the developer tools, and the id="#" took 0.32 seconds. While the javascript:void(0) method took only 0.18 seconds. So in google chrome, javascript:void(0) works better and faster.
I personally use them in combination. For example:
HTML
Link
with little bit of jQuery
$('a[href="#"]').attr('href','javascript:void(0);');
or
$('a[href="#"]').click(function(e) {
e.preventDefault();
});
But I'm using that just for preventing the page jumping to the top when the user clicks on an empty anchor. I'm rarely using onClick and other on events directly in HTML.
My suggestion would be to use <span> element with the class attribute instead of
an anchor. For example:
<span class="link">Link</span>
Then assign the function to .link with a script wrapped in the body and just before the </body> tag or in an external JavaScript document.
<script>
(function($) {
$('.link').click(function() {
// do something
});
})(jQuery);
</script>
*Note: For dynamically created elements, use:
$('.link').on('click', function() {
// do something
});
And for dynamically created elements which are created with dynamically created elements, use:
$(document).on('click','.link', function() {
// do something
});
Then you can style the span element to look like an anchor with a little CSS:
.link {
color: #0000ee;
text-decoration: underline;
cursor: pointer;
}
.link:active {
color: red;
}
Here's a jsFiddle example of above aforementioned.
On a modern website the use of href should be avoided if the element is only doing JavaScript functionality (not a real link).
Why?
The presence of this element tells the browser that this is a link with a destination.
With that, the browser will show the Open In New Tab / Window function (also triggered when you use shift+click).
Doing so will result in opening the same page without the desired function triggered (resulting in user frustration).
In regards to IE:
As of IE8, element styling (including hover) works if the doctype is set. Other versions of IE are not really to worry about anymore.
Only Drawback:
Removing HREF removes the tabindex.
To overcome this, you can use a button that's styled as a link or add a tabindex attribute using JS.
When I've got several faux-links, I prefer to give them a class of 'no-link'.
Then in jQuery, I add the following code:
$(function(){
$('.no-link').click(function(e){
e.preventDefault();
});
});
And for the HTML, the link is simply
Faux-Link
I don't like using Hash-Tags unless they're used for anchors, and I only do the above when I've got more than two faux-links, otherwise I go with javascript:void(0).
Faux-Link
Typically, I like to just avoid using a link at all and just wrap something around in a span and use that as a way to active some JavaScript code, like a pop-up or a content-reveal.
It's nice to have your site be accessible by users with JavaScript disabled, in which case the href points to a page that performs the same action as the JavaScript being executed. Otherwise I use "#" with a "return false;" to prevent the default action (scroll to top of the page) as others have mentioned.
Googling for "javascript:void(0)" provides a lot of information on this topic. Some of them, like this one mention reasons to NOT use void(0).

Categories