HTML/JavaScript Linking - javascript

This question may have been asked before, but I had trouble finding an answer, since I didn't quite know what search terms to use.
In HTML, how do you make a link go a place, but execute JavaScript instead when it is clicked? Right now, I have a link that's somewhat like this:
Stuff
But, the thing is, when someone right clicks the link, I want them to be able to copy a direct URL to the link. Also, if someone's browser does not support JavaScript, or they have it disabled, I would still like them to be able to reach the page. Is it just
Stuff?
Or is there something more complicated?
Thanks!

Stuff
Make sure that the dosuff function returns false if you want the link to not be followed when the script runs.
(The 'javascript:' is pointless. It labels a loop, but you don't have a loop. See the HTML spec for how to specify which language is being used in the intrinsic event handler attributes — better yet, use unobtrusive JavaScript and progressive enhancement).

You need to let the event return false to block the default action.
<a href="http://example.com" onclick="doSomething(); return false;">

Related

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

It is wrong or a bad practice to use "javascript://" as links to prevent action?

I just saw this question
and it reminds me of something I usually do to prevent the default action of some link:
something
Then I handle it with jQuery click function. I already saw in some places people using
something
I know the better way is using
e.preventDefault();
But is it wrong or a bad practice to do what I do? How this actually works?
It's a bit unfortunate because if the user Ctrl+clicks or right clicks and says "Open in New Tab," they will get a completely blank page.
Using something plus preventDefault is better, since in that case Ctrl+click just takes them back to the page they were on.
Of course, the very best is if you can have the href point to a page that is actually meaningful, with the JavaScript being a progressive enhancement to the experience that overrides that meaningful default. A great example of this is popup windows, but with a bit more work anything can be made to do this.
It is bad practice because a better mechanism exists and that is event.preventDefault().
Also, the javascript: pseudo protocol should only be used for bookmarklets.

What is the proper use of the anchor tag?

I've read how the anchor tag is holy, it should not be used with javascript:
Popup
that it should ONLY be used for a link to another page:
Take me over there
So what is the proper use of the anchor tag with javascript? Should I be using:
Energize!
or some other variant? I'm somewhat confused by different views on the subject. Also is it only SEO that I should be worried about if making the href a javascript piece? Or is it more of a proper web standards compliance deal?
Thoughts? Hopefully I'm not the only one confused.
You are not alone Jakub; even the biggest WWW companies use different approaches.
However based on experiences since Netscape days I wouldn't use :
Popup
which can make some troubles on some browsers, like opening an empty page or breaking the event order on the current page.
However;
Energize!
or;
Link
don't make a serious trouble and are ok to use. Note that the prior one may reset the scroll to the top.
You should use meaningful link targets and unobtrusive javascript wherever possible, but this is not always possible in real life examples. It's not a defined standard, but a method highly agreed by most of the web developers.
When it comes to standards, there is one related with this situation:
You should consider using a 'button' for inputs which doesn't really send the visitor to a page, but does an operation. This is also important for SEO.
As #Sime says (and it should be an answer really), it is considered "bad practise" to now directly reference javascript in any HTML object. So in these cases you attach the event using something like jQuery using the concepts laid out in "unobtrusive javascript".
As you mention another consideration is SEO and accessibility. If SEO is important to your site, make sure that the site is fully navigable using just standard links. Again you can manage this using "unobtrusive javascript", etc.
I've always gone with using an anchor as normal (i.e. specify either an alternate url that is another location where the user could perform what's being done through javascript, or use javascript:void() / #) then use the onclick event for anything you want executed.
You could also use a <span> if you're that worried about conformance, just would need to perhaps style it (change cursor, perhaps color as well) to make it visually obvious you're making it an action.
I think Facebook is the best-case example. Almost all of their links are javascript tied in, but they also have a "backup" page for those that either have disallowed javascript or don't have it (the later, in this day and age, being far less common). Take a look at a module that reacts like you'd like yours to and see how they've done it. They also invested a bunch of work in best-practices that you can benefit from.
If anything, you should bind your anchor links to javascript methods only by using unobtrusive javascript like Paul mentioned.
This means, using separation of concerns and leaving your markup being just that, html markup:
<a id="Jolter">Energize!</a>
and later
<script type="text/javascript">
$(document).ready(function(){
$("#Jolter").click(function(){
// doStuffHere ...
});
});
</script>

Empty-linked anchor

I have an anchor that doesn't go anywhere but has an onclick (e.g. <a onclick="..."></a>). My question pertains to the href attribute. What should I put for the value?
If I simply omit href, the anchor doesn't have the appropriate decoration--the mouse pointer icon doesn't change when the mouse is put over it.
If I use href="#", then the window scrolls to the top of the page when the link is clicked.
If I use href="javascript:..." and put the value of onclick proceeding javascript:, the page is left and the address bar contains the Javascript when the link is clicked.
When I refer to browser behavior, I'm referring to Chrome, which I'm testing it in to start with.
What should I be putting for href when the anchor isn't an actual link but exists only to have the onclick perform behavior?
Ideally you would have an option for those with Javascript disabled:
do the option!
If you're not into that sort of thing, although you really should be, the most common way is to use the pound but then cancel the event to prevent the default action from happening, like so:
do something
But then you have to make sure do_something returns false. (or you can just add return false; at the end of the click handler, but this gets even more unsightly fast)
Although, to be honest, you really shouldn't have inline Javascript attributes to begin with. They are bad practice, a nightmare to maintain, and there are much better alternatives out there.
EDIT: In response to your comment, the alternative is unobtrusive javascript:
"Unobtrusive JavaScript" is an emerging technique in the JavaScript programming language, as used on the World Wide Web. Though the term is not formally defined, its basic principles are generally understood to include:
Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
Progressive enhancement to support user agents that may not support advanced JavaScript functionality
Read the page for some examples.
In your onclick handler, add this to the end:
return false;
This will cancel the default processing (i.e. following the link) and you can put whatever you want in the href (the # is as good as any).
txt
I prefer to drop the href (it's not required according to W3C spec) if it's not used. To get the expected mouse cursor, use CSS!
<style type="text/css">
a { cursor: pointer; }
</style>
<a onclick="go();">link</a>
Foo
Short, descriptive and does not jump like #.
There are two ways of doing this, if the id tag of the link is link, you can use href="#"in your HTML, and then in your JavaScript have:
$('#link').click(function(evt) {
// code goes here
evt.preventDefault();
});
This prevents the browser's normal behavior. Or
$('#link').click(function(evt) {
// code goes here
return false;
});

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